/* * Keyed Hashing * */ public byte[] HashFile(byte[] _key) { byte[] hashbyte = { }; //Ensure that the source file exists if (false == File.Exists(_SourceFilepath)) { return(hashbyte); } try { //Open the Source file FileStream fsSource = File.OpenRead(_SourceFilepath); //Create the default hash algorithm KeyedHashAlgorithm hash = KeyedHashAlgorithm.Create(); //Set the key hash.Key = _key; //Compute the hash hashbyte = hash.ComputeHash(fsSource); //close the streams fsSource.Close(); } catch (Exception) { } return(hashbyte); }
/// <summary> /// Compute and return the hash of a data blob using the specified key /// </summary> /// <param name="algorithm">Algorithm to use for hashing</param> /// <param name="key">Hash key</param> /// <param name="data">Data blob</param> /// <returns>Hash of the data</returns> private static byte[] ComputeHash(string algorithm, byte[] key, byte[] data) { KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(algorithm); kha.Key = key; return(kha.ComputeHash(data)); }
/// <summary> /// Compute and return the hash of a data blob using the specified algorithm /// and key /// </summary> /// <param name="algorithm">Algorithm to use for hashing</param> /// <param name="key">Hash key</param> /// <param name="data">Data blob</param> /// <returns>Hash of the data</returns> protected byte[] ComputeKeyedHash(string algorithm, byte[] key, byte[] data) { var kha = KeyedHashAlgorithm.Create(algorithm); kha.Key = key; return(kha.ComputeHash(data)); }
/// <summary> /// Computes a hash-based message authentication code /// </summary> /// <param name="data">Input to compute the hash code for</param> /// <param name="key">Signing key</param> /// <param name="algorithmName">Hashing algorithm to use</param> /// <returns>Computed hash code in bytes</returns> public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName) { if (key == null || key.Length == 0) { throw new ArgumentNullException("key", "Please specify a Secret Signing Key."); } if (data == null || data.Length == 0) { throw new ArgumentNullException("data", "Please specify data to sign."); } KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture)); if (null == algorithm) { throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use."); } try { algorithm.Key = key; byte[] bytes = algorithm.ComputeHash(data); return(bytes); } finally { algorithm.Clear(); } }
/** * Add authentication related and version parameters */ private void AddRequiredParameters(IDictionary <string, string> parameters) { if (String.IsNullOrEmpty(this.awsAccessKeyId)) { throw new AmazonAutoScalingException("The AWS Access Key ID cannot be NULL or a Zero length string"); } parameters["AWSAccessKeyId"] = this.awsAccessKeyId; parameters["SignatureVersion"] = config.SignatureVersion; parameters["SignatureMethod"] = config.SignatureMethod; parameters["Timestamp"] = AWSSDKUtils.FormattedCurrentTimestampISO8601; parameters["Version"] = config.ServiceVersion; if (!config.SignatureVersion.Equals("2")) { throw new AmazonAutoScalingException("Invalid Signature Version specified"); } string toSign = AWSSDKUtils.CalculateStringToSignV2(parameters, config.ServiceURL); KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(config.SignatureMethod.ToUpper()); string auth; if (config.UseSecureStringForAwsSecretKey) { auth = AWSSDKUtils.HMACSign(toSign, awsSecretAccessKey, algorithm); } else { auth = AWSSDKUtils.HMACSign(toSign, clearAwsSecretAccessKey, algorithm); } parameters["Signature"] = auth; }
public static string GetHash(this string input, HashType hashType) { byte[] inputBytes = input.ToByteArray(); switch (hashType) { case HashType.HMAC: return(Convert.ToBase64String(HMAC.Create().ComputeHash(inputBytes))); case HashType.HMACMD5: return(Convert.ToBase64String(HMAC.Create().ComputeHash(inputBytes))); case HashType.HMACSHA1: return(Convert.ToBase64String(HMAC.Create().ComputeHash(inputBytes))); case HashType.HMACSHA256: return(Convert.ToBase64String(HMAC.Create().ComputeHash(inputBytes))); case HashType.HMACSHA384: return(Convert.ToBase64String(HMAC.Create().ComputeHash(inputBytes))); case HashType.HMACSHA512: return(Convert.ToBase64String(HMAC.Create().ComputeHash(inputBytes))); case HashType.MACTripleDES: return(Convert.ToBase64String(KeyedHashAlgorithm.Create().ComputeHash(inputBytes))); case HashType.MD5: return(Convert.ToBase64String(MD5.Create().ComputeHash(inputBytes))); case HashType.RIPEMD160: return(Convert.ToBase64String(RIPEMD160.Create().ComputeHash(inputBytes))); case HashType.SHA1: return(Convert.ToBase64String(SHA1.Create().ComputeHash(inputBytes))); case HashType.SHA256: return(Convert.ToBase64String(SHA256.Create().ComputeHash(inputBytes))); case HashType.SHA384: return(Convert.ToBase64String(SHA384.Create().ComputeHash(inputBytes))); case HashType.SHA512: return(Convert.ToBase64String(SHA512.Create().ComputeHash(inputBytes))); default: return(Convert.ToBase64String(inputBytes)); } }
public static string getPassword(string sk) { TimeSpan ts = DateTime.UtcNow - EPOCH_START; long timestamp = Convert.ToInt64(ts.TotalMilliseconds); KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create("HMACSHA1"); if (null == algorithm) { throw new InvalidOperationException("HMACSHA1 not exist!"); } try { algorithm.Key = Encoding.UTF8.GetBytes(timestamp.ToString()); byte[] bytes = algorithm.ComputeHash(Encoding.UTF8.GetBytes(sk)); string signature = byteArrayToUpperString(bytes); // Console.WriteLine(signature); StringBuilder data = new StringBuilder(64); data.Append(signature).Append(COLON).Append(timestamp); return(Convert.ToBase64String(Encoding.UTF8.GetBytes(data.ToString()))); } finally { algorithm.Clear(); } }
/// <summary> /// Get the <see cref="HashAlgorithm"/> associated to the <see cref="HashAlgorithmEnum"/> /// </summary> /// <param name="algorithm">Algorithm request</param> /// <returns></returns> static public HashAlgorithm GetAlgorithm(HashAlgorithmEnum algorithm) { switch (algorithm) { case HashAlgorithmEnum.MD5: return(MD5.Create()); case HashAlgorithmEnum.SHA1: return(SHA1.Create()); case HashAlgorithmEnum.SHA256: return(SHA256.Create()); case HashAlgorithmEnum.SHA384: return(SHA384.Create()); case HashAlgorithmEnum.SHA512: return(SHA512.Create()); case HashAlgorithmEnum.RIPEMD160: return(RIPEMD160.Create()); case HashAlgorithmEnum.KeyedHashAlgorithm: return(KeyedHashAlgorithm.Create()); default: return(SHA256.Create()); } }
private static byte[] HmacSha256(String data, byte[] key) { var hmacSha256 = KeyedHashAlgorithm.Create("HmacSHA256"); hmacSha256.Key = key; return(hmacSha256.ComputeHash(Encoding.UTF8.GetBytes(data))); }
protected override string ComputeSignatureCore(string key, string data) { Debug.Assert(!string.IsNullOrEmpty(data)); using (KeyedHashAlgorithm algorithm = new HMACSHA1()) { algorithm.Key = _encoding.GetBytes(key); //var hash = algorithm.ComputeHash(_encoding.GetBytes(data)); //var returnStr = new StringBuilder(""); //for (int i = 0; i < hash.Length; i++) //{ // returnStr.Append(hash[i].ToString("X2").ToUpper()); //} //return returnStr.ToString(); return(Convert.ToBase64String(algorithm.ComputeHash(_encoding.GetBytes(data)))); } using (KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create( this.SignatureMethod.ToString().ToUpperInvariant())) { algorithm.Key = _encoding.GetBytes(key.ToCharArray()); return(Convert.ToBase64String( algorithm.ComputeHash(_encoding.GetBytes(data.ToCharArray())))); } }
/// <summary> /// Serializes a processor to a string. The string is encrypted and validated. /// Thanks to Dean Brettle for help with this http://www.brettle.com. /// </summary> /// <param name="processor">Processor to serialize.</param> /// <returns>The serialized processor.</returns> internal string SerializeProcessor(IFileProcessor processor) { SettingsStorageObject so = new SettingsStorageObject(); MemoryStream ms = new MemoryStream(); MemoryStream outStream = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, processor); // Encrypt the serialized object MemoryStream cipherTextStream = new MemoryStream(); SymmetricAlgorithm cipher = SymmetricAlgorithm.Create(); cipher.Mode = CipherMode.CBC; cipher.Padding = PaddingMode.PKCS7; cipher.Key = DefaultEncryptionKey; CryptoStream cryptoStream = new CryptoStream(cipherTextStream, cipher.CreateEncryptor(), CryptoStreamMode.Write); byte[] cryptoBytes = ms.ToArray(); cryptoStream.Write(cryptoBytes, 0, cryptoBytes.Length); cryptoStream.Close(); so.CipherText = cipherTextStream.ToArray(); so.CipherIV = cipher.IV; // Generate a hash for the encrypted data KeyedHashAlgorithm kh = KeyedHashAlgorithm.Create(); kh.Key = DefaultValidationKey; so.Hash = kh.ComputeHash(so.CipherText); bf.Serialize(outStream, so); return(Convert.ToBase64String(outStream.ToArray())); }
private void BtnVerifica_Click(object sender, RoutedEventArgs e) { var algo = (cbAlgoritmos.SelectedValue as ComboBoxItem).Content.ToString(); try { var dir = new DirectoryInfo(txtDirectorio.Text); using (var algoritmo = KeyedHashAlgorithm.Create(algo)) { algoritmo.Key = Encoding.UTF8.GetBytes(txtClave.Text); foreach (FileInfo fInfo in dir.GetFiles()) { using (Stream fich = fInfo.Open(FileMode.Open)) { var nueva = Convert.ToBase64String(algoritmo.ComputeHash(fich)); var firma = lista.FirstOrDefault(o => o.Fichero == fInfo.Name); if (firma != null) { firma.Valido = firma.Firma == nueva; } } } } gFirmas.ItemsSource = null; gFirmas.ItemsSource = lista; } catch (Exception ex) { consola.Text = ex.Message; } }
public static byte[] HmacSHA256(string data, byte[] key) { KeyedHashAlgorithm keyedHashAlgorithm = KeyedHashAlgorithm.Create("HmacSHA256"); keyedHashAlgorithm.Key = key; return(keyedHashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(data))); }
public void Hash(byte[] temp) { using var DSACng = new DSACng(10); // Noncompliant {{Make sure this weak hash algorithm is not used in a sensitive context here.}} // ^^^^^^^^^^^^^^ using var DSACryptoServiceProvider = new DSACryptoServiceProvider(); // Noncompliant using var DSACreate = DSA.Create(); // Noncompliant using var DSACreateWithParam = DSA.Create("DSA"); // Noncompliant using var DSACreateFromName = (AsymmetricAlgorithm)CryptoConfig.CreateFromName("DSA"); // Noncompliant using var DSAAsymmetricAlgorithm = AsymmetricAlgorithm.Create("DSA"); // Noncompliant using var DSAAsymmetricAlgorithmWithNamespace = AsymmetricAlgorithm.Create("System.Security.Cryptography.DSA"); // Noncompliant using var HMACCreate = HMAC.Create(); // Noncompliant using var HMACCreateWithParam = HMAC.Create("HMACMD5"); // Noncompliant using var HMACMD5 = new HMACMD5(); // Noncompliant using var HMACMD5Create = HMACMD5.Create(); // Noncompliant using var HMACMD5CreateWithParam = HMACMD5.Create("HMACMD5"); // Noncompliant using var HMACMD5KeyedHashAlgorithm = KeyedHashAlgorithm.Create("HMACMD5"); // Noncompliant using var HMACMD5KeyedHashAlgorithmWithNamespace = KeyedHashAlgorithm.Create("System.Security.Cryptography.HMACMD5"); // Noncompliant using var HMACMD5CryptoConfig = (HashAlgorithm)CryptoConfig.CreateFromName("HMACMD5"); // Noncompliant using var HMACSHA1 = new HMACSHA1(); // Noncompliant using var HMACSHA1Create = HMACMD5.Create(); // Noncompliant using var HMACSHA1CreateWithParam = HMACMD5.Create("HMACSHA1"); // Noncompliant using var HMACSHA1KeyedHashAlgorithm = KeyedHashAlgorithm.Create("HMACSHA1"); // Noncompliant using var HMACSHA1KeyedHashAlgorithmWithNamespace = KeyedHashAlgorithm.Create("System.Security.Cryptography.HMACSHA1"); // Noncompliant using var HMACSHA1CryptoConfig = (HashAlgorithm)CryptoConfig.CreateFromName("HMACSHA1"); // Noncompliant using var HMACSHA256Create = HMACSHA256.Create("HMACSHA256"); using var HMACSHA256KeyedHashAlgorithm = KeyedHashAlgorithm.Create("HMACSHA256"); using var HMACSHA256KeyedHashAlgorithmWithNamespace = KeyedHashAlgorithm.Create("System.Security.Cryptography.HMACSHA256"); using var HMACSHA256CryptoConfig = (HashAlgorithm)CryptoConfig.CreateFromName("HMACSHA256"); using var MD5CryptoServiceProvider = new MD5CryptoServiceProvider(); // Noncompliant using var MD5CryptoConfig = (HashAlgorithm)CryptoConfig.CreateFromName("MD5"); // Noncompliant using var MD5HashAlgorithm = HashAlgorithm.Create("MD5"); // Noncompliant using var MD5HashAlgorithmWithNamespace = HashAlgorithm.Create("System.Security.Cryptography.MD5"); // Noncompliant using var MD5Create = MD5.Create(); // Noncompliant using var MD5CreateWithParam = MD5.Create("MD5"); // Noncompliant using var SHA1Managed = new SHA1Managed(); // Noncompliant using var SHA1Create = SHA1.Create(); // Noncompliant using var SHA1CreateWithParam = SHA1.Create("SHA1"); // Noncompliant using var SHA1HashAlgorithm = HashAlgorithm.Create("SHA1"); // Noncompliant using var SHA1HashAlgorithmWithNamespace = HashAlgorithm.Create("System.Security.Cryptography.SHA1"); // Noncompliant using var SHA1CryptoServiceProvider = new SHA1CryptoServiceProvider(); // Noncompliant using var sha256Managed = new SHA256Managed(); using var sha256HashAlgorithm = HashAlgorithm.Create("SHA256Managed"); using var sha256HashAlgorithmWithNamespace = HashAlgorithm.Create("System.Security.Cryptography.SHA256Managed"); var sha256CryptoConfig = CryptoConfig.CreateFromName("SHA256Managed"); HashAlgorithm hashAlgo = HashAlgorithm.Create(); var algoName = "MD5"; var md5Var = (HashAlgorithm)CryptoConfig.CreateFromName(algoName); // Noncompliant algoName = "SHA256Managed"; var SHA256ManagedVar = (HashAlgorithm)CryptoConfig.CreateFromName(algoName); }
public static string HashPassword(string pass, string salt, string hashAlgorithm, string macKey) { byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Encoding.Unicode.GetBytes(salt); byte[] dst = new byte[src.Length + bytes.Length]; Buffer.BlockCopy(src, 0, dst, 0, src.Length); Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); HashAlgorithm algorithm; if (hashAlgorithm.ToUpper().Contains("HMAC")) { if (string.IsNullOrEmpty(macKey)) { throw new ArgumentException("HMAC style hashing algorithm requires a fixed ValidationKey in the web.config or machine.config."); } KeyedHashAlgorithm keyedAlg = KeyedHashAlgorithm.Create(hashAlgorithm); keyedAlg.Key = HexToByte(macKey); algorithm = keyedAlg; } else { algorithm = HashAlgorithm.Create(hashAlgorithm); } byte[] inArray = algorithm.ComputeHash(dst); return(Convert.ToBase64String(inArray)); }
public ContosoKeyedHash(String keyedHashName, byte[] rgbKey) { // Make sure we know which algorithm to use if (rgbKey != null) { KeyValue = rgbKey; HashSizeValue = 160; // Create a KeyedHashAlgorithm encryptor if (keyedHashName == null) { //<Snippet2> keyedCrypto = KeyedHashAlgorithm.Create(); //</Snippet2> } else { //<Snippet1> keyedCrypto = KeyedHashAlgorithm.Create(keyedHashName); //</Snippet1> } } else { throw new ArgumentNullException("rgbKey"); } }
/// <summary> /// Calculates hash of data by key /// </summary> public byte[] ComputeKeyedHash(byte[] key, byte[] data) { KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(HMACSHA256); algorithm.Key = key; return(algorithm.ComputeHash(data)); }
public EncryptedPacket EncryptData(string original, RSAEncryption rsaEncryption) { //Bug 1: Hard coded key and initialization vector should not be used byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; byte[] iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; using (SymmetricAlgorithm aes = SymmetricAlgorithm.Create("AES")) { aes.Key = key; aes.IV = iv; EncryptedPacket encryptedPacket = new EncryptedPacket { Iv = aes.IV }; encryptedPacket.EncryptedData = _aesEncryption.EncryptStringToBytes_Aes(original, key, encryptedPacket.Iv); encryptedPacket.EncryptedSessionKey = rsaEncryption.EncryptData(aes.Key); //Bug 2: Weak hashing technique used using (KeyedHashAlgorithm hmac = KeyedHashAlgorithm.Create("HMACSHA1")) { hmac.Key = aes.Key; encryptedPacket.Hmac = hmac.ComputeHash(encryptedPacket.EncryptedData); } return(encryptedPacket); } }
public bool IsValid(string passwordSubmitted, string salt, byte[] password) { try { var plainText = Encoding.Default.GetBytes(passwordSubmitted + salt); var hashKey = Encoding.Default.GetBytes(HashKey); var keyedHashAlgorithm = KeyedHashAlgorithm.Create("HMACSHA1"); keyedHashAlgorithm.Key = hashKey; var hashedPassword = keyedHashAlgorithm.ComputeHash(plainText); var dbValue = password; if (CompareBytesArray(hashedPassword, dbValue)) { return(true); } return(false); } catch { //If something bad happens return false return(false); } }
public static void Main(string[] args) { // Create a byte array from the key string, which is the // second command-line argument. byte[] key = Encoding.Unicode.GetBytes(args[2]); // Create a KeyedHashAlgorithm derived object to generate the keyed // hash code for the input file. Pass the byte array representing the // key to the constructor. using (KeyedHashAlgorithm hashAlg = KeyedHashAlgorithm.Create(args[1])) { // Assign the key. hashAlg.Key = key; // Open a FileStream to read the input file; the file name is // specified by the first command-line argument. using (Stream file = new FileStream(args[0], FileMode.Open, FileAccess.Read)) { // Generate the keyed hash code of the file’s contents. byte[] hash = hashAlg.ComputeHash(file); // Display the keyed hash code to the console. Console.WriteLine(BitConverter.ToString(hash)); } } // Wait to continue. Console.WriteLine("\nMain method complete. Press Enter."); Console.ReadLine(); }
/// <summary> /// Computes a hash-based message authentication code /// </summary> /// <param name="data">Input to compute the hash code for</param> /// <param name="key">Signing key</param> /// <param name="algorithmName">Hashing algorithm to use</param> /// <returns>Computed hash code in base-64</returns> public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName) { if (String.IsNullOrEmpty(key)) { throw new ArgumentNullException("key", "Please specify a Secret Signing Key."); } if (data == null || data.Length == 0) { throw new ArgumentNullException("data", "Please specify data to sign."); } KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture)); if (null == algorithm) { throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use."); } try { algorithm.Key = Encoding.UTF8.GetBytes(key); byte[] bytes = algorithm.ComputeHash(data); return(Convert.ToBase64String(bytes)); } finally { algorithm.Clear(); } }
public string EncryptPassword(string pass, string salt) { byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Convert.FromBase64String(salt); byte[] inArray = null; KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(); algorithm.Key = new byte[64]; //compatible with mono if (algorithm.Key.Length == src.Length) { algorithm.Key = src; } else if (algorithm.Key.Length < src.Length) { byte[] dst = new byte[algorithm.Key.Length]; Buffer.BlockCopy(src, 0, dst, 0, dst.Length); algorithm.Key = dst; } else { int num2; byte[] buffer5 = new byte[algorithm.Key.Length]; for (int i = 0; i < buffer5.Length; i += num2) { num2 = Math.Min(src.Length, buffer5.Length - i); Buffer.BlockCopy(src, 0, buffer5, i, num2); } algorithm.Key = buffer5; } inArray = algorithm.ComputeHash(bytes); return(Convert.ToBase64String(inArray)); }
private static string ComputeSignature(string key, string data) { using var algorithm = KeyedHashAlgorithm.Create("HmacSHA1".ToUpperInvariant()); algorithm.Key = Encoding.UTF8.GetBytes(key.ToCharArray()); return(Convert.ToBase64String( algorithm.ComputeHash(Encoding.UTF8.GetBytes(data.ToCharArray())))); }
/// <summary> /// Validate the file given by hashing it using a keyed-hash, and comparing the resulting signature to /// the given signature. Return true if they match. /// </summary> /// <param name="filePath">full or relative path to file</param> /// <param name="signature">the original signature of the file as obtained from the server</param> /// <returns>true if signatures match, file is valid</returns> bool IValidator.Validate(string filePath, string signature) { // HOW THIS WORKS: // 1) load file // 2) hash file // 3) encrypt given file's hash with the key // 4) compare signature with the encrypted hash WE generated from downloaded file; // 5) if they match, file is good. // the SECRET is the key. If both parties hashed the file with the secret key, then the signatures must match. // if the file has been altered or the wrong key was used, they will not match and we must suspect tampering/replacement byte[] inSignature = null; byte[] outSignature = null; // convert base64 signature to byte[] inSignature = Convert.FromBase64String(signature); // using the key (member variable) use hashed-key algorithm to generate // a signature for the file using (FileStream fs = new FileStream(filePath, FileMode.Open)) { KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(); kha.Key = _key; outSignature = kha.ComputeHash(fs); } // now compare the hash we just created with the signature that was passed. // if they're not identical we can't trust the file return(compareKeys(outSignature, inSignature)); }
/// <summary> /// Compute and return the hash of a data blob using the specified algorithm and key /// </summary> /// <param name="algorithm">Algorithm to use for hashing</param> /// <param name="key">Hash key</param> /// <param name="data">Data blob</param> /// <returns>Hash of the data</returns> private static byte[] ComputeKeyedHash(byte[] key, byte[] data) { using (KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create("HMACSHA256")) { kha.Key = key; return(kha.ComputeHash(data)); } }
/// <summary> /// Validates the manifest root xml node against the signature it contains, detects false/tampered manifests /// </summary> /// <param name="xml">the contents of the manifest</param> /// <param name="signature">the encrypted hash code of the contents of the manifest xml file</param> /// <returns>true if the decrypted hash signature of the xml matches the hash of the xml generated here</returns> bool IValidator.Validate(XmlNode xml, string signature) { byte[] inSignature = null; byte[] outSignature = null; byte[] xmlNodeByte = null; // convert xmlnode contents into byte array xmlNodeByte = Encoding.Unicode.GetBytes(xml.InnerXml); // convert base64 signature to byte[] inSignature = Convert.FromBase64String(signature); // using the key (member variable) use hashed-key algorithm to generate // a signature for the xml KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(); kha.Key = _key; outSignature = kha.ComputeHash(xmlNodeByte); // now compare the hash we just created with the signature that was passed. // if they're not identical we can't trust the file return(compareKeys(outSignature, inSignature)); }
private static bool CustomDeviceId(ref string __result) { if (!File.Exists("mac.txt")) { string newId = (from x in KeyedHashAlgorithm.Create().ComputeHash(Encoding.UTF8.GetBytes(string.Format("{0}B-61-{1}A-{2}-{3}{4}-1{5}", new object[] { new System.Random().Next(0, 9), new System.Random().Next(0, 9), new System.Random().Next(0, 9), new System.Random().Next(0, 9), new System.Random().Next(0, 9), new System.Random().Next(0, 9) }))) select x.ToString("x2")).Aggregate((string x, string y) => x + y); File.WriteAllText("mac.txt", newId); __result = newId; } else { if (string.IsNullOrEmpty(m_deviceId)) { m_deviceId = File.ReadAllText("mac.txt"); } __result = m_deviceId; } return(false); }
/// <summary> /// Reads the given xml and creates a hash code that uses every byte of the xml to contribute, then encrypts the resulting hash code using the key /// in the KeyedHashAlgorithm /// </summary> /// <param name="xml">the node of xml to sign</param> /// <param name="key">the "secret" key used to "sign" the hash</param> /// <returns>a base64-encoded string which is the encrypted signature of the xml</returns> string IValidator.Sign(XmlNode xml, string key) { byte[] outSignature = null; byte[] xmlNodeByte = null; // convert xmlnode contents into byte array xmlNodeByte = Encoding.Unicode.GetBytes(xml.InnerXml); try { // create an instance of keyed hash algo--note that the static Create is its own Factory method (sweet) KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(); // feed the hash algo the key kha.Key = Convert.FromBase64String(key); // key-hash xml outSignature = kha.ComputeHash(xmlNodeByte); } catch (Exception e) { ApplicationUpdateManager.TraceWrite(e, "[KeyValidator.Sign]", "RES_EXCEPTION_SigningXml"); throw e; } // no finally, no hard resources used // return key-hash return(Convert.ToBase64String(outSignature)); }
/** * Computes RFC 2104-compliant HMAC signature for request parameters * Implements AWS Signature, as per following spec: * * If Signature Version is 0, it signs concatenated Action and Timestamp * * If Signature Version is 1, it performs the following: * * Sorts all parameters (including SignatureVersion and excluding Signature, * the value of which is being created), ignoring case. * * Iterate over the sorted list and append the parameter name (in original case) * and then its value. It will not URL-encode the parameter values before * constructing this string. There are no separators. * * If Signature Version is 2, string to sign is based on following: * * 1. The HTTP Request Method followed by an ASCII newline (%0A) * 2. The HTTP Host header in the form of lowercase host, followed by an ASCII newline. * 3. The URL encoded HTTP absolute path component of the URI * (up to but not including the query string parameters); * if this is empty use a forward '/'. This parameter is followed by an ASCII newline. * 4. The concatenation of all query string components (names and values) * as UTF-8 characters which are URL encoded as per RFC 3986 * (hex characters MUST be uppercase), sorted using lexicographic byte ordering. * Parameter names are separated from their values by the '=' character * (ASCII character 61), even if the value is empty. * Pairs of parameter and values are separated by the '&' character (ASCII code 38). * */ private String SignParameters(IDictionary <String, String> parameters, String key) { String signatureVersion = parameters["SignatureVersion"]; KeyedHashAlgorithm algorithm = new HMACSHA1(); String stringToSign = null; if ("0".Equals(signatureVersion)) { stringToSign = CalculateStringToSignV0(parameters); } else if ("1".Equals(signatureVersion)) { stringToSign = CalculateStringToSignV1(parameters); } else if ("2".Equals(signatureVersion)) { String signatureMethod = config.SignatureMethod; algorithm = KeyedHashAlgorithm.Create(signatureMethod.ToUpper()); parameters.Add("SignatureMethod", signatureMethod); stringToSign = CalculateStringToSignV2(parameters); } else { throw new Exception("Invalid Signature Version specified"); } return(Sign(stringToSign, key, algorithm)); }
public static byte[] ComputeHash <T>([NotNull] this byte[] bytes, [NotNull] byte[] key) where T : KeyedHashAlgorithm { Contract.Requires <ArgumentNullException>(bytes != null); Contract.Requires <ArgumentNullException>(key != null); byte[] hashedBytes; // Use an abstract factory to create an instance // of a specific given type of KeyedHashAlgorithm. using (T hasher = KeyedHashAlgorithm.Create((typeof(T)).ToString()) as T) { // warning CC1024: CodeContracts: Contract section within try block. //// Contract.Requires(hasher != null); if (hasher == null) { throw new InvalidOperationException(string.Concat(typeof(T).FullName, " is not a keyed cryptographic hash algorithm!")); } hasher.Key = key; hashedBytes = hasher.ComputeHash(bytes); } return(hashedBytes); }