• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Cryptography.HMACSHA256类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Security.Cryptography.HMACSHA256的典型用法代码示例。如果您正苦于以下问题:C# HMACSHA256类的具体用法?C# HMACSHA256怎么用?C# HMACSHA256使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



HMACSHA256类属于System.Security.Cryptography命名空间,在下文中一共展示了HMACSHA256类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Main

		public static void Main (string[] args)
		{
			var host = "https://api.coinbase.com/";
			var apiKey = "yourApiKey";
			var apiSecret = "youApiSecret";

			var unixTimestamp = (Int32)(DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1))).TotalSeconds;
			var currency = "USD";
			var message = string.Format ("{0}GET/v2/prices/spot?currency={1}", unixTimestamp.ToString (), currency);

			byte[] secretKey = Encoding.UTF8.GetBytes (apiSecret);
			HMACSHA256 hmac = new HMACSHA256 (secretKey);
			hmac.Initialize ();
			byte[] bytes = Encoding.UTF8.GetBytes (message);
			byte[] rawHmac = hmac.ComputeHash (bytes);
			var signature = rawHmac.ByteArrayToHexString ();

			var price = host
				.AppendPathSegment ("v2/prices/spot")
				.SetQueryParam ("currency", currency)
				.WithHeader ("CB-ACCESS-SIGN", signature)
				.WithHeader ("CB-ACCESS-TIMESTAMP", unixTimestamp)
				.WithHeader ("CB-ACCESS-KEY", apiKey)
				.GetJsonAsync<dynamic> ()
				.Result;

			Console.WriteLine (price.ToString (Formatting.None));
			Console.ReadLine ();
		}
开发者ID:iYalovoy,项目名称:demibyte.coinbase,代码行数:29,代码来源:Program.cs


示例2: PHash

        private static byte[] PHash(byte[] secret, byte[] seed, int iterations)
        {
            using (HMACSHA256 hmac = new HMACSHA256(secret))
            {
                byte[][] a = new byte[iterations + 1][];

                a[0] = seed;

                for (int i = 0; i < iterations; i++)
                {
                    a[i + 1] = hmac.ComputeHash(a[i]);
                }

                byte[] prf = new byte[iterations * 32];

                byte[] buffer = new byte[32 + seed.Length];
                Buffer.BlockCopy(seed, 0, buffer, 32, seed.Length);

                for (int i = 0; i < iterations; i++)
                {
                    Buffer.BlockCopy(a[i + 1], 0, buffer, 0, 32);

                    byte[] hash = hmac.ComputeHash(buffer);

                    Buffer.BlockCopy(hash, 0, prf, 32 * i, 32);
                }

                return prf;
            }
        }
开发者ID:EugenDueck,项目名称:netmq,代码行数:30,代码来源:SHA256PRF.cs


示例3: BuildBase64Signature

        public static string BuildBase64Signature(
                string apiKey,
                string appId,
                Uri rawUri,
                HttpMethod httpMethod,
                HttpContent content,
                string nonce,
                string requestTimeStamp
            )
        {
            var requestUri = HttpUtility.UrlEncode(rawUri.AbsoluteUri.ToLower());
            var requestHttpMethod = httpMethod.Method;

            // Get the content string out of the content.
            string requestContentBase64String = ComputeBase64RequestContent(content);

            // Rebuild the signature raw data.
            var signatureRawData =
            $"{appId}{requestHttpMethod}{requestUri}{requestTimeStamp}{nonce}{requestContentBase64String}";

            // Get the api key bytes.
            var secretKeyBytes = Convert.FromBase64String(apiKey);

            // Get the signature.
            var signature = Encoding.UTF8.GetBytes(signatureRawData);

            // Create HMAC SHA class with key data.
            using (var hmac = new HMACSHA256(secretKeyBytes))
            {
                return Convert.ToBase64String(hmac.ComputeHash(signature));
            }
        }
开发者ID:SamStrong,项目名称:WebAPI.HMAC,代码行数:32,代码来源:HMACHelper.cs


