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


C# HMACSHA1.ComputeHash方法代码示例

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


在下文中一共展示了HMACSHA1.ComputeHash方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ComputeCombinedKey

 public static byte[] ComputeCombinedKey(byte[] requestorEntropy, byte[] issuerEntropy, int keySizeInBits)
 {
     if (requestorEntropy == null)
     {
         throw new ArgumentNullException("requestorEntropy");
     }
     if (issuerEntropy == null)
     {
         throw new ArgumentNullException("issuerEntropy");
     }
     int num = ValidateKeySizeInBytes(keySizeInBits);
     byte[] array = new byte[num];
     
     using (KeyedHashAlgorithm algorithm = new HMACSHA1())
     {
         algorithm.Key = requestorEntropy;
         byte[] buffer = issuerEntropy;
         byte[] buffer3 = new byte[(algorithm.HashSize / 8) + buffer.Length];
         byte[] buffer4 = null;
         try
         {
             try
             {
                 int num2 = 0;
                 while (num2 < num)
                 {
                     algorithm.Initialize();
                     buffer = algorithm.ComputeHash(buffer);
                     buffer.CopyTo(buffer3, 0);
                     issuerEntropy.CopyTo(buffer3, buffer.Length);
                     algorithm.Initialize();
                     buffer4 = algorithm.ComputeHash(buffer3);
                     for (int i = 0; i < buffer4.Length; i++)
                     {
                         if (num2 >= num)
                         {
                             continue;
                         }
                         array[num2++] = buffer4[i];
                     }
                 }
             }
             catch
             {
                 Array.Clear(array, 0, array.Length);
                 throw;
             }
             return array;
         }
         finally
         {
             if (buffer4 != null)
             {
                 Array.Clear(buffer4, 0, buffer4.Length);
             }
             Array.Clear(buffer3, 0, buffer3.Length);
             algorithm.Clear();
         }
     }
 }
开发者ID:bencoveney,项目名称:Thinktecture.IdentityModel.40,代码行数:60,代码来源:KeyGenerator.cs

示例2: Decrypt

        public static Account Decrypt(Stream inputStream, ConsoleType consoleType)
        {
            var hmac = new HMACSHA1(consoleType == ConsoleType.Retail ? RetailKey : DevkitKey);
            var hash = inputStream.ReadBytes(16);
            var rc4Key = hmac.ComputeHash(hash);
            Array.Resize(ref rc4Key, 16);

            var rest = inputStream.ReadBytes(388);
            var body = RC4.Decrypt(rc4Key, rest);

            var compareBuffer = hmac.ComputeHash(body);
            if (!memcmp(hash, compareBuffer, 16))
                throw new InvalidDataException("Keys do not match");
            return ModelFactory.GetModel<Account>(body.Skip(8).ToArray());
        }
开发者ID:mousetwentytwo,项目名称:test,代码行数:15,代码来源:Account.cs

示例3: GeneratePassword

        /// <summary>
        /// The original code at
        /// http://www.codeproject.com/Articles/403355/Implementing-Two-Factor-Authentication-in-ASP-NET
        /// by Rick Bassham, http://www.codeproject.com/script/Membership/View.aspx?mid=4294419
        /// under MIT License, http://opensource.org/licenses/mit-license.php
        /// 
        /// Modified by HouYu Li <[email protected]>
        /// </summary>
        /// <param name="secret"></param>
        /// <param name="iterationNumber"></param>
        /// <param name="digits"></param>
        /// <returns></returns>
        public static string GeneratePassword(string secret, long iterationNumber, int digits = 6)
        {
            byte[] counter = BitConverter.GetBytes(iterationNumber);

            if (BitConverter.IsLittleEndian)
                Array.Reverse(counter);

            byte[] key = Base32Decode.Decode(secret);

            HMACSHA1 hmac = new HMACSHA1(key, true);

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

            int offset = hash[hash.Length - 1] & 0xf;

            int binary =
                ((hash[offset] & 0x7f) << 24)
                | ((hash[offset + 1] & 0xff) << 16)
                | ((hash[offset + 2] & 0xff) << 8)
                | (hash[offset + 3] & 0xff);

            int password = binary % (int)Math.Pow(10, digits);

            return password.ToString(new string('0', digits));
        }
开发者ID:lihouyu,项目名称:TOTPGen,代码行数:37,代码来源:TOTP_GA.cs

示例4: getHash

 public string getHash(string input)
 {
     HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["HashSecret"]));
     byte[] byteArray = Encoding.ASCII.GetBytes(input);
     MemoryStream stream = new MemoryStream(byteArray);
     return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
 }
开发者ID:willdrob,项目名称:pollerbear,代码行数:7,代码来源:Encoder.cs

示例5: GetCodeInternal

        protected string GetCodeInternal(string secret, ulong challengeValue)
        {
            ulong chlg = challengeValue;
            byte[] challenge = new byte[8];
            for (int j = 7; j >= 0; j--) {
                challenge[j] = (byte)((int)chlg & 0xff);
                chlg >>= 8;
            }

            var key = Base32Encoding.ToBytes(secret);
            for (int i = secret.Length; i < key.Length; i++) {
                key[i] = 0;
            }

            HMACSHA1 mac = new HMACSHA1(key);
            var hash = mac.ComputeHash(challenge);

            int offset = hash[hash.Length - 1] & 0xf;

            int truncatedHash = 0;
            for (int j = 0; j < 4; j++) {
                truncatedHash <<= 8;
                truncatedHash |= hash[offset + j];
            }

            truncatedHash &= 0x7FFFFFFF;
            truncatedHash %= 1000000;

            string code = truncatedHash.ToString();
            return code.PadLeft(6, '0');
        }
开发者ID:TouchStar,项目名称:TwoStepsAuthenticator,代码行数:31,代码来源:Authenticator.cs

示例6: Sign

        protected internal Uri Sign(Uri _uri)
        {
            if (_uri == null)
                throw new ArgumentNullException("_uri");

            if (string.IsNullOrWhiteSpace(this.Key))
                throw new ArgumentException("Invalid signing key.");

            if (this.ClientId == null)
                throw new NullReferenceException("ClientID");

            if (!this.ClientId.StartsWith("gme-"))
                throw new ArgumentException("A user ID must start with 'gme-'.");

            var _urlSegmentToSign = _uri.LocalPath + _uri.Query + "&client=" + this.ClientId;
            var _privateKey = SignableRequest.FromBase64UrlString(this.Key);
            byte[] _signature;

            using (var _algorithm = new HMACSHA1(_privateKey))
            {
                _signature = _algorithm.ComputeHash(Encoding.ASCII.GetBytes(_urlSegmentToSign));
            }

            return new Uri(_uri.Scheme + "://" + _uri.Host + _urlSegmentToSign + "&signature=" + SignableRequest.ToBase64UrlString(_signature));
        }
开发者ID:JasonBSteele,项目名称:GoogleApi,代码行数:25,代码来源:SignableRequest.cs

示例7: Sign

        private static string Sign(string url, string appSid, string appKey)
        {
            // Add AppSid parameter.
            UriBuilder uriBuilder = new UriBuilder(url);

            if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
                uriBuilder.Query = uriBuilder.Query.Substring(1) + "&appSID=" + appSid;
            else
                uriBuilder.Query = "appSID=" + appSid;

            // Remove final slash here as it can be added automatically.
            uriBuilder.Path = uriBuilder.Path.TrimEnd('/');

            // Compute the hash.
            byte[] privateKey = Encoding.UTF8.GetBytes(appKey);
            HMACSHA1 algorithm = new HMACSHA1(privateKey);

            byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri);
            byte[] hash = algorithm.ComputeHash(sequence);
            string signature = Convert.ToBase64String(hash);

            // Remove invalid symbols.
            signature = signature.TrimEnd('=');
            signature = HttpUtility.UrlEncode(signature);

            // Convert codes to upper case as they can be updated automatically.
            signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());

            // Add the signature to query string.
            return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature);
        }
