示例#1
0
 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);
                                                       }
                                                   }
                          }
                      };
 }
示例#2
0
 public static string HMACSHA384(string key, string message)
 {
     using (var hasher = new crypto.HMACSHA384(Encoding.UTF8.GetBytes(key)))
     {
         return(hasher.ComputeHash(Encoding.UTF8.GetBytes(message)).ToHexString());
     }
 }
示例#3
0
        public static string Encode(string publicKey, int choice = 2)
        {
            byte[] hashMessage = null;
            byte[] messageBytes = m_encoding.GetBytes(publicKey);

            switch (choice%6)
            {
                case 0:
                    var hmacmd5 = new HMACMD5(m_keyBytes);
                    hashMessage = hmacmd5.ComputeHash(messageBytes);
                    break;
                case 1:
                    var hmacripedmd160 = new HMACRIPEMD160(m_keyBytes);
                    hashMessage = hmacripedmd160.ComputeHash(messageBytes);
                    break;
                case 2:
                    var hmacsha1 = new HMACSHA1(m_keyBytes);
                    hashMessage = hmacsha1.ComputeHash(messageBytes);
                    break;
                case 3:
                    var hmacsha256 = new HMACSHA256(m_keyBytes);
                    hashMessage = hmacsha256.ComputeHash(messageBytes);
                    break;
                case 4:
                    var hmacsha384 = new HMACSHA384(m_keyBytes);
                    hashMessage = hmacsha384.ComputeHash(messageBytes);
                    break;
                case 5:
                    var hmacsha512 = new HMACSHA512(m_keyBytes);
                    hashMessage = hmacsha512.ComputeHash(messageBytes);
                    break;
            }

            return Convert.ToBase64String(hashMessage);
        }
示例#4
0
 public static string CalculateHMACSHA384(byte[] input)
 {
     Encoding encoding = new UTF8Encoding();
     byte[] key = encoding.GetBytes(ConfigurationManager.AppSettings["HMACSHA384Key"]);
     HashAlgorithm hashAlgo = new HMACSHA384(key);
     byte[] hash = hashAlgo.ComputeHash(input);
     return BitConverter.ToString(hash).Replace("-", "").ToLower();
 }
        private void btnSHA384_Click(object sender, EventArgs e)
        {
            string input = tbInput.Text;
            var salt = System.Text.Encoding.UTF8.GetBytes("my salt");
            var password = System.Text.Encoding.UTF8.GetBytes(input);
            var hmacSHA384 = new HMACSHA384(salt);
            var saltedHash = hmacSHA384.ComputeHash(password);

            tbOutput.Text = System.Text.Encoding.UTF8.GetString(saltedHash);
        }
示例#6
0
        /// <summary>
        /// Hash the random string value that was created as to make it more random and return a 64 byte key.
        /// </summary>
        /// <param name="randomKey"></param>
        /// <returns></returns>
        private static string HashGeneratedString(string randomKey)
        {
            Guid g = Guid.NewGuid();
            string salt = Convert.ToBase64String(g.ToByteArray());
            salt = salt.Replace("=", "").Replace("+", "");

            byte[] saltBytes = Encoding.ASCII.GetBytes(salt);
            HashAlgorithm hashAlgorithm = new HMACSHA384(saltBytes);

            byte[] bytesToHash = Encoding.ASCII.GetBytes(randomKey);
            byte[] computedHashBytes = hashAlgorithm.ComputeHash(bytesToHash);

            string generatedKey = Convert.ToBase64String(computedHashBytes);
            return generatedKey;
        }
 public static string GetHashHMACSHA384(this string text, string key)
 {
     using (HMACSHA384 hSHA1 = new HMACSHA384() { Key = UTF8Encoding.UTF8.GetBytes(key) })
     {
         text = Convert.ToBase64String(hSHA1.ComputeHash(UTF8Encoding.UTF8.GetBytes(text)));
     }
     return text;
 }
示例#8
0
        public static byte[] HmacData(TpmAlgId hashAlgId, byte[] key, byte[] dataToHash)
        {
#if TSS_USE_BCRYPT
            string algName = Native.BCryptHashAlgName(hashAlgId);
            if (string.IsNullOrEmpty(algName))
            {
                Globs.Throw<ArgumentException>("HmacData(): Unsupported hash algorithm " + hashAlgId);
                return null;
            }

            var alg = new BCryptAlgorithm(algName, Native.BCRYPT_ALG_HANDLE_HMAC);
            var digest = alg.HmacData(key, dataToHash);
            alg.Close();
            return digest;
#else
            switch (hashAlgId)
            {
                case TpmAlgId.Sha1:
                    using (var h = new HMACSHA1(key))
                    {
                        return h.ComputeHash(dataToHash);
                    }
                case TpmAlgId.Sha256:
                    using (var h2 = new HMACSHA256(key))
                    {
                        return h2.ComputeHash(dataToHash);
                    }
                case TpmAlgId.Sha384:
                    using (var h3 = new HMACSHA384(key))
                    {
                        return h3.ComputeHash(dataToHash);
                    }
                case TpmAlgId.Sha512:
                    using (var h4 = new HMACSHA512(key))
                    {
                        return h4.ComputeHash(dataToHash);
                    }
                default:
                    Globs.Throw<ArgumentException>("HmacData(): Unsupported hash algorithm " + hashAlgId);
                    return null;
            }
#endif // !TSS_USE_BCRYPT
        }
 private string GetHexHashSignature(string payload)
 {
     HMACSHA384 hmac = new HMACSHA384(Encoding.UTF8.GetBytes(_apiSecret));
     byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
     return BitConverter.ToString(hash).Replace("-", "").ToLower();
 }
示例#10
0
        /// <summary>
        /// Computes a keyed hash for a source file based on key provided and the HMAC algorithm selected by the user
        /// Defaults to HMACSHA1
        /// </summary>
        /// <param name="file">file to get the HMAC of</param>
        /// <param name="hmacAlgo">HMAC algorithm to use</param>
        /// <param name="hmacKey">Key supplied by the user</param>
        public string CalculateHMAC(string file, string hmacAlgo, byte[] hmacKey)
        {
            string resultHmac = "";
            byte[] hashOfInputFile;
            try
            {
                switch (hmacAlgo)
                {
                    case "HMACMD5":
                        using (HMACMD5 hmacSha1 = new HMACMD5(hmacKey))
                        {
                            using (FileStream objFS = new FileStream(file, FileMode.Open))
                            {
                                // Computing the hash of the input file
                                hashOfInputFile = hmacSha1.ComputeHash(objFS);
                            }
                        }
                        break;
                    case "HMACSHA256":
                        using (HMACSHA256 hmacSha1 = new HMACSHA256(hmacKey))
                        {
                            using (FileStream objFS = new FileStream(file, FileMode.Open))
                            {
                                // Computing the hash of the input file
                                hashOfInputFile = hmacSha1.ComputeHash(objFS);
                            }
                        }
                        break;
                    case "HMACSHA384":
                        using (HMACSHA384 hmacSha1 = new HMACSHA384(hmacKey))
                        {
                            using (FileStream objFS = new FileStream(file, FileMode.Open))
                            {
                                // Computing the hash of the input file
                                hashOfInputFile = hmacSha1.ComputeHash(objFS);
                            }
                        }
                        break;
                    case "HMACSHA512":
                        using (HMACSHA512 hmacSha1 = new HMACSHA512(hmacKey))
                        {
                            using (FileStream objFS = new FileStream(file, FileMode.Open))
                            {
                                // Computing the hash of the input file
                                hashOfInputFile = hmacSha1.ComputeHash(objFS);
                            }
                        }
                        break;
                    case "HMACRIPEMD160":
                        using (HMACRIPEMD160 hmacSha1 = new HMACRIPEMD160(hmacKey))
                        {
                            using (FileStream objFS = new FileStream(file, FileMode.Open))
                            {
                                // Computing the hash of the input file
                                hashOfInputFile = hmacSha1.ComputeHash(objFS);
                            }
                        }
                        break;
                    default:// "HMACSHA1":
                        using (HMACSHA1 hmacSha1 = new HMACSHA1(hmacKey))
                        {
                            using(FileStream objFS = new FileStream(file, FileMode.Open))
                            {
                                // Computing the hash of the input file
                                hashOfInputFile = hmacSha1.ComputeHash(objFS);
                            }
                        }
                        break;
                }
                resultHmac = BitConverter.ToString(hashOfInputFile).Replace("-", String.Empty).ToLower();
                return resultHmac;
             }
            catch
            {
                resultHmac = HMAC_ERROR;
                return resultHmac;
            }
            finally
            {

            }
        }
示例#11
0
        private string sendPostRequest(string method, List<Tuple<string, string>> paramz = null)
        {
            string path = BASE_URL + method;

            WebException exc = null;
            for (int i = 1; i <= RETRY_COUNT; i++)
            {
                long nonce = DateTime.UtcNow.Ticks;
                nonce += _nonceOffset;

                string paramDict = "{" + String.Format("\"request\":\"/v1/{0}\",\"nonce\":\"{1}\"", method, nonce);
                if (null != paramz && paramz.Any())
                {
                    foreach (var param in paramz)
                        paramDict += "," + param.Item1 + ":" + param.Item2;
                }
                paramDict += "}";
                string payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(paramDict));

                var hmac = new HMACSHA384(Encoding.UTF8.GetBytes(_config.SecretKey));
                byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
                string hexHash = BitConverter.ToString(hash).Replace("-", "").ToLower();

                var headers = new NameValueCollection
                {
                    {"X-BFX-APIKEY", _config.AccessKey},
                    {"X-BFX-PAYLOAD", payload},
                    {"X-BFX-SIGNATURE", hexHash}
                };

                var request = (HttpWebRequest)WebRequest.Create(path);
                request.KeepAlive = true;
                request.Method = "POST";

                if (null != _webProxy)
                    request.Proxy = _webProxy;

                request.Headers.Add(headers);

                byte[] byteArray = Encoding.UTF8.GetBytes(paramDict);
                request.ContentLength = byteArray.Length;

                using (var writer = request.GetRequestStream())
                {
                    writer.Write(byteArray, 0, byteArray.Length);
                }

                try
                {
                    using (WebResponse response = request.GetResponse())
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            using (var reader = new StreamReader(stream))
                            {
                                var text = reader.ReadToEnd();
                                _logger.LastResponse = text;
                                return text;
                            }
                        }
                    }
                }
                catch (WebException we)
                {
                    //Business errors act as 400-ProtocolError, so must be sorted out
                    if (we.Response != null)
                    {
                        using (var errorResponse = (HttpWebResponse)we.Response)
                        {
                            using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                            {
                                string json = reader.ReadToEnd();
                                var error = Helpers.DeserializeJSON<ErrorResponse>(json);
                                if (!String.IsNullOrEmpty(error.message))
                                    return json;
                            }
                        }
                    }

                    //Else real HTTP problem
                    var text = String.Format("(ATTEMPT {0}/{1}) Web request failed with exception={2}; status={3}", i, RETRY_COUNT, we.Message, we.Status);

                    _logger.Warning(text);
                    exc = we;
                    Thread.Sleep(RETRY_DELAY);
                }
            }

            throw new Exception(String.Format("Web request failed {0} times in a row with error '{1}'. Giving up.", RETRY_COUNT, exc.Message));
        }