/// <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; }
internal static int MacData( HashAlgorithmName hashAlgorithm, ReadOnlySpan <byte> key, ReadOnlySpan <byte> source, Span <byte> destination) { if (Helpers.HasHMAC) { if (hashAlgorithm == HashAlgorithmName.SHA256) { return(HMACSHA256.HashData(key, source, destination)); } else if (hashAlgorithm == HashAlgorithmName.SHA1) { return(HMACSHA1.HashData(key, source, destination)); } else if (hashAlgorithm == HashAlgorithmName.SHA512) { return(HMACSHA512.HashData(key, source, destination)); } else if (hashAlgorithm == HashAlgorithmName.SHA384) { return(HMACSHA384.HashData(key, source, destination)); } else if (hashAlgorithm == HashAlgorithmName.MD5) { return(HMACMD5.HashData(key, source, destination)); } } throw new CryptographicException(SR.Format(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name)); }
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()); } }
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); } } } }; }
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); }
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(); }
public override void SetUp () { algo = new HMACSHA384 (); algo.Key = new byte [8]; hash = algo; // http://blogs.msdn.com/shawnfa/archive/2007/01/31/please-do-not-use-the-net-2-0-hmacsha512-and-hmacsha384-classes.aspx legacy = (new HS384 ().BlockSize == 64); }
public void Constructors () { algo = new HMACSHA384 (); Assert.IsNotNull (algo, "HMACSHA384 ()"); byte[] key = new byte [8]; algo = new HMACSHA384 (key); Assert.IsNotNull (algo, "HMACSHA384 (key)"); }
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); }
public void Invariants () { algo = new HMACSHA384 (); Assert.IsTrue (algo.CanReuseTransform, "HMACSHA384.CanReuseTransform"); Assert.IsTrue (algo.CanTransformMultipleBlocks, "HMACSHA384.CanTransformMultipleBlocks"); Assert.AreEqual ("SHA384", algo.HashName, "HMACSHA384.HashName"); Assert.AreEqual (384, algo.HashSize, "HMACSHA384.HashSize"); Assert.AreEqual (1, algo.InputBlockSize, "HMACSHA384.InputBlockSize"); Assert.AreEqual (1, algo.OutputBlockSize, "HMACSHA384.OutputBlockSize"); Assert.AreEqual ("System.Security.Cryptography.HMACSHA384", algo.ToString (), "HMACSHA384.ToString()"); }
/// <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; }
/// <summary> /// Creates a new HMAC instance /// </summary> /// <param name="theHash">The hash.</param> /// <returns>A <see cref="HMAC"/> instance</returns> /// <exception cref="NotSupportedException">If the given <paramref name="theHash"/> is not a supported HMAC</exception> public static System.Security.Cryptography.HMAC CreateInstance(HashType theHash) { System.Security.Cryptography.HMAC hmac = null; switch (theHash) { case HashType.MD5: { hmac = new HMACMD5(); break; } case HashType.RIPEMD160: { hmac = new HMACRIPEMD160(); break; } case HashType.SHA1: { hmac = new HMACSHA1(); break; } case HashType.SHA256: { hmac = new HMACSHA256(); break; } case HashType.SHA384: { hmac = new HMACSHA384(); break; } case HashType.SHA512: { hmac = new HMACSHA512(); break; } default: { throw new NotSupportedException(String.Format("The given hash :'{0}' is not a supported hmac", theHash)); } } return hmac; }
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; }
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)); }
// validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name] // [1] http://msdn.microsoft.com/en-us/library/system.web.configuration.machinekeyvalidation.aspx // [2] http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx public static KeyedHashAlgorithm GetValidationAlgorithm (MachineKeySection section) { KeyedHashAlgorithm kha = null; switch (section.Validation) { case MachineKeyValidation.MD5: kha = new HMACMD5 (); break; case MachineKeyValidation.AES: // see link [1] or [2] case MachineKeyValidation.TripleDES: // see link [2] case MachineKeyValidation.SHA1: kha = new HMACSHA1 (); break; #if NET_4_0 case MachineKeyValidation.HMACSHA256: kha = new HMACSHA256 (); break; case MachineKeyValidation.HMACSHA384: kha = new HMACSHA384 (); break; case MachineKeyValidation.HMACSHA512: kha = new HMACSHA512 (); break; case MachineKeyValidation.Custom: // remove the "alg:" from the start of the string string algo = section.ValidationAlgorithm; if (algo.StartsWith ("alg:")) kha = KeyedHashAlgorithm.Create (algo.Substring (4)); break; #endif } return kha; }
private static void GetAlgorithmParameters( string algorithm, byte[] key, out byte[] aes_key, out byte[] hmac_key, out HMAC hmac ) { switch ( algorithm ) { case Aes128CbcHmacSha256.AlgorithmName: { if ( ( key.Length << 3 ) < 256 ) throw new CryptographicException( string.Format( CultureInfo.CurrentCulture, "{0} key length in bits {1} < 256", algorithm, key.Length << 3 ) ); hmac_key = new byte[128 >> 3]; aes_key = new byte[128 >> 3]; Array.Copy( key, hmac_key, 128 >> 3 ); Array.Copy( key, 128 >> 3, aes_key, 0, 128 >> 3 ); hmac = new HMACSHA256( hmac_key ); break; } case Aes192CbcHmacSha384.AlgorithmName: { if ( ( key.Length << 3 ) < 384 ) throw new CryptographicException( string.Format( CultureInfo.CurrentCulture, "{0} key length in bits {1} < 384", algorithm, key.Length << 3 ) ); hmac_key = new byte[192 >> 3]; aes_key = new byte[192 >> 3]; Array.Copy( key, hmac_key, 192 >> 3 ); Array.Copy( key, 192 >> 3, aes_key, 0, 192 >> 3 ); hmac = new HMACSHA384( hmac_key ); break; } case Aes256CbcHmacSha512.AlgorithmName: { if ( ( key.Length << 3 ) < 512 ) throw new CryptographicException( string.Format( CultureInfo.CurrentCulture, "{0} key length in bits {1} < 512", algorithm, key.Length << 3 ) ); hmac_key = new byte[256 >> 3]; aes_key = new byte[256 >> 3]; Array.Copy( key, hmac_key, 256 >> 3 ); Array.Copy( key, 256 >> 3, aes_key, 0, 256 >> 3 ); hmac = new HMACSHA512( hmac_key ); break; } default: { throw new CryptographicException( string.Format( CultureInfo.CurrentCulture, "Unsupported algorithm: {0}", algorithm ) ); } } }
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(); }
/// <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 { } }
/// <summary> /// 获取加密方法 /// </summary> /// <param name="hmacFormat"></param> /// <param name="key"></param> /// <returns></returns> private static HMAC GetHmac(HmacFormat hmacFormat, byte[] key) { HMAC hmac = null; switch (hmacFormat) { case HmacFormat.HMACMD5: hmac = new HMACMD5(key); break; case HmacFormat.HMACRIPEMD160: hmac = new HMACRIPEMD160(key); break; case HmacFormat.HMACSHA1: hmac = new HMACSHA1(key); break; case HmacFormat.HMACSHA256: hmac = new HMACSHA256(key); break; case HmacFormat.HMACSHA384: hmac = new HMACSHA384(key); break; case HmacFormat.HMACSHA512: hmac = new HMACSHA512(key); break; } return hmac; }
private byte[] PBKDF2_SHA384(byte[] password, byte[] salt, int iterations, int outputBytes) { using (var hmac = new HMACSHA384()) { var df = new Pbkdf2(hmac, password, salt, iterations); return df.getBytes(AppConst.AESKeySize + AppConst.AESBlockSize); } }
protected virtual string Sign(string unsignedToken, JwtHeader header) { var algorithm = ParseSigningCredentials(header.SigningCredentials); if (header.SignatureAlgorithm != algorithm) { throw new InvalidOperationException("Mismatch between signature algorithm and signing key"); } HMAC hmac; switch (algorithm) { case JwtConstants.SignatureAlgorithms.HMACSHA256: hmac = new HMACSHA256(); break; case JwtConstants.SignatureAlgorithms.HMACSHA384: hmac = new HMACSHA384(); break; case JwtConstants.SignatureAlgorithms.HMACSHA512: hmac = new HMACSHA512(); break; default: throw new InvalidOperationException("Unsupported signature algorithm"); } hmac.Key = (header.SigningCredentials.SigningKey as InMemorySymmetricSecurityKey).GetSymmetricKey(); using (hmac) { var signature = hmac.ComputeHash(Encoding.UTF8.GetBytes(unsignedToken)); return Base64Url.Encode(signature); } }
public static byte[] PRF(PRFAlgorithm prfAlgorithm, byte[] key, string label, byte[] seed, int bytesNeeded) { switch (prfAlgorithm) { case PRFAlgorithm.TLSPrfSHA256: using (var hmac = new HMACSHA256(key)) return PRF(hmac, label, seed, bytesNeeded); case PRFAlgorithm.TLSPrfSHA384: using (var hmac = new HMACSHA384(key)) return PRF(hmac, label, seed, bytesNeeded); case PRFAlgorithm.TLSPrfMD5SHA1: var halfKeyLen = (key.Length + 1) / 2; var key1 = new byte[halfKeyLen]; var key2 = new byte[halfKeyLen]; Buffer.BlockCopy(key, 0, key1, 0, halfKeyLen); Buffer.BlockCopy(key, key.Length - halfKeyLen, key2, 0, halfKeyLen); using (var hmac1 = new HMACMD5(key1)) { using (var hmac2 = new HMACSHA1(key2)) { var prf1 = PRF(hmac1, label, seed, bytesNeeded); var prf2 = PRF(hmac2, label, seed, bytesNeeded); for (var i = 0; i < bytesNeeded; i++) { prf1[i] ^= prf2[i]; } ClearArray(key1); ClearArray(key2); ClearArray(prf2); return prf1; } } default: throw new NotSupportedException(); } }
public BitfinexApiV1(string key, string secret) { hashMaker = new HMACSHA384(Encoding.UTF8.GetBytes(secret)); this.Key = key; }
public override void SetUp () { algo = new HMACSHA384 (); algo.Key = new byte [8]; hash = algo; }
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 }
public byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey) { ECPublicKeyParameters publicKey = GetPublicKeyParameters(otherPartyPublicKey); // Calculate the shared secret from public key Org.BouncyCastle.Crypto.Agreement.ECDHBasicAgreement agreement = new Org.BouncyCastle.Crypto.Agreement.ECDHBasicAgreement(); agreement.Init(_privateKeyParameters); byte[] secret = agreement.CalculateAgreement(publicKey).ToByteArray(); // Make sure the secret is always correct length byte[] tmpSecret = new byte[(_keySize+7)/8]; Buffer.BlockCopy(secret, System.Math.Max(0, secret.Length-tmpSecret.Length), tmpSecret, System.Math.Max(0, tmpSecret.Length-secret.Length), System.Math.Min(tmpSecret.Length, secret.Length)); secret = tmpSecret; if (_kdf == ECDiffieHellmanKeyDerivationFunction.Hash || _kdf == ECDiffieHellmanKeyDerivationFunction.Hmac) { HashAlgorithm hashAlgorithm; if (_kdf == ECDiffieHellmanKeyDerivationFunction.Hash) { if (_hashAlgorithm.Equals(CngAlgorithm.MD5)) { hashAlgorithm = new MD5CryptoServiceProvider(); } else if (_hashAlgorithm.Equals(CngAlgorithm.Sha1)) { hashAlgorithm = new SHA1CryptoServiceProvider(); } else if (_hashAlgorithm.Equals(CngAlgorithm.Sha256)) { hashAlgorithm = new SHA256Managed(); } else if (_hashAlgorithm.Equals(CngAlgorithm.Sha384)) { hashAlgorithm = new SHA384Managed(); } else if (_hashAlgorithm.Equals(CngAlgorithm.Sha512)) { hashAlgorithm = new SHA512Managed(); } else { throw new Exception("Unsupported hash algorithm type: " + _hashAlgorithm); } } else { byte[] hmacKey = _hmacKey; if (UseSecretAgreementAsHmacKey) { hmacKey = secret; } if (_hashAlgorithm.Equals(CngAlgorithm.MD5)) { hashAlgorithm = new HMACMD5(hmacKey); } else if (_hashAlgorithm.Equals(CngAlgorithm.Sha1)) { hashAlgorithm = new HMACSHA1(hmacKey); } else if (_hashAlgorithm.Equals(CngAlgorithm.Sha256)) { hashAlgorithm = new HMACSHA256(hmacKey); } else if (_hashAlgorithm.Equals(CngAlgorithm.Sha384)) { hashAlgorithm = new HMACSHA384(hmacKey); } else if (_hashAlgorithm.Equals(CngAlgorithm.Sha512)) { hashAlgorithm = new HMACSHA512(hmacKey); } else { throw new Exception("Unsupported hash algorithm type: " + _hashAlgorithm); } } hashAlgorithm.Initialize(); if (_secretPrepend != null) { hashAlgorithm.TransformBlock(_secretPrepend, 0, _secretPrepend.Length, _secretPrepend, 0); } hashAlgorithm.TransformBlock(secret, 0, secret.Length, secret, 0); if (_secretAppend != null) { hashAlgorithm.TransformBlock(_secretAppend, 0, _secretAppend.Length, _secretAppend, 0); } hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0); return hashAlgorithm.Hash; } throw new Exception("KeyDerivationFunction not implemented yet"); }