开发者ID:mrtaunus,项目名称:Aspose_Cloud_SDK_For_.NET,代码行数:31,代码来源:ServiceController.cs

示例8: HMAC

 protected static byte[] HMAC(byte[] data, string key)
 {
     using (var hmac = new HMACSHA1(data, true))
     {
         return hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
     }
 }
开发者ID:rob-blackbourn,项目名称:JetBlack.Authentication,代码行数:7,代码来源:ScramSha1.cs

示例9: GetSimInfo

 public async Task<bool> GetSimInfo()
 {
     Tools.Tools.SetProgressIndicator(true);
     try
     {
         Tools.Tools.SetProgressIndicator(true);
         SystemTray.ProgressIndicator.Text = "loading sims";
         var client = new VikingsApi();
         OAuthUtility.ComputeHash = (key, buffer) =>
         {
             using (var hmac = new HMACSHA1(key))
             {
                 return hmac.ComputeHash(buffer);
             }
         };
         string json = await client.GetInfo(new AccessToken((string) IsolatedStorageSettings.ApplicationSettings["tokenKey"], (string) IsolatedStorageSettings.ApplicationSettings["tokenSecret"]), client.Sim, new KeyValuePair {content = "1", name = "alias"});
         Sims = JsonConvert.DeserializeObject<Sim[]>(json);
         Tools.Tools.SetProgressIndicator(false);
         return true;
     }
     catch (Exception)
     {
         Message.ShowToast("Could not load sim information, please try again later");
         return false;
     }
 }
开发者ID:JanJoris,项目名称:VikingApp,代码行数:26,代码来源:MainPivotViewmodel.cs

示例10: GeneratePin

        /// <summary>
        ///   Generates a pin by hashing a key and counter.
        /// </summary>
        private static string GeneratePin(byte[] key, long counter)
        {
            //Get counter bytes (in big endian order)
            var counterBytes = BitConverter.GetBytes(counter);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(counterBytes);

            byte[] hash;
            using (var hmac = new HMACSHA1(key))
                hash = hmac.ComputeHash(counterBytes);

            var offset = hash[hash.Length - 1] & 0xF;

            var selectedBytes = new byte[sizeof(int)];
            Buffer.BlockCopy(hash, offset, selectedBytes, 0, sizeof(int));

            //spec interprets bytes in big-endian order
            if (BitConverter.IsLittleEndian)
                Array.Reverse(selectedBytes);

            var selectedInteger = BitConverter.ToInt32(selectedBytes, 0);

            //remove the most significant bit for interoperability per spec
            var truncatedHash = selectedInteger & 0x7FFFFFFF;

            //generate number of digits for given pin length
            var pin = truncatedHash % _pinModulo;

            return pin.ToString(CultureInfo.InvariantCulture).PadLeft(PIN_LENGTH, '0');
        }
开发者ID:WildGenie,项目名称:Bastet-Legacy,代码行数:33,代码来源:GoogleAuthenticator.cs

示例11: GenerateSignature

        /// <summary>
        /// Generates a signature using the specified signatureType 
        /// </summary>
        /// <param name="httpMethod">The http method used</param>
        /// <param name="url">The full url to be signed</param>
        /// <param name="parametersIn">The collection of parameters to sign</param>
        /// <param name="consumerSecret">The OAuth consumer secret used to generate the signature</param>
        /// <returns>A base64 string of the hash value</returns>
        public static string GenerateSignature(string httpMethod, Uri url, NameValueCollection parametersIn, string consumerSecret)
        {
            // Work with a copy of the parameters so the caller's data is not changed
            var parameters = new NameValueCollection(parametersIn);

            // https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
            // The query component is parsed into a list of name/value pairs by treating it as an
            // "application/x-www-form-urlencoded" string, separating the names and values and
            // decoding them as defined by [W3C.REC - html40 - 19980424], Section 17.13.4.
            //
            // Unescape the query so that it is not doubly escaped by UrlEncodingParser.
            var querystring = new UrlEncodingParser(Uri.UnescapeDataString(url.Query));
            parameters.Add(querystring);

            var signatureBase = GenerateSignatureBase(httpMethod, url, parameters);

            // Note that in LTI, the TokenSecret (second part of the key) is blank
            var hmacsha1 = new HMACSHA1
            {
                Key = Encoding.ASCII.GetBytes($"{consumerSecret.ToRfc3986EncodedString()}&")
            };

            var dataBuffer = Encoding.ASCII.GetBytes(signatureBase);
            var hashBytes = hmacsha1.ComputeHash(dataBuffer);

            return Convert.ToBase64String(hashBytes);
        }