示例4: EncryptAesCbc

        /// <summary>
        /// Encrypt a message using AES in CBC (cipher-block chaining) mode.
        /// </summary>
        /// <param name="plaintext">The message (plaintext) to encrypt</param>
        /// <param name="key">An AES key</param>
        /// <param name="iv">The IV to use or null to use a 0 IV</param>
        /// <param name="addHmac">When set, a SHA256-based HMAC (HMAC256) of 32 bytes using the same key is added to the plaintext
        /// before it is encrypted.</param>
        /// <returns>The ciphertext derived by encrypting the orignal message using AES in CBC mode</returns>
        public static byte[] EncryptAesCbc(byte[] plaintext, byte[] key, byte[] iv = null, bool addHmac = false)
        {
            using (Aes aes =Aes.Create())
//            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.Key = key;
                if (iv == null)
                    iv = NullIv;
                aes.Mode = CipherMode.CBC;
                aes.IV = iv;

                // Encrypt the message with the key using CBC and InitializationVector=0
                byte[] cipherText;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintext, 0, plaintext.Length);
                        if (addHmac)
                        {
                            byte[] hmac = new HMACSHA256(key).ComputeHash(plaintext);
                            cs.Write(hmac, 0, hmac.Length);
                        }
                        cs.Flush();
                    }
                    cipherText = ciphertext.ToArray();
                }

                return cipherText;
            }
        }
开发者ID:Microsoft,项目名称:StopGuessing,代码行数:40,代码来源:Encryption.cs


