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); } }
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 static string CryptoMD5(string TextToCryptograph) { var md5 = new HMACMD5(); byte[] passwordArray = System.Text.Encoding.Default.GetBytes(TextToCryptograph); return Convert.ToBase64String(md5.ComputeHash(passwordArray)); }
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(); }
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()); } }
// 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; }
// 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 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 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 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 byte[] HashingAMessageWithASecretKey(byte[] iterationNumberByte, byte[] userIdByte) { using (var hmac = new HMACMD5(userIdByte)) { byte[] hash = hmac.ComputeHash(iterationNumberByte); return hash; } }
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 void CheckA (string testName, byte[] key, byte[] data, byte[] result) { algo = new HMACMD5 (); algo.Key = key; byte[] hmac = algo.ComputeHash (data); AssertEquals (testName + "a1", result, hmac); AssertEquals (testName + "a2", result, algo.Hash); }
/// <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(); } }
/// <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; }
public static byte[] GetMic( byte[] key, byte[] input, int usage) { // get sign key byte[] signatureData = Encoding.ASCII.GetBytes(ConstValue.SIGNATURE_KEY); HMACMD5 hmacMd5 = new HMACMD5(key); byte[] signKey = hmacMd5.ComputeHash(signatureData); hmacMd5.Key = signKey; // toBeHashedData = keyUsageData + inputData byte[] usageData = BitConverter.GetBytes(usage); byte[] toBeHashedData = ArrayUtility.ConcatenateArrays(usageData, input); // hash result byte[] md5Hash = CryptoUtility.ComputeMd5(toBeHashedData); return hmacMd5.ComputeHash(md5Hash); }
/// <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> /// 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 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 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> /// 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> /// 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 string encryptPassword(string password , string saltFirst) { byte[] salt = Encoding.ASCII.GetBytes(saltFirst); var passwordEncryp = System.Text.Encoding.UTF8.GetBytes(password); var hmacMD5 = new HMACMD5(salt); var saltedHash = hmacMD5.ComputeHash(passwordEncryp); var saitPlusHash = Convert.ToBase64String(saltedHash) + ":" + saltFirst; return saitPlusHash; }
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()); }
internal static string GenerateKey(string minResult) { string hash; using (var cryto = new HMACMD5(Encoding.Default.GetBytes(CdnHelpersContext.Current.Configuration.HashKey))) { var bytes = cryto.ComputeHash(Encoding.UTF8.GetBytes(minResult)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { sb.Append(bytes[i].ToString("x2")); } hash = sb.ToString(); } return hash; }
/// <summary> /// Cram-MD5に従って文字列を変換します。 /// </summary> /// <param name="text"></param> /// <param name="key"></param> /// <returns></returns> public static String ToCramMd5String(String text, String key) { StringBuilder sb = new StringBuilder(128); Byte[] bb = null; HMACMD5 md5 = new HMACMD5(Encoding.UTF8.GetBytes(key)); // Base64デコードしたチャレンジコードに対してパスワードをキーとしたHMAC-MD5ハッシュ値を計算する bb = md5.ComputeHash(Convert.FromBase64String(text)); // 計算したHMAC-MD5ハッシュ値のbyte[]を16進表記の文字列に変換する for (int i = 0; i < bb.Length; i++) { sb.Append(bb[i].ToString("x02")); } return sb.ToString(); }
public string GetHashedValue(string value, string salt) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } var valueBytes = Encoding.UTF8.GetBytes(value); var saltBytes = Encoding.UTF8.GetBytes(salt); var hmacMd5 = new HMACMD5(saltBytes); var saltedHash = hmacMd5.ComputeHash(valueBytes); return Convert.ToBase64String(saltedHash); }
/// <summary> /// Creates an MD5 hash of a string using a salt. If no salt is specified, one is created. /// </summary> /// <param name="input">The plain text input to hash.</param> /// <param name="salt">The salt used to create hashed string.</param> /// <param name="encoding">The encoding used to gather the bytes. Defaults to UTF8.</param> /// <returns>A hashed version of the input string.</returns> public static string Md5Hash(string input, ref string salt, Encoding encoding = null) { if (encoding == null) encoding = System.Text.Encoding.UTF8; if (string.IsNullOrWhiteSpace(salt)) salt = KeyGen.Generate(15, KeyGen.AllCharacters); byte[] saltBytes = encoding.GetBytes(salt), inputBytes = encoding.GetBytes(input); var hmacMd5 = new HMACMD5(saltBytes); byte[] hash = hmacMd5.ComputeHash(inputBytes); return Convert.ToBase64String(hash); //encoding.GetString(hash); }
private static string getHMACMD5Signature(string methodPath, string additionalParameters, string timeStamp, string accessKey, string secretKey) { //build the uri to sign, exclude the domain part, start with '/' var uristring = new StringBuilder(); //will hold the final uri uristring.Append(methodPath.StartsWith("/") ? "" : "/"); //start with a slash uristring.Append(methodPath); //this is the address of the resource uristring.Append("?clientid=" + HttpUtility.UrlEncode(accessKey)); //url encoded parameters uristring.Append("×tamp=" + HttpUtility.UrlEncode(timeStamp)); uristring.Append(additionalParameters); //calculate hmac signature byte[] secretBytes = Encoding.ASCII.GetBytes(secretKey); var hmac = new HMACMD5(secretBytes); byte[] dataBytes = Encoding.ASCII.GetBytes(uristring.ToString()); byte[] computedHash = hmac.ComputeHash(dataBytes); string computedHashString = Convert.ToBase64String(computedHash); return computedHashString; }
/// <summary> /// Encrypts the key/value pair supplied using HMAC-MD5 /// </summary> /// <param name="key">key</param> /// <param name="value">value</param> /// <returns></returns> public static string EncryptHMAC(string key, string value) { // The first two lines take the input values and convert them from strings to Byte arrays byte[] HMACkey = (new System.Text.ASCIIEncoding()).GetBytes(key); byte[] HMACdata = (new System.Text.ASCIIEncoding()).GetBytes(value); // create a HMACMD5 object with the key set HMACMD5 myhmacMD5 = new HMACMD5(HMACkey); //calculate the hash (returns a byte array) byte[] HMAChash = myhmacMD5.ComputeHash(HMACdata); //loop through the byte array and add append each piece to a string to obtain a hash string string fingerprint = ""; for (int i = 0; i < HMAChash.Length; i++) { fingerprint += HMAChash[i].ToString("x").PadLeft(2, '0'); } return fingerprint; }
public override string Encrypt(string input) { using (var hmacMd5 = new HMACMD5(Salt)) { // Convert the input string to a byte array and compute the hash. byte[] data = hmacMd5.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.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; } }