开发者ID:andyfmiller,项目名称:LtiLibrary,代码行数:35,代码来源:OAuthUtility.cs

示例12: GetSignature

 public string GetSignature()
 {
     var policy64 = GetPolicyInBase64();
     byte[] b64Key = Encoding.ASCII.GetBytes(CManager.Settings.AWSSecretAccessKey);
     var hmacSha1 = new HMACSHA1(b64Key);
     return Convert.ToBase64String(hmacSha1.ComputeHash(Encoding.ASCII.GetBytes(policy64)));
 }
开发者ID:AbbTek,项目名称:6weeks-challenge,代码行数:7,代码来源:AWSS3upload.cs

示例13: EncodePassword

 //EncodePassword:Encrypts, Hashes, or leaves the password clear based on the PasswordFormat.
 public string EncodePassword(string password)
 {
     var encodedPassword = password;
     var hash = new HMACSHA1 { Key = HexToByte(_machineKey.ValidationKey) };
     encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
     return encodedPassword;
 }
开发者ID:Aaronontheweb,项目名称:PeerLearningSite,代码行数:8,代码来源:PasswordHelper.cs

示例14: EncodePassword

        private static string EncodePassword(string password)
        {
            HMACSHA1 hash = new HMACSHA1 {Key = HexToByte(key)};
            string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));

            return encodedPassword;
        }
开发者ID:divayht,项目名称:YouFood,代码行数:7,代码来源:PasswordManager.cs

示例15: WithS3Authentication

        //--- Extension Methods ---
        /// <summary>
        /// Add a Plug Pre-Handler to attach the appropriate auth header.
        /// </summary>
        /// <param name="plug">Plug instance to base operation on.</param>
        /// <param name="privateKey">Amazon S3 private key.</param>
        /// <param name="publicKey">Amazon S3 public key.</param>
        /// <returns>New Plug instance with pre-handler.</returns>
        public static Plug WithS3Authentication(this Plug plug, string privateKey, string publicKey)
        {
            return plug.WithPreHandler((verb, uri, normalizedUri, message) => {

                // add amazon date header (NOTE: this must be the real wall-time)
                var date = DateTime.UtcNow.ToString("r");
                message.Headers[AWS_DATE] = date;

                // add authorization header
                var authString = new StringBuilder()
                    .Append(verb)
                    .Append("\n")
                    .Append(message.Headers[DreamHeaders.CONTENT_MD5])
                    .Append("\n")
                    .Append(message.ContentType.ToString())
                    .Append("\n")
                    .Append("\n");
                foreach(var header in message.Headers.OrderBy(x => x.Key.ToLowerInvariant(), StringComparer.Ordinal)) {
                    if(!header.Key.StartsWithInvariantIgnoreCase("x-amz-")) {
                        continue;
                    }
                    authString.AppendFormat("{0}:{1}\n", header.Key.ToLowerInvariant(), header.Value);
                }
                authString.Append(normalizedUri.Path);
                var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(privateKey));
                var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(authString.ToString())));
                message.Headers.Authorization = string.Format("AWS {0}:{1}", publicKey, signature);
                message.Headers.ContentType = message.ContentType;
                return message;
            });
        }
开发者ID:nataren,项目名称:DReAM,代码行数:39,代码来源:S3PlugEx.cs


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