示例5: GenerateHMACSHA256AuthorisationToken

        public static string GenerateHMACSHA256AuthorisationToken(string sessionToken, string sharedSecret, out string dateString)
        {
            if (String.IsNullOrWhiteSpace(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }

            if (String.IsNullOrWhiteSpace(sessionToken))
            {
                throw new ArgumentNullException("sessionToken");
            }

            // Generate UTC ISO 8601 date string.
            dateString = DateTime.UtcNow.ToString("o");
            // 1. Combine the Token and current date time in UTC using ISO 8601 format.
            byte[] messageBytes = Encoding.ASCII.GetBytes(sessionToken + ":" + dateString);
            // 2. Calculate the HMAC SHA 256 using the Consumer Secret and then Base64 encode.
            byte[] keyBytes = Encoding.ASCII.GetBytes(sharedSecret);
            string hmacsha256EncodedString;

            using (HMACSHA256 hmacsha256 = new HMACSHA256(keyBytes))
            {
                byte[] hashMessage = hmacsha256.ComputeHash(messageBytes);
                hmacsha256EncodedString = Convert.ToBase64String(hashMessage);
            }

            // 3. Combine the Token with the resulting string from above separated by a colon.
            string combinedMessage = sessionToken + ":" + hmacsha256EncodedString;
            // 4. Base64 encode this string.
            string base64EncodedString = Convert.ToBase64String(Encoding.ASCII.GetBytes(combinedMessage));

            // 5. Prefix this string with the Authentication Method and a space.
            return AuthorisationMethod.HMACSHA256.ToString() + " " + base64EncodedString;
        }
开发者ID:ZiNETHQ,项目名称:sif3-framework-dotnet,代码行数:34,代码来源:AuthenticationUtils.cs


示例6: EncodeFile

 // Computes a keyed hash for a source file, creates a target file with the keyed hash
 // prepended to the contents of the source file, then decrypts the file and compares
 // the source and the decrypted files.
 public static void EncodeFile(byte[] key, String sourceFile, String destFile)
 {
     // Initialize the keyed hash object.
     HMACSHA256 myhmacsha256 = new HMACSHA256(key);
     FileStream inStream = new FileStream(sourceFile, FileMode.Open);
     FileStream outStream = new FileStream(destFile, FileMode.Create);
     // Compute the hash of the input file.
     byte[] hashValue = myhmacsha256.ComputeHash(inStream);
     // Reset inStream to the beginning of the file.
     inStream.Position = 0;
     // Write the computed hash value to the output file.
     outStream.Write(hashValue, 0, hashValue.Length);
     // Copy the contents of the sourceFile to the destFile.
     int bytesRead;
     // read 1K at a time
     byte[] buffer = new byte[1024];
     do
     {
         // Read from the wrapping CryptoStream.
         bytesRead = inStream.Read(buffer, 0, 1024);
         outStream.Write(buffer, 0, bytesRead);
     } while (bytesRead > 0);
     myhmacsha256.Clear();
     // Close the streams
     inStream.Close();
     outStream.Close();
     return;
 }
开发者ID:shi5588,项目名称:shi5588,代码行数:31,代码来源:Program.cs


示例7: JsonWebToken

 static JsonWebToken()
 {
     HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>>
                      {
                          {JwtHashAlgorithm.RS256, (key, value) =>
                                                   {
                                                       using (var sha = new HMACSHA256(key))
                                                       {
                                                           return sha.ComputeHash(value);
                                                       }
                                                   }
                          },
                          {JwtHashAlgorithm.HS384, (key, value) =>
                                                   {
                                                       using (var sha = new HMACSHA384(key))
                                                       {
                                                           return sha.ComputeHash(value);
                                                       }
                                                   }
                          },
                          {JwtHashAlgorithm.HS512, (key, value) =>
                                                   {
                                                       using (var sha = new HMACSHA512(key))
                                                       {
                                                           return sha.ComputeHash(value);
                                                       }
                                                   }
                          }
                      };
 }
开发者ID:austinejei,项目名称:sidekick,代码行数:30,代码来源:JsonWebToken.cs


示例8: Verify

        public static FacebookSignedRequestResult Verify(string appSecret, string signedRequest)
        {
            var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(appSecret));
            var javaScriptSerializer = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(signedRequest) || !signedRequest.Contains("."))
            {
                return new FacebookSignedRequestResult(false, string.Empty, string.Empty, null, null);
            }

            var split = signedRequest.Split('.');
            var providedPayloadHash = split[0];
            var requestPayload = split[1];

            byte[] hashBytes = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(requestPayload));
            string calculatedHash = Convert.ToBase64String(hashBytes);
            string modifiedBase64Hash = ConvertToModifiedBase64(calculatedHash);

            string payloadBase64 = ConvertFromModifiedBase64(requestPayload);
            byte[] payloadBytes = Convert.FromBase64String(payloadBase64);
            string payloadJson = Encoding.UTF8.GetString(payloadBytes);

            var request = javaScriptSerializer.Deserialize<FacebookSignedRequest>(payloadJson);

            return new FacebookSignedRequestResult(providedPayloadHash == modifiedBase64Hash, request.user_id, request.app_data, request.page, request.user);
        }
开发者ID:Blueblau,项目名称:FacebookFoundation,代码行数:26,代码来源:FacebookSignedRequestVerifier.cs


示例9: GetAlgorithmByFunctionName

 /// <summary>
 /// Every time is created new instance of class to guarantee thread safety
 /// </summary>
 /// <param name="function"></param>
 /// <returns></returns>
 private HMAC GetAlgorithmByFunctionName(string function)
 {
     HMAC a;
     switch(Util.Convertion.EnumNameToValue<HMACFunction>(function))
     {
         case HMACFunction.HMACMD5:
             a = new HMACMD5();
             break;
         case HMACFunction.HMACSHA1:
             a = new HMACSHA1();
             break;
         case HMACFunction.HMACSHA256:
             a = new HMACSHA256();
             break;
         case HMACFunction.HMACSHA384:
             a = new HMACSHA384();
             break;
         case HMACFunction.HMACSHA512:
             a = new HMACSHA512();
             break;
         default:
             throw new ArgumentException("Unknown function", "function");
     }
     return a;
 }
开发者ID:danni95,项目名称:Core,代码行数:30,代码来源:HMACProvider.cs


示例10: ComputeHmac

 public byte[] ComputeHmac(string input)
 {
     using (var hmac = new HMACSHA256(this.signingKey))
     {
         return hmac.ComputeHash(this.encoding.GetBytes(input));
     }
 }
