protected void VerifyHmac( int testCaseId, string digest, int truncateSize = -1) { byte[] digestBytes = ByteUtils.HexToByteArray(digest); byte[] computedDigest; using (HMAC hmac = Create()) { Assert.True(hmac.HashSize > 0); byte[] key = (byte[])_testKeys[testCaseId].Clone(); hmac.Key = key; // make sure the getter returns different objects each time Assert.NotSame(key, hmac.Key); Assert.NotSame(hmac.Key, hmac.Key); // make sure the setter didn't cache the exact object we passed in key[0] = (byte)(key[0] + 1); Assert.NotEqual <byte>(key, hmac.Key); computedDigest = hmac.ComputeHash(_testData[testCaseId]); } if (truncateSize != -1) { byte[] tmp = new byte[truncateSize]; Array.Copy(computedDigest, 0, tmp, 0, truncateSize); computedDigest = tmp; } Assert.Equal(digestBytes, computedDigest); }
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { var hashed = _Hash.ComputeHash(inputBuffer, inputOffset, inputCount); Buffer.BlockCopy(hashed, 0, outputBuffer, outputOffset, hashed.Length); return(inputCount); }
static string GetHMACText(string text, HMAC algorithm) { var byteText = Encoding.ASCII.GetBytes(text); var byteResult = algorithm.ComputeHash(byteText); return(Convert.ToBase64String(byteResult)); }
// // * Sign a request in the form of a Dictionary of name-value pairs. // * // * This method returns a complete URL to use. Modifying the returned URL // * in any way invalidates the signature and Amazon will reject the requests. // public string Sign(IDictionary <string, string> request) { // Use a SortedDictionary to get the parameters in naturual byte order, as // required by AWS. ParamComparer pc = new ParamComparer(); SortedDictionary <string, string> sortedMap = new SortedDictionary <string, string>(request, pc); // Add the AWSAccessKeyId and Timestamp to the requests. sortedMap["AWSAccessKeyId"] = this.akid; sortedMap["Timestamp"] = this.GetTimestamp(); // Get the canonical query string string canonicalQS = this.ConstructCanonicalQueryString(sortedMap); // Derive the bytes needs to be signed. StringBuilder builder = new StringBuilder(); builder.Append(REQUEST_METHOD).Append("\n").Append(this.endPoint).Append("\n").Append(REQUEST_URI).Append("\n").Append(canonicalQS); string stringToSign = builder.ToString(); byte[] toSign = Encoding.UTF8.GetBytes(stringToSign); // Compute the signature and convert to Base64. byte[] sigBytes = signer.ComputeHash(toSign); string signature = Convert.ToBase64String(sigBytes); // now construct the complete URL and return to caller. StringBuilder qsBuilder = new StringBuilder(); qsBuilder.Append(" http://").Append(this.endPoint).Append(REQUEST_URI).Append("?").Append(canonicalQS).Append("&Signature=").Append(this.PercentEncodeRfc3986(signature)); return(qsBuilder.ToString()); }
public Mac(SecretKeySpec key, string data) { switch (key.Method) { case EncryptionMethods.HMACMD5: mac = new HMACMD5(key.SecretKey); break; case EncryptionMethods.HMACSHA512: mac = new HMACSHA512(key.SecretKey); break; case EncryptionMethods.HMACSHA384: mac = new HMACSHA384(key.SecretKey); break; case EncryptionMethods.HMACSHA256: mac = new HMACSHA256(key.SecretKey); break; case EncryptionMethods.HMACSHA1: mac = new HMACSHA1(key.SecretKey); break; default: throw new NotSupportedException("not supported HMAC"); } rawHmac = mac.ComputeHash(Cardinity.ENCODING.GetBytes(data)); }
/// <summary> /// Implements step 2: Expand /// </summary> /// <param name="prk">A pseudorandom key used as key for the internal HMAC operation</param> /// <param name="info">An optional context and application specific information</param> /// <param name="length">The length of the output keying material in bytes (<= 255 * hash length)</param> /// <returns>The expanded output keying material (OKM)</returns> public byte[] Expand(byte[] prk, byte[] info, int length) { using HMAC hmac = m_hmacFactory.Invoke(); if (prk == null || prk.Length == 0) { throw new ArgumentException($"{nameof(prk)} must not be null or empty", nameof(prk)); } int hashLength = hmac.HashSize / 8; if (length < 1 || length > 255 * hashLength) { throw new ArgumentException($"{nameof(length)} must be: 1 <= {nameof(length)} <= {255 * hashLength:0,000} (255 * hash length in bytes)", nameof(length)); } if (info == null) { info = new byte[0]; } byte[] lastT = new byte[0]; try { int n = (int)Math.Ceiling((double)length / hashLength); byte[] finalKey = new byte[length]; int nPendingBytes = length; hmac.Key = prk; for (int i = 0; i < n && nPendingBytes > 0; i++) { byte[] input = PrepareExpandInput(lastT, info, i + 1); if (lastT.Length > 0) { // don't keep any part of the OKM in memory, if not needed anymore Array.Clear(lastT, 0, lastT.Length); } lastT = hmac.ComputeHash(input); Buffer.BlockCopy(lastT, 0, finalKey, i * hashLength, Math.Min(lastT.Length, nPendingBytes)); nPendingBytes -= lastT.Length; } return(finalKey); } finally { if (lastT.Length > 0) { // don't keep any part of the OKM in memory, if not needed anymore Array.Clear(lastT, 0, lastT.Length); } } }
public static string GenerateSignature(string key, string message) { HMAC hmac = HMAC.Create("HMACSHA256"); hmac.Key = Encoding.UTF8.GetBytes(key); byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message)); return(BitConverter.ToString(hash).Replace("-", "").ToUpperInvariant()); }
/// <summary> /// HMAC helper function /// </summary> /// <param name="key"></param> /// <param name="input"></param> /// <returns></returns> private byte[] Hmac(byte[] key, string input) { _hmac.Key = key; var bytes = Encoding.UTF8.GetBytes(input); var hash = _hmac.ComputeHash(bytes); return(hash); }
/// <summary> /// 对字符串进行基于密钥的 Hash 加密 /// </summary> /// <param name="inputString"></param> /// <param name="key">密钥的长度不限,建议的密钥长度为 64 个英文字符。</param> /// <param name="hashFormat"></param> /// <returns></returns> public static string Hmac(string inputString, string key, HmacFormat hashFormat = HmacFormat.HMACSHA1) { HMAC algorithm = GetHmac(hashFormat, Encoding.ASCII.GetBytes(key)); algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)); return(BitConverter.ToString(algorithm.Hash).Replace("-", "").ToUpper()); }
/// <summary> /// /// </summary> /// <param name="hmac"></param> /// <param name="stream">待加密的流</param> /// <returns></returns> private static string GetHMacSha(HMAC hmac, Stream stream) { byte[] hashmessage = hmac.ComputeHash(stream); string res = hashmessage.ConvertToBase64(); hmac.Dispose(); return(res); }
public static byte[] ComputeHash(this HMAC hmac, params object[] blobs) { return(hmac.ComputeHash( blobs .Select(blob => Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(blob))) .ToArray() )); }
public static byte[] SignWithSymmetricKey(string message, byte[] key) { using (HMAC hmac = HMAC.Create("HMACSHA256")) { hmac.Key = key; return(hmac.ComputeHash(Encoding.UTF8.GetBytes(message))); } }
/// <summary> /// Creates a hashed signature from the string and private key provided. /// </summary> /// <param name="dataBytes"> /// A byte array generated from the string to be signed. /// </param> /// <param name="keyBytes"> /// The private key to use in hashing /// </param> /// <returns> /// the hashed signature /// </returns> private static byte[] Sign(byte[] dataBytes, byte[] keyBytes) { using (HMAC mac = HMAC.Create(HmacAlgorithm)) { mac.Key = keyBytes; return(mac.ComputeHash(dataBytes)); } }
public static byte[] Extract(HMAC hmac, byte[] salt, byte[] ikm) { //if salt not provided, salt is set to a string of HMAC.HashSize/8 zeros hmac.Key = salt ?? new byte[hmac.HashSize / 8]; var prk = hmac.ComputeHash(ikm); return(prk); }
public void CheckC(string testName, HMAC algo, byte[] data, byte[] result) { using (MemoryStream ms = new MemoryStream(data)) { byte[] hmac = algo.ComputeHash(ms); Compare(result, hmac, testName + "c1"); Compare(result, algo.Hash, testName + "c2"); } }
public static byte[] SignData(byte[] Key, byte[] data, HMAC alg) { alg.Key = Key; var hash = alg.ComputeHash(data); var result = hash.Concat(data).ToArray(); return(result); }
public static byte[] ComputeHmac(string algorithmName, byte[] data, byte[] key) { using (HMAC hmac = HMAC.Create(algorithmName)) { hmac.Key = key; return(hmac.ComputeHash(data)); } }
public static byte[] Hash(string input, HMAC hashAlgorithm, Encoding encoding = null) { EnsureArg.IsNotNull(input, nameof(input)); EnsureArg.IsNotNull(hashAlgorithm, nameof(hashAlgorithm)); encoding ??= Encoding.UTF8; return(hashAlgorithm.ComputeHash(encoding.GetBytes(input))); }
private byte[] SignPayload(byte[] payload) { byte[] key = Convert.FromBase64String(metadata.SymmetricKey); using HMAC hmac = HMAC.Create(); hmac.Key = key; return(hmac.ComputeHash(payload)); }
public String SignToken(String tokenValue) { HMAC hmac = HMAC.Create(signAlg); byte[] binaryKey = Encoding.UTF8.GetBytes(key); hmac.Key = binaryKey; byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(tokenValue)); return(System.Convert.ToBase64String(hash, 0, hash.Length)); }
/// <summary> /// Derive a key given a variable salt and key /// </summary> /// <param name="salt">Variable salt input</param> /// <param name="secret">Key bytes</param> /// <param name="outputLength">Desired output length in bytes</param> /// <returns>A key of the required length as a byte array</returns> public byte[] DeriveKey(byte[] salt, byte[] secret, int outputLength) { using (HMAC hmac = GetHmac(salt)) { byte[] privateKey = hmac.ComputeHash(secret); byte[] result = Expand(hmac, privateKey, outputLength); return(result); } }
/// <summary> /// HMAC_SHA_512 /// </summary> public static string hmacSha512(string key, string value) { HMAC hmac = HMAC.Create("hmacsha512"); hmac.Key = Encoding.UTF8.GetBytes(key); var code = hmac.ComputeHash(Encoding.UTF8.GetBytes(value)); return(BitConverter.ToString(code).Replace("-", string.Empty)); }
/// <summary> /// /// </summary> /// <param name="hmac"></param> /// <param name="str">待价密的字符串</param> /// <param name="encoding">编码格式,默认UTF-8</param> /// <returns></returns> private static string GetHMacSha(HMAC hmac, string str, Encoding encoding) { byte[] messageBytes = encoding.GetBytes(str); byte[] hashmessage = hmac.ComputeHash(messageBytes); string res = hashmessage.ConvertToBase64(); hmac.Dispose(); return(res); }
private int FinalizeUpdate(String filename, String passphrase) { try { core.InitializeKeys(passphrase); } catch { Console.Error.WriteLine("Invalid passphrase"); return(1); } StreamReader sr = new StreamReader(Path.Combine(core.ApplicationDataFolder, "identity")); String username = sr.ReadLine(); String email = sr.ReadLine(); sr.Close(); username.Trim(); email.Trim(); Connect(); ArrayList key = new ArrayList(File.ReadAllBytes(Path.Combine(core.ApplicationDataFolder, "answers.key"))); AESInfo info = new AESInfo(); info.key = (byte[])key.GetRange(0, Crypto.AESKeySize / 8).ToArray(Type.GetType("System.Byte")); info.IV = (byte[])key.GetRange(Crypto.AESKeySize / 8, Crypto.AESIVSize / 8).ToArray(Type.GetType("System.Byte")); Rijndael aes = Rijndael.Create(); String e_macpass = File.ReadAllText(filename); e_macpass = Crypto.StripMessage(e_macpass); byte[] macpass = Crypto.AESDecrypt(Convert.FromBase64String(e_macpass), aes.CreateDecryptor(info.key, info.IV)); HMAC hmac = HMACSHA1.Create(); hmac.Key = macpass; byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(core.PublicKey)); if (server.USKeyUpdate_SendPublicKey(username, email, core.PublicKey, Convert.ToBase64String(hash))) { Console.WriteLine("Public key successfully sent."); } else { Console.WriteLine("Public key could not be sent, please try again."); } File.Delete(Path.Combine(core.ApplicationDataFolder, "answers.key")); return(0); }
public string GenerateSignature(out long nonce) { nonce = Nonce.Next(); var bytes = Encoding.UTF8.GetBytes($"{nonce}{UserId}{ApiKey}"); var hash = _hmac.ComputeHash(bytes); return(string.Concat(hash.Select(b => b.ToString("X2")))); }
public static byte[] ComputeHmacHash(Stream input, HMAC hashAlgorithm) { if (input == null) { return(null); } return(hashAlgorithm.ComputeHash(input)); }
/// <summary> /// Initializes a new instance of the <see cref="HKDF"/> class. /// </summary> /// <param name="hmac">The HMAC hash function to use.</param> /// <param name="ikm">input keying material.</param> /// <param name="salt">optional salt value (a non-secret random value); if not provided, it is set to a string of HMAC.HashSize/8 zeros.</param> public HKDF(HMAC hmac, byte[] ikm, byte[] salt = null) { this.hmac = hmac; this.hashLength = hmac.HashSize / 8; // now we compute the PRK hmac.Key = salt ?? new byte[this.hashLength]; this.prk = hmac.ComputeHash(ikm); }
public HKDF(Func<HMAC> hmacFactory, byte[] ikm, byte[] salt = null, byte[] context = null) { hmac = hmacFactory(); hashLength = hmac.OutputBlockSize; hmac.Key = salt ?? new byte[hashLength]; hmac.Key = hmac.ComputeHash(ikm); // re-keying hmac with PRK this.context = context; Reset(); }
public static bool IsTokenValid(string token, string ip, string userAgent) { bool result = false; try { // Base64 decode the string, obtaining the token:username:timeStamp. string key = Encoding.UTF8.GetString(Convert.FromBase64String(token)); // Split the parts. string[] parts = key.Split(new char[] { ':' }); if (parts.Length == 3) { // Get the hash message, username, and timestamp. string hash = parts[0]; string username = parts[1]; long ticks = long.Parse(parts[2]); DateTime timeStamp = new DateTime(ticks); // Ensure the timestamp is valid. bool expired = Math.Abs((DateTime.UtcNow - timeStamp).TotalMinutes) > _expirationMinutes; if (!expired) { String passwordEnc = string.Empty; string hashLeft = string.Empty; using (HMAC hmac = HMACSHA256.Create(_alg)) { hmac.ComputeHash(Encoding.UTF8.GetBytes(hash)); hashLeft = Convert.ToBase64String(hmac.Hash); } using (var ctx = new GASEntities()) { if (username.All(char.IsDigit)) { passwordEnc = (from u in ctx.Users where u.UserMobile == username select u.Password.ToString()).First(); } else { passwordEnc = (from u in ctx.Users where u.UserEmail == username select u.Password.ToString()).First(); } } if (!string.IsNullOrEmpty(passwordEnc)) { string computedToken = GenerateTokenUsingHashPassword(username, passwordEnc, ip, userAgent, ticks); // Compare the computed token with the one supplied and ensure they match. result = (token == computedToken); } } } } catch { } return(result); }
public string NewSignature(out long nonce) { var n = Nonce.Next; var bytes = EncodingHelpers.EncodeString(string.Format("{0}{1}{2}", n, Username, ApiKey)); var hash = _hmac.ComputeHash(bytes); nonce = n; // Hexencode hash return(string.Concat(hash.Select(b => b.ToString("X2")))); }
protected void VerifyHmac_KeyAlreadySet( HMAC hmac, int testCaseId, string digest) { byte[] digestBytes = ByteUtils.HexToByteArray(digest); byte[] computedDigest; computedDigest = hmac.ComputeHash(_testData[testCaseId]); Assert.Equal(digestBytes, computedDigest); }
public static void VerifyTrivialHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } }