当前位置: 首页>>代码示例>>C#>>正文


C# HMACSHA256.Initialize方法代码示例

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


在下文中一共展示了HMACSHA256.Initialize方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: GenerateSaSToken

        private static string GenerateSaSToken(Uri uri)
        {
            var targetUri = WebUtility.UrlEncode(uri.ToString().ToLower()).ToLower();
            
            var expiresOnDate = Convert.ToInt64(DateTime.UtcNow.Subtract
                (new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds) + 60 * 60;
            var toSign = targetUri + "\n" + expiresOnDate;

            var keyBytes = Encoding.UTF8.GetBytes(SasKeyValue);
            var mac = new HMACSHA256(keyBytes);
            mac.Initialize();
            var rawHmac = mac.ComputeHash(Encoding.UTF8.GetBytes(toSign));
            var signature = WebUtility.UrlEncode(Convert.ToBase64String(rawHmac));

            var token = "SharedAccessSignature sr=" + targetUri + "&sig=" 
                    + signature + "&se=" + expiresOnDate + "&skn=" + SasKeyName;
            return token;
        }
开发者ID:faisalishak,项目名称:azure-notificationhubs-samples,代码行数:18,代码来源:NotificationHub.cs

示例3: SignHmac

 /// <summary>
 /// Compute hmac of input content with key.
 /// </summary>
 /// <param name="key">Hmac key</param>
 /// <param name="content">Bytes to be hmac computed</param>
 /// <returns>Computed hmac of input content</returns>
 private byte[] SignHmac(byte[] key, byte[] content)
 {
     HMACSHA256 hmac = new HMACSHA256(key);
     hmac.Initialize();
     return hmac.ComputeHash(content);
 }
开发者ID:minio,项目名称:minio-dotnet,代码行数:12,代码来源:V4Authenticator.cs

示例4: PBKDF2_SHA256

        /// <summary>
        /// Compute PBKDF2 using HMAC-SHA256 as the PRF, and write the output to derivedKey.
        /// </summary>
        private static void PBKDF2_SHA256(HMACSHA256 mac, byte[] password, byte[] salt, int saltLength, long iterationCount, byte[] derivedKey, int derivedKeyLength)
        {
            if (derivedKeyLength > (Math.Pow(2, 32) - 1) * 32)
            {
                throw new ArgumentException("Requested key length too long");
            }

            var U = new byte[32];
            var T = new byte[32];
            var saltBuffer = new byte[saltLength + 4];

            var blockCount = (int)Math.Ceiling((double)derivedKeyLength / 32);
            var r = derivedKeyLength - (blockCount - 1) * 32;

            Buffer.BlockCopy(salt, 0, saltBuffer, 0, saltLength);

            for (int i = 1; i <= blockCount; i++)
            {
                saltBuffer[saltLength + 0] = (byte)(i >> 24);
                saltBuffer[saltLength + 1] = (byte)(i >> 16);
                saltBuffer[saltLength + 2] = (byte)(i >> 8);
                saltBuffer[saltLength + 3] = (byte)(i);

                mac.Initialize();
                mac.TransformFinalBlock(saltBuffer, 0, saltBuffer.Length);
                Buffer.BlockCopy(mac.Hash, 0, U, 0, U.Length);
                Buffer.BlockCopy(U, 0, T, 0, 32);

                for (long j = 1; j < iterationCount; j++)
                {
                    mac.TransformFinalBlock(U, 0, U.Length);
                    Buffer.BlockCopy(mac.Hash, 0, U, 0, U.Length);

                    for (int k = 0; k < 32; k++)
                    {
                        T[k] ^= U[k];
                    }
                }

                Buffer.BlockCopy(T, 0, derivedKey, (i - 1) * 32, (i == blockCount ? r : 32));
            }
        }
开发者ID:paragonie-scott,项目名称:Scrypt,代码行数:45,代码来源:ScryptEncoder.cs

示例5: verify

        private static bool verify(String consumerSecret, String encodedPayload, String encodedSignature)            
        {
            if (consumerSecret == null || consumerSecret.Trim().Length == 0)
            {
                throw new System.ArgumentException("secret is null, did you set your environment variable CANVAS_CONSUMER_SECRET?");            
            }
                       
            try {
               byte[] key = Encoding.UTF8.GetBytes(consumerSecret);
               HMACSHA256 hmacKey = new HMACSHA256(key);
               hmacKey.Initialize();
               byte[] algorithmBytes = Encoding.UTF8.GetBytes(encodedPayload);
               byte[] rawHmac = hmacKey.ComputeHash(algorithmBytes);
               string result = Convert.ToBase64String(rawHmac);

               return (result == Uri.UnescapeDataString(encodedSignature)) ? true : false;   
              
            } catch (System.Exception e) {
                throw new System.Exception("Verify failed.", e.InnerException);
            }
        }
开发者ID:bugude,项目名称:.Net_Canvas_Classes,代码行数:21,代码来源:SignedRequest.cs

示例6: HmacEval

		private static void HmacEval(byte[] pbKey, byte[] pbMsg,
			byte[] pbExpc, string strID)
		{
			using(HMACSHA256 h = new HMACSHA256(pbKey))
			{
				h.TransformBlock(pbMsg, 0, pbMsg.Length, pbMsg, 0);
				h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

				byte[] pbHash = h.Hash;
				if(!MemUtil.ArraysEqual(pbHash, pbExpc))
					throw new SecurityException("HMAC-SHA-256-" + strID);

				// Reuse the object
				h.Initialize();
				h.TransformBlock(pbMsg, 0, pbMsg.Length, pbMsg, 0);
				h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

				pbHash = h.Hash;
				if(!MemUtil.ArraysEqual(pbHash, pbExpc))
					throw new SecurityException("HMAC-SHA-256-" + strID + "-R");
			}
		}
开发者ID:joshuadugie,项目名称:KeePass-2.x,代码行数:22,代码来源:SelfTest.cs

示例7: Pbkdf2

        public static byte[] Pbkdf2(byte[] password, byte[] salt, int iterations = Pbkdf2Iterations)
        {
            /*
            // Algorithm Credits to https://github.com/vexocide
            //
            // Implements PBKDF2WithHmacSHA256 in Java. Beautifully Amazing.
            using (var mac = new HMACSHA256(password))
            {
                mac.TransformBlock(salt, 0, salt.Length, salt, 0);
                byte[] i = { 0, 0, 0, 1 };
                mac.TransformFinalBlock(i, 0, i.Length);
                byte[] t = mac.Hash;
                mac.Initialize();

                byte[] u = t;
                for (uint c = 2; c <= iterations; c++)
                {
                    t = mac.ComputeHash(t);
                    for (int j = 0; j < mac.HashSize / 8; j++)
                    {
                        u[j] ^= t[j];
                    }
                }

                return u;
            }
*/
#if STANDARD
            using( var macSalt = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, password) )
#endif
            using ( var mac = new HMACSHA256(password) )
            {
#if STANDARD
                macSalt.AppendData(salt);
#else
                mac.TransformBlock(salt, 0, salt.Length, salt, 0);
#endif
                byte[] i = {0, 0, 0, 1};
#if STANDARD
                macSalt.AppendData(i);
#else
                mac.TransformFinalBlock(i, 0, i.Length);
#endif
#if STANDARD
                byte[] t = macSalt.GetHashAndReset();
#else
                byte[] t = mac.Hash;
                mac.Initialize();
#endif

                byte[] u = t;

                for( uint c = 2; c <= iterations; c++ )
                {
                    t = mac.ComputeHash(t);
                    for( int j = 0; j < mac.HashSize / 8; j++ )
                    {
                        u[j] ^= t[j];
                    }
                }

                return u;
            }
        }
开发者ID:fjsnogueira,项目名称:RethinkDb.Driver,代码行数:64,代码来源:Crypto.cs


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