开发者ID:ssankar1234,项目名称:stormpath-sdk-dotnet,代码行数:7,代码来源:HmacGenerator.cs


示例11: AuthorizationHeader

        public static string AuthorizationHeader(
            string storageAccount, 
            string storageKey, 
            string method, 
            DateTime now,
            HttpRequestMessage request, 
            string ifMatch = "", 
            string contentMD5 = "", 
            string size = "", 
            string contentType = "")
        {
            string stringToSign = string.Format(
                "{0}\n\n\n{1}\n{5}\n{6}\n\n\n{2}\n\n\n\n{3}{4}", 
                method, 
                (size == string.Empty) ? string.Empty : size, 
                ifMatch, 
                GetCanonicalizedHeaders(request), 
                GetCanonicalizedResource(request.RequestUri, storageAccount), 
                contentMD5, 
                contentType);

            byte[] signatureBytes = Encoding.UTF8.GetBytes(stringToSign);
            string authorizationHeader;
            using (HMACSHA256 hmacsha256 = new HMACSHA256(Convert.FromBase64String(storageKey)))
            {
                authorizationHeader = "SharedKey " + storageAccount + ":"
                                      + Convert.ToBase64String(hmacsha256.ComputeHash(signatureBytes));
            }

            return authorizationHeader;
        }
开发者ID:dsgouda,项目名称:buildtools,代码行数:31,代码来源:AzureHelper.cs


示例12: ComputeHmac

 public byte[] ComputeHmac(byte[] sessionKey, byte[] encrpytedData)
 {
     using (var hmac = new HMACSHA256(sessionKey))
     {
         return hmac.ComputeHash(encrpytedData);
     }
 }
开发者ID:wasteland540,项目名称:SecureFileShare,代码行数:7,代码来源:HybridRsaAes.cs


示例13: CreateToken

 public static string CreateToken(string message, string key)
 {
     var myhmacsha1 = new HMACSHA256(Encoding.ASCII.GetBytes(key));
     var byteArray = Encoding.ASCII.GetBytes(message);
     var stream = new MemoryStream(byteArray);
     return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + $"{e:x2}", s => s);
 }
开发者ID:MikkelJR,项目名称:Quickpay,代码行数:7,代码来源:Cryptography.cs


示例14: sign

        bool m_isCheckAmazonAwsInstancesEmailWasSent = false;  // to avoid sending the same warning email many times; send only once

        //# Key derivation functions. See: 
        //# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
        internal byte[] sign(byte[] key, string msg)
        {
            HMACSHA256 hmac = new HMACSHA256(key);
            var computedDigest = hmac.ComputeHash(Encoding.UTF8.GetBytes(msg));
            return computedDigest;
            //return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest();
        }
开发者ID:gyantal,项目名称:SQLab,代码行数:11,代码来源:CheckAmazonAwsInstances.cs


示例15: ComputeHash

 /// <summary>
 /// Computes the <see cref="HMACSHA256"/> hash of the string using the given
 /// salt and <c cref="Encoding.UTF8">UTF8 Encoding</c>
 /// </summary>
 /// <param name="plainText"></param>
 /// <param name="salt"></param>
 /// <returns></returns>
 public static byte[] ComputeHash(this string plainText, string salt)
 {
     var encoding = Encoding.UTF8;
     using (var sha = new HMACSHA256(Encoding.UTF8.GetBytes(salt))) {
         return sha.ComputeHash(encoding.GetBytes(plainText));
     }
 }
开发者ID:tmont,项目名称:portoa,代码行数:14,代码来源:SecurityExtensions.cs


示例16: GeneratePrivateKey

 /// <summary>
 ///  Generates the private key for a specific domain, based on the master key. 
 /// </summary>
 /// <returns>
 ///  The private key. 
 /// </returns>
 /// <param name='masterKey'>
 ///  The master key. 
 /// </param>
 /// <param name='domain'>
 ///  The domain. 
 /// </param>
 public byte[] GeneratePrivateKey(byte[] masterKey, string domain)
 {
     using(HMACSHA256 hmac = new HMACSHA256(masterKey))
     {
         return hmac.ComputeHash(Encoding.UTF8.GetBytes(domain));
     }
 }
