public byte[] Compute(int bytes, byte[] secret, string label, byte[][] seeds) { /* SEEDSを再構成 */ byte[][] new_seeds = new byte[seeds.Length + 1][]; new_seeds[0] = System.Text.Encoding.ASCII.GetBytes (label); for (int i = 0; i < seeds.Length; i ++) new_seeds[i + 1] = seeds[i]; /* secretを分割 */ byte[] S1 = new byte[secret.Length >> 1]; byte[] S2 = new byte[secret.Length >> 1]; Buffer.BlockCopy (secret, 0, S1, 0, S1.Length); Buffer.BlockCopy (secret, S1.Length, S2, 0, S2.Length); /* P_SHA1とP_MD5を計算 */ byte[] pSHA1, pMD5; using (HMACSHA1 hmacSHA1 = new HMACSHA1 (S2, true)) using (HMACMD5 hmacMD5 = new HMACMD5 (S1)) { pSHA1 = Compute_PHash (bytes, new_seeds, hmacSHA1, 20); pMD5 = Compute_PHash (bytes, new_seeds, hmacMD5, 16); } /* PRFを算出 */ byte[] prf = new byte[bytes]; for (int i = 0; i < prf.Length; i++) prf[i] = (byte)(pSHA1[i] ^ pMD5[i]); return prf; }
public static string CryptoMD5(string TextToCryptograph) { var md5 = new HMACMD5(); byte[] passwordArray = System.Text.Encoding.Default.GetBytes(TextToCryptograph); return Convert.ToBase64String(md5.ComputeHash(passwordArray)); }
// Computes a keyed hash for a source file, creates a target file with the keyed hash // prepended to the contents of the source file, then decrypts the file and compares // the source and the decrypted files. /// <summary> /// 文件加密 /// </summary> /// <param name="key"></param> /// <param name="sourceFile">待加密的文件</param> /// <param name="destFile">加密后的文件</param> public static void EncodeFile(byte[] key, String sourceFile, String destFile) { // Initialize the keyed hash object. HMACMD5 myhmacMD5 = new HMACMD5(key); FileStream inStream = new FileStream(sourceFile, FileMode.Open); FileStream outStream = new FileStream(destFile, FileMode.Create); // Compute the hash of the input file. byte[] hashValue = myhmacMD5.ComputeHash(inStream); // Reset inStream to the beginning of the file. inStream.Position = 0; // Write the computed hash value to the output file. outStream.Write(hashValue, 0, hashValue.Length); // Copy the contents of the sourceFile to the destFile. int bytesRead; // read 1K at a time byte[] buffer = new byte[1024]; do { // Read from the wrapping CryptoStream. bytesRead = inStream.Read(buffer, 0, 1024); outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); myhmacMD5.Clear(); // Close the streams inStream.Close(); outStream.Close(); return; }
public static string ComputeHashDigest(string hashString, string preSharedKey, HashMethod hashMethod) { byte[] key = StringToByteArray(preSharedKey); byte[] data = StringToByteArray(hashString); byte[] hashDigest; switch (hashMethod) { case HashMethod.HMACMD5: hashDigest = new HMACMD5(key).ComputeHash(data); break; case HashMethod.HMACSHA1: hashDigest = new HMACSHA1(key).ComputeHash(data); break; case HashMethod.MD5: hashDigest = new MD5CryptoServiceProvider().ComputeHash(data); break; case HashMethod.SHA1: hashDigest = new SHA1CryptoServiceProvider().ComputeHash(data); break; default: throw new InvalidOperationException("Invalid hash method"); } return (ByteArrayToHexString(hashDigest)); }
public static string HMACMD5(string key, string message) { using (var hasher = new crypto.HMACMD5(Encoding.UTF8.GetBytes(key))) { return(hasher.ComputeHash(Encoding.UTF8.GetBytes(message)).ToHexString()); } }
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 string signMD5(Dictionary<string, string> paramDic, string SecurityKey, bool isContent = false) { byte[] signatureKey = Encoding.UTF8.GetBytes(SecurityKey);//此处用自己的签名密钥 List<string> list = new List<string>(); foreach (KeyValuePair<string, string> kv in paramDic) { if (kv.Key.ToLower() != "sign") list.Add(kv.Key + kv.Value); } list.Sort(); StringBuilder tmp = new StringBuilder(); foreach (string kvstr in list) { tmp.Append(kvstr); } //HMAC-MD5 HMACMD5 hmacmd5 = new HMACMD5(signatureKey); hmacmd5.ComputeHash(Encoding.UTF8.GetBytes(tmp.ToString())); /* hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(urlPath)); foreach (string kvstr in list) { hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(kvstr)); } */ byte[] hash = hmacmd5.Hash; //TO HEX return BitConverter.ToString(hash).Replace("-", string.Empty).ToUpper(); }
// Decrypt the encoded file and compare to original file. /// <summary> /// 检查文件是否被篡改 /// </summary> /// <param name="key"></param> /// <param name="sourceFile"></param> /// <returns>true文件与哈希值一致, false不一致</returns> public static bool DecodeFile(byte[] key, String sourceFile) { // Initialize the keyed hash object. HMACMD5 hmacMD5 = new HMACMD5(key); // Create an array to hold the keyed hash value read from the file. byte[] storedHash = new byte[hmacMD5.HashSize / 8]; // Create a FileStream for the source file. FileStream inStream = new FileStream(sourceFile, FileMode.Open); // Read in the storedHash. inStream.Read(storedHash, 0, storedHash.Length); // Compute the hash of the remaining contents of the file. // The stream is properly positioned at the beginning of the content, // immediately after the stored hash value. byte[] computedHash = hmacMD5.ComputeHash(inStream); // compare the computed hash with the stored value for (int i = 0; i < storedHash.Length; i++) { if (computedHash[i] != storedHash[i]) { Console.WriteLine("Hash values differ! Encoded file has been tampered with!"); return false; } } Console.WriteLine("Hash values agree -- no tampering occurred."); return true; }
public override ISaslStep Next(byte[] bytesReceived) { var kMd5 = new HMACMD5(Encoding.UTF8.GetBytes(_password)); var computedHash = kMd5.ComputeHash(bytesReceived); var passwordHash = BitConverter.ToString(computedHash).ToLower().Replace("-", ""); return new SecondStep(Encoding.UTF8.GetBytes(string.Concat(_userName, ' ', passwordHash))); }
public bool ValidateResponse(string password) { HMACMD5 hmacmd5 = new HMACMD5(ASCIIEncoding.ASCII.GetBytes(password)); string expectedResponse = BitConverter.ToString(hmacmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Challenge))).Replace("-", ""); return string.Equals(expectedResponse, ChallengeResponse, StringComparison.InvariantCultureIgnoreCase); }
public override byte[] EvaluateChallenge(byte[] challenge) { if ( challenge == null || challenge.Length == 0 ) throw new ArgumentNullException("challenge"); NameCallback nameCB = new NameCallback(AuthorizationId); PasswordCallback pwdCB = new PasswordCallback(); ISaslCallback[] callbacks = { nameCB, pwdCB }; Handler.Handle(callbacks); string username = nameCB.Text; //Encode the Hashed Password as Hex byte[] passwd = Encoding.UTF8.GetBytes(ToHex(pwdCB.HashedText)); string s = System.Text.UTF8Encoding.UTF8.GetString(challenge); using ( HMAC hmac = new HMACMD5(passwd) ) { byte[] value = hmac.ComputeHash(challenge); string encoded = ToHex(value); SetComplete(); return Encoding.UTF8.GetBytes(username + " " + encoded); } }
/// <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; }
private static byte[] CreateHash(string unHashed) { var md5Hasing = new System.Security.Cryptography.HMACMD5(); var data = UTF8Encoding.UTF8.GetBytes(unHashed); data = md5Hasing.ComputeHash(data); return(data); }
public static string Hash(string key, string message) { UTF8Encoding encoding = new UTF8Encoding(); var messageBytes = encoding.GetBytes(message); var md5Hasher = new HMACMD5(encoding.GetBytes(key)); var hashBytes = md5Hasher.ComputeHash(messageBytes); return new string(hashBytes.SelectMany(b => b.ToString("X2")).ToArray()).ToLower(); }
public void CheckB (string testName, byte[] key, byte[] data, byte[] result) { algo = new HMACMD5 (); algo.Key = key; byte[] hmac = algo.ComputeHash (data, 0, data.Length); AssertEquals (testName + "b1", result, hmac); AssertEquals (testName + "b2", result, algo.Hash); }
public byte[] HashingAMessageWithASecretKey(byte[] iterationNumberByte, byte[] userIdByte) { using (var hmac = new HMACMD5(userIdByte)) { byte[] hash = hmac.ComputeHash(iterationNumberByte); return hash; } }
/** * * This is the constructor of the class * Three parameters are needed to build an object of this type * * @param key this represents your private. You should contact the NitroSell Support Team to request one. * @param userid this represents your User ID as assigned by the retailer to which you would like to query his data * @param webstoreUrl this is the URL of the WebStore that you would like to query */ public NScAPIWrapper(string key, string userid, string webstoreUrl) { this._key = key; this._userid = userid; this._webstoreUrl = webstoreUrl; var keyByte = encoding.GetBytes(key); this._hmacmd5 = new HMACMD5(keyByte); }
public override void Initialize() { base.Initialize(); if (md5 == null) md5 = new HMACMD5(); else md5.Initialize(); }
/// <summary> /// Creates an HMAC-MD5 fingerprint of the given data with the given key using the specified encoding /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <param name="enc"></param> /// <returns></returns> public static string HMACMD5(this string data, string key, Encoding enc) { var hmacKey = enc.GetBytes(key); var hmacData = enc.GetBytes(data); using (var hmacMd5 = new HMACMD5(hmacKey)) { return hmacMd5.ComputeHash(hmacData).ToHex().ToLower(); } }
public void Constructors () { algo = new HMACMD5 (); Assert.IsNotNull (algo, "HMACMD5 ()"); byte[] key = new byte [8]; algo = new HMACMD5 (key); Assert.IsNotNull (algo, "HMACMD5 (key)"); }
/// <summary> /// Decrypt the encoded file and compare to original file. It returns false if the file is corrupted. /// </summary> /// <param name="key">The key used to encode the file</param> /// <param name="sourceFile">The file to decrypt complete path</param> /// <param name="destFile">Destination file complete path. If the file doesn't exist, it creates it</param> /// <returns></returns> public bool DecodeFile(string key, String sourceFile, String destFile) { if (sourceFile.IsNullOrWhiteSpace() || !File.Exists(sourceFile)) throw new FileNotFoundException("Cannot find the specified source file", sourceFile ?? "null"); if (destFile.IsNullOrWhiteSpace()) throw new ArgumentException("Please specify the path of the output path", nameof(destFile)); if (string.IsNullOrEmpty(key)) throw new ArgumentException("Please specify the key", nameof(key)); // Create a key using a random number generator. This would be the // secret key shared by sender and receiver. byte[] secretkey = key.ToByteArray(); // Initialize the keyed hash object. HMACMD5 hmacMD5 = new HMACMD5(secretkey); // Create an array to hold the keyed hash value read from the file. byte[] storedHash = new byte[hmacMD5.HashSize / 8]; // Create a FileStream for the source file. FileStream inStream = new FileStream(sourceFile, FileMode.Open); // Read in the storedHash. inStream.Read(storedHash, 0, storedHash.Length); // Compute the hash of the remaining contents of the file. // The stream is properly positioned at the beginning of the content, // immediately after the stored hash value. byte[] computedHash = hmacMD5.ComputeHash(inStream); // compare the computed hash with the stored value int i; for (i = 0; i < storedHash.Length; i++) { if (computedHash[i] != storedHash[i]) { inStream.Close(); return false; } } FileStream outStream = new FileStream(destFile, FileMode.Create); // Reset inStream to the beginning of the file. inStream.Position = i; // Copy the contents of the sourceFile to the destFile. int bytesRead; // read 1K at a time byte[] buffer = new byte[1024]; do { // Read from the wrapping CryptoStream. bytesRead = inStream.Read(buffer, 0, 1024); outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); // Close the streams inStream.Close(); outStream.Close(); return true; }
/// <summary> /// Authenticate packet and return authentication parameters value to the caller /// </summary> /// <param name="authenticationSecret">User authentication secret</param> /// <param name="engineId">SNMP agent authoritative engine id</param> /// <param name="wholeMessage">Message to authenticate</param> /// <returns>Authentication parameters value</returns> public byte[] authenticate(byte[] authenticationSecret, byte[] engineId, byte[] wholeMessage) { byte[] result = new byte[12]; byte[] authKey = PasswordToKey(authenticationSecret, engineId); HMACMD5 md5 = new HMACMD5(authKey); byte[] hash = md5.ComputeHash(wholeMessage); // copy 12 bytes of the hash into the wholeMessage Buffer.BlockCopy(hash, 0, result, 0, 12); return result; }
/// <summary> /// /// </summary> /// <param name="plainText"></param> /// <param name="key"></param> /// <param name="encoding"></param> /// <param name="encryptedType"></param> /// <returns></returns> public override string DoEncrypt(string plainText, string key, Encoding encoding, DataMode encryptedType) { byte[] keyByte = encoding.GetBytes(key); HMACMD5 hmacMD5 = new HMACMD5(keyByte); byte[] messageBytes = encoding.GetBytes(plainText); byte[] hashMessage = hmacMD5.ComputeHash(messageBytes); return BytesToString(hashMessage, encoding, encryptedType); }
/// <summary> /// Creates a unique guid based on any string. /// </summary> public static Guid CreateGuidFromString(string input) { if (string.IsNullOrEmpty(input)) throw new ArgumentNullException("input"); HMACMD5 hmacmd5 = new HMACMD5("This is used as a static salt".GetBytes()); byte[] inputData = input.GetBytes(); byte[] hash = hmacmd5.ComputeHash(inputData); return new Guid(hash); }
/// <summary> /// Computes the <see cref="HMACMD5"/> hash for the current byte array using the managed library. /// </summary> /// <param name="input">An array of 8-bit unsigned integers.</param> /// <param name="key">The key to use in the hash algorithm.</param> /// <param name="offset">The offset into the byte array from which to begin using data.</param> /// <param name="count">The number of bytes in the array to use as data.</param> /// <returns>The computed hash code.</returns> public static byte[] ComputeHMACMD5Hash(this byte[] input, byte[] key, int offset, int count) { var hash = new HMACMD5(key); input = input .Skip(offset) .Take(count) .ToArray(); return hash.ComputeHash(input); }
public static string EncodePassword(string password) { var salt = System.Text.Encoding.UTF8.GetBytes("&^%£$Ugdsgs:;"); var userpassword = System.Text.Encoding.UTF8.GetBytes(password); var hmacMD5 = new HMACMD5(salt); var saltedHash = hmacMD5.ComputeHash(userpassword); //Convert encoded bytes back to a 'readable' string return Convert.ToBase64String(saltedHash); }
/// <summary> /// HMACMD5 encrypt /// </summary> /// <param name="data">the date to encrypt</param> /// <param name="key">the key used in HMACMD5</param> /// <returns></returns> public static string GetEncryptResult(string data, string key) { HMACMD5 source = new HMACMD5(Encoding.UTF8.GetBytes(key)); byte[] buff = source.ComputeHash(Encoding.UTF8.GetBytes(data)); string result = string.Empty; for (int i = 0; i < buff.Length; i++) { result += buff[i].ToString("X2"); // hex format } return result; }
public static Byte[] CRAM_MD5(String Token, String Login, String Password) { var HMAC_MD5 = new HMACMD5(Password.ToUTF8Bytes()); var digest = HMAC_MD5.ComputeHash(Token.ToUTF8Bytes()); // result := login[space]digest return Login.ToUTF8Bytes(). Concat(new Byte[1] { 0x20 }). Concat(digest.ToHexString().ToUTF8Bytes()). ToArray(); }
public void Invariants () { algo = new HMACMD5 (); AssertEquals ("HMACMD5.CanReuseTransform", true, algo.CanReuseTransform); AssertEquals ("HMACMD5.CanTransformMultipleBlocks", true, algo.CanTransformMultipleBlocks); AssertEquals ("HMACMD5.HashName", "MD5", algo.HashName); AssertEquals ("HMACMD5.HashSize", 128, algo.HashSize); AssertEquals ("HMACMD5.InputBlockSize", 1, algo.InputBlockSize); AssertEquals ("HMACMD5.OutputBlockSize", 1, algo.OutputBlockSize); AssertEquals ("HMACMD5.ToString()", "System.Security.Cryptography.HMACMD5", algo.ToString ()); }
protected override void Dispose(bool disposing) { if (disposing) { if (md5 != null) { md5.Clear(); md5 = null; } } base.Dispose(disposing); }
public void Invariants () { algo = new HMACMD5 (); Assert.IsTrue (algo.CanReuseTransform, "HMACMD5.CanReuseTransform"); Assert.IsTrue (algo.CanTransformMultipleBlocks, "HMACMD5.CanTransformMultipleBlocks"); Assert.AreEqual ("MD5", algo.HashName, "HMACMD5.HashName"); Assert.AreEqual (128, algo.HashSize, "HMACMD5.HashSize"); Assert.AreEqual (1, algo.InputBlockSize, "HMACMD5.InputBlockSize"); Assert.AreEqual (1, algo.OutputBlockSize, "HMACMD5.OutputBlockSize"); Assert.AreEqual ("System.Security.Cryptography.HMACMD5", algo.ToString (), "HMACMD5.ToString()"); }
private static string ComputeHmacMd5(byte[] data, byte[] key) { var hmacmd5 = new HMACMD5(key); var hmacData = hmacmd5.ComputeHash(data); var result = new StringBuilder(); foreach (var b in hmacData) { result.Append(b.ToString("x2")); } return result.ToString(); }
/// <summary> /// 使用 MD5 算法计算数据的 HMAC码; /// </summary> /// <param name="key"></param> /// <param name="data"></param> /// <returns></returns> public static byte[] HmacSignDataUsingMd5(byte[] key, byte[] data) { HMAC alg = new System.Security.Cryptography.HMACMD5(); //设置密钥 alg.Key = key; //计算哈希值 var hash = alg.ComputeHash(data); //返回具有签名的数据(哈希值+数组本身) // return hash.Concat(data).ToArray(); return(hash.ToArray()); }
/// <summary> /// 加密 /// </summary> /// <param name="key">公共key</param> /// <param name="value">值</param> /// <returns>加密后的值</returns> public static string HMACMD5(string key, string value) { System.Security.Cryptography.HMACMD5 objHMAC = new System.Security.Cryptography.HMACMD5(Encoding.GetEncoding("UTF-8").GetBytes(key)); byte[] hashValue = objHMAC.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(value)); StringBuilder objSB = new StringBuilder(); foreach (byte objB in hashValue) { objSB.AppendFormat("{0:x2}", objB); } return(objSB.ToString()); }
private static string Encrypt(string secretSalt, string clearSecret) { try { string returnValue = string.Empty; secretSalt = GetHexString(secretSalt); clearSecret = GetHexString(clearSecret); System.Security.Cryptography.HMACMD5 hash = new System.Security.Cryptography.HMACMD5(); byte[] returnBytes = new byte[secretSalt.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) { returnBytes[i] = Convert.ToByte(secretSalt.Substring(i * 2, 2), 16); } hash.Key = returnBytes; string encodedSecret = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(clearSecret))); #pragma warning disable CA1305 // Specify IFormatProvider string newSecret = string.Format("{0}{1}", secretSalt, encodedSecret); #pragma warning restore CA1305 // Specify IFormatProvider byte[] bytes = Encoding.UTF8.GetBytes(newSecret); StringBuilder sb = new StringBuilder(); foreach (byte bt in bytes) { #pragma warning disable CA1305 // Specify IFormatProvider sb.AppendFormat("{0:x2}", bt); #pragma warning restore CA1305 // Specify IFormatProvider } returnValue = sb.ToString(); return(returnValue); } catch (Exception e) { if (e.InnerException != null) { throw e.InnerException; } throw; } }