开发者ID:brownj,项目名称:SqrlNet,代码行数:19,代码来源:HmacGenerator.cs


示例17: DecodeFile

 // Decrypt the encoded file and compare to original file.
 public static bool DecodeFile(byte[] key, String sourceFile)
 {
     // Initialize the keyed hash object.
     HMACSHA256 hmacsha256 = new HMACSHA256(key);
     // Create an array to hold the keyed hash value read from the file.
     byte[] storedHash = new byte[hmacsha256.HashSize / 8];
     // Create a FileStream for the source file.
     FileStream inStream = new FileStream(sourceFile, FileMode.Open);
     // Read in the storedHash.
     inStream.Read(storedHash, 0, storedHash.Length);
     // Compute the hash of the remaining contents of the file.
     // The stream is properly positioned at the beginning of the content,
     // immediately after the stored hash value.
     byte[] computedHash = hmacsha256.ComputeHash(inStream);
     // compare the computed hash with the stored value
     for (int i = 0; i < storedHash.Length; i++)
     {
         if (computedHash[i] != storedHash[i])
         {
             Console.WriteLine("Hash values differ! Encoded file has been tampered with!");
             return false;
         }
     }
     Console.WriteLine("Hash values agree -- no tampering occurred.");
     return true;
 }
开发者ID:shi5588,项目名称:shi5588,代码行数:27,代码来源:Program.cs


示例18: HMACSHA256

 public static byte[] HMACSHA256(byte[] key, byte[] data)
 {
     using (var hmac = new HMACSHA256(key))
     {
         return hmac.ComputeHash(data);
     }
 }
开发者ID:lontivero,项目名称:BitcoinLite,代码行数:7,代码来源:Hashes.cs


示例19: hmacSHA256

 static byte[] hmacSHA256(String data, String key)
 {
     using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key)))
     {
         return hmac.ComputeHash(Encoding.ASCII.GetBytes(data));
     }
 }
开发者ID:regiondo-dev,项目名称:api,代码行数:7,代码来源:Sha256Example.cs


示例20: SendAsync

		protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			string requestContentBase64String = string.Empty;
			string requestUri = System.Web.HttpUtility.UrlEncode(request.RequestUri.AbsoluteUri.ToLower());

			//Checking if the request contains body, usually will be null wiht HTTP GET
			if (request.Content != null)
			{
				using (var md5 = MD5.Create())
				{
					var content = await request.Content.ReadAsByteArrayAsync();
				
					//Hashing the request body, any change in request body will result in different hash, we'll incure message integrity
					var requestContentHash = md5.ComputeHash(content);
					requestContentBase64String = Convert.ToBase64String(requestContentHash);
				}
			}

			//create random nonce for each request
			var nonce = Guid.NewGuid().ToString("N");

			//Creating the raw signature string
			var signatureRawData = string.Concat(_apiKey, "POST", requestUri, nonce, requestContentBase64String);	
			var secretKeyByteArray = Convert.FromBase64String(_apiSecret);
			var signature = Encoding.UTF8.GetBytes(signatureRawData);
			using (var hmac = new HMACSHA256(secretKeyByteArray))
			{
				var signatureBytes = hmac.ComputeHash(signature);
				var requestSignatureBase64String = Convert.ToBase64String(signatureBytes);

				//Setting the values in the Authorization header using custom scheme (amx)
				request.Headers.Authorization = new AuthenticationHeaderValue("amx", string.Format("{0}:{1}:{2}", _apiKey, requestSignatureBase64String, nonce));
			}
			return await base.SendAsync(request, cancellationToken);
		}
开发者ID:CryptopiaNZ,项目名称:CryptopiaApi-Csharp,代码行数:35,代码来源:AuthDelegatingHandler.cs



注:本文中的System.Security.Cryptography.HMACSHA256类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Cryptography.HMACSHA512类代码示例发布时间:2022-05-26
下一篇:
C# Cryptography.HMACSHA1类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap