/// <summary>
        /// Produces a signature over the 'input' using the <see cref="SymmetricSecurityKey"/> and 'algorithm' passed to <see cref="SymmetricSignatureProvider( SecurityKey, string )"/>.
        /// </summary>
        /// <param name="input">The bytes to sign.</param>
        /// <returns>Signed bytes</returns>
        /// <exception cref="ArgumentNullException">'input' is null. </exception>
        /// <exception cref="ArgumentException">'input.Length' == 0. </exception>
        /// <exception cref="ObjectDisposedException"><see cref="Dispose(bool)"/> has been called.</exception>
        /// <exception cref="InvalidOperationException"><see cref="KeyedHashAlgorithm"/> is null. This can occur if a derived type deletes it or does not create it.</exception>
        public override byte[] Sign(byte[] input)
        {
            if (input == null)
            {
                throw LogHelper.LogArgumentNullException("input");
            }

            if (input.Length == 0)
            {
                throw LogHelper.LogException <ArgumentException>(LogMessages.IDX10624);
            }

            if (_disposed)
            {
                throw LogHelper.LogException <ObjectDisposedException>(GetType().ToString());
            }

            if (_keyedHash == null)
            {
                throw LogHelper.LogException <InvalidOperationException>(LogMessages.IDX10623);
            }

            IdentityModelEventSource.Logger.WriteInformation(LogMessages.IDX10642, input);

            return(_keyedHash.ComputeHash(input));
        }
        public MFTestResults HmacTest_Test1()
        {
            bool testResult = false;

            try
            {
                string dataToSign = "This is a simple message to be encrypted";

                byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(dataToSign);

                Mechanism mech = new Mechanism(MechanismType.SHA_1_HMAC);

                using (Session openSession = new Session("", mech.Type))
                {
                    using (KeyedHashAlgorithm hmacOpenSSL = new KeyedHashAlgorithm(KeyedHashAlgorithmType.HMACSHA1, openSession))
                    {
                        byte[] hmac1 = hmacOpenSSL.ComputeHash(data);

                        byte[] hmac2 = hmacOpenSSL.ComputeHash(data);

                        data[3] = (byte)((data[3] & 1) == 0 ? data[3] + 1 : data[3] - 1);

                        byte[] hmac3 = hmacOpenSSL.ComputeHash(data);

                        testResult = true;
                        bool difFound = false;

                        for (int i = 0; i < hmac1.Length; i++)
                        {
                            if (hmac1[i] != hmac2[i])
                            {
                                testResult = false;
                                break;
                            }
                            if (hmac1[i] != hmac1[3])
                            {
                                difFound = true;
                            }
                        }
                        testResult &= difFound;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected Exception", ex);
            }

            return(testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
Beispiel #3
0
 private byte GetByte()
 {
     if (index >= chunk.Length)
     {
         hmac.Initialize();
         aValue = hmac.ComputeHash(aValue);
         aValue.CopyTo((Array)buffer, 0);
         seed.CopyTo((Array)buffer, aValue.Length);
         hmac.Initialize();
         chunk = hmac.ComputeHash(buffer);
         index = 0;
     }
     ++position;
     return(chunk[index++]);
 }
Beispiel #4
0
        private byte[] ComputeBlock()
        {
            var tmp = Packer.Pack("A^I", _salt, _blockNumber++);

            tmp = _hmacAlgorithm.ComputeHash(tmp);
            var result = tmp;

            for (var i = 1; i < _iterations; i++)
            {
                tmp    = _hmacAlgorithm.ComputeHash(tmp);
                result = ByteArray.Xor(tmp, 0, result, 0, tmp.Length);
            }

            return(result);
        }
Beispiel #5
0
        /// <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));
        }
Beispiel #6
0
 private byte[] SignData(byte[] cipherText, byte[] masterKey, SymmetricAlgorithm symmetricAlgorithm, KeyedHashAlgorithm hashAlgorithm, int keyDerivationIterationCount)
 {
     hashAlgorithm.Key = DerivedSigningKey(masterKey, symmetricAlgorithm, keyDerivationIterationCount);
     byte[] signature = hashAlgorithm.ComputeHash(cipherText);
     hashAlgorithm.Clear();
     return(signature);
 }
Beispiel #7
0
            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 = CreateKeyedHashAlgorithm(algorithmName);

                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.Dispose();
                }
            }
Beispiel #8
0
        /// <summary>
        /// Use hashing algorithm to compute a value using the signing key and data
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] HMACSignBinary(byte[] data, byte[] key)
        {
            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("HmacSHA256".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();
            }
        }
        /**
         * Get signature according to signedParams, method and secret
         * @param signedParams params which need to be signed
         * @param method http method e.g. GET
         * @param secret AccessKeySecret
         * @return the signature
         */
        public static string GetRPCSignature(Dictionary <string, string> signedParams, string method, string secret)
        {
            List <string> sortedKeys = signedParams.Keys.ToList();

            sortedKeys.Sort();
            StringBuilder canonicalizedQueryString = new StringBuilder();

            foreach (string key in sortedKeys)
            {
                if (!string.IsNullOrEmpty(signedParams[key]))
                {
                    canonicalizedQueryString.Append("&")
                    .Append(PercentEncode(key)).Append("=")
                    .Append(PercentEncode(signedParams[key]));
                }
            }
            StringBuilder stringToSign = new StringBuilder();

            stringToSign.Append(method);
            stringToSign.Append(SEPARATOR);
            stringToSign.Append(PercentEncode("/"));
            stringToSign.Append(SEPARATOR);
            stringToSign.Append(PercentEncode(
                                    canonicalizedQueryString.ToString().Substring(1)));
            System.Diagnostics.Debug.WriteLine("GetRPCSignature:stringToSign is " + stringToSign.ToString());
            byte[] signData;
            using (KeyedHashAlgorithm algorithm = CryptoConfig.CreateFromName("HMACSHA1") as KeyedHashAlgorithm)
            {
                algorithm.Key = Encoding.UTF8.GetBytes(secret + SEPARATOR);
                signData      = algorithm.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString().ToCharArray()));
            }
            string signedStr = System.Convert.ToBase64String(signData);

            return(signedStr);
        }
        /// <summary>
        /// Generates digests based on the contents of an array of bytes and splits the result into 4-byte int's and store them in an array. The
        /// digest function is called until the required number of int's are produced. For each call to digest a salt
        /// is prepended to the data. The salt is increased by 1 for each call.
        /// </summary>
        /// <param name="data">specifies input data</param>
        /// <param name="hashes">number of hashes/int's to produce</param>
        /// <returns>array of int-sized hashes</returns>
        public static int[] CreateHashes(byte[] data, int hashes)
        {
            int[] result = new int[hashes];

            int k = 0;

            byte[] salt = new byte[1];
            while (k < hashes)
            {
                byte[] digest;
                lock (DigestFunction)
                {
                    DigestFunction.Key = salt;
                    salt[0]++;
                    digest = DigestFunction.ComputeHash(data);
                }

                for (int i = 0; i < digest.Length / 4 && k < hashes; i++)
                {
                    int h = 0;
                    for (int j = (i * 4); j < (i * 4) + 4; j++)
                    {
                        h <<= 8;
                        h  |= digest[j] & 0xFF;
                    }
                    result[k] = h;
                    k++;
                }
            }
            return(result);
        }
Beispiel #11
0
        static string GetStringHash(KeyedHashAlgorithm kha, string str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return(String.Empty);
            }

            string result;

            try {
                _stringHashCacheLock.EnterUpgradeableReadLock();
                if (stringHashCache.TryGetValue(str, out result))
                {
                    return(result);
                }

                try {
                    _stringHashCacheLock.EnterWriteLock();
                    if (stringHashCache.TryGetValue(str, out result))
                    {
                        return(result);
                    }

                    result = Convert.ToBase64String(kha.ComputeHash(Encoding.UTF8.GetBytes(str)));
                    stringHashCache.Add(str, result);
                } finally {
                    _stringHashCacheLock.ExitWriteLock();
                }
            } finally {
                _stringHashCacheLock.ExitUpgradeableReadLock();
            }

            return(result);
        }
Beispiel #12
0
        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);
            }
        }
        /// <summary>
        /// 获取添加密钥签名后的查询字符串。
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="accessKeyId">AccessKeyId。</param>
        /// <param name="accessKeySecret">AccessKeySecret。</param>
        /// <param name="algorithmName">签名 HMAC 哈希算法名称。</param>
        /// <returns></returns>
        public static string GetKeyedSignedQueryString(Uri uri, string accessKeyId, string accessKeySecret, string algorithmName)
        {
            if (string.IsNullOrWhiteSpace(accessKeyId))
            {
                throw new ArgumentNullException(nameof(accessKeyId), "AccessKeyId is not nullable.");
            }
            if (string.IsNullOrWhiteSpace(accessKeySecret))
            {
                throw new ArgumentNullException(nameof(accessKeySecret), "AccessKeySecret is not nullable.");
            }

            IDictionary <string, string> sortedQueryStrings = GetSortedQueries(uri);
            string signRequiredQueryString = GetSignRequiredQueryString(sortedQueryStrings, accessKeyId);

            using (KeyedHashAlgorithm hashAlgorithm = CryptoConfig.CreateFromName(algorithmName) as KeyedHashAlgorithm)
            {
                if (hashAlgorithm == null)
                {
                    throw new NotSupportedException($"Algorithm \"{algorithmName}\" is not supported for query keyed signature.");
                }

                hashAlgorithm.Key = Encoding.UTF8.GetBytes(accessKeySecret);
                sortedQueryStrings[QUERY_NAME_SIGNATURE] = BitConverter.ToString(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(signRequiredQueryString))).Replace("-", "").ToLower();
                return(string.Join("&", sortedQueryStrings.Select(q => $"{PercentEncodingUtil.Encode(q.Key)}={PercentEncodingUtil.Encode(q.Value)}")));
            }
        }
Beispiel #14
0
            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 keyedHashAlgorithm = ThreadSafeCreateKeyedHashedAlgorithm(algorithmName);

                if (keyedHashAlgorithm != null)
                {
                    try
                    {
                        keyedHashAlgorithm.Key = key;
                        return(keyedHashAlgorithm.ComputeHash(data));
                    }
                    finally
                    {
                        keyedHashAlgorithm.Clear();
                    }
                }
                throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use.");
            }
        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();
        }
        public static string DecodeData(string strValidationKey, string strValidationAlgorithm, byte[] protectedData, string modifier)
        {
            byte[] byteModifier = CryptoUtil.HexToBinary(modifier);
            Array.Reverse(byteModifier);

            int hashSize = ViewStateHelper.hashSizes[Array.IndexOf(ViewStateHelper.algorithms, strValidationAlgorithm)];
            int dataSize = protectedData.Length - hashSize;

            byte[] byteHash = new byte[hashSize];
            Buffer.BlockCopy(protectedData, dataSize, byteHash, 0, hashSize);

            byte[] byteData = new byte[dataSize + byteModifier.Length];
            Buffer.BlockCopy(protectedData, 0, byteData, 0, dataSize);
            Buffer.BlockCopy(byteModifier, 0, byteData, dataSize, byteModifier.Length);

            KeyedHashAlgorithm keyedHashAlgorithm = GetHMACAlgorithm(strValidationAlgorithm, CryptoUtil.HexToBinary(strValidationKey));

            byte[] computedHash = keyedHashAlgorithm.ComputeHash(byteData);

            if (CryptoUtil.BinaryToHex(computedHash) == CryptoUtil.BinaryToHex(byteHash))
            {
                byte[] rawData = new byte[dataSize];
                Buffer.BlockCopy(protectedData, 0, rawData, 0, dataSize);
                return(System.Convert.ToBase64String(rawData));
            }
            return("");
        }
Beispiel #17
0
        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));
        }
Beispiel #18
0
        /// <summary>
        /// Generates digests based on the contents of an array of bytes and splits the result into 4-byte int's and store them in an array. The
        /// digest function is called until the required number of int's are produced. For each call to digest a salt
        /// is prepended to the data. The salt is increased by 1 for each call.
        /// </summary>
        /// <param name="data">specifies input data</param>
        /// <param name="hashes">number of hashes/int's to produce</param>
        /// <returns>array of int-sized hashes</returns>
        public static int[] CreateHashes(byte[] data, int hashes)
        {
            var result = new int[hashes];

            var k    = 0;
            var salt = new byte[1];

            while (k < hashes)
            {
                byte[] digest;
                lock (DigestFunction)
                {
                    DigestFunction.Key = salt;
                    salt[0]++;
                    digest = DigestFunction.ComputeHash(data);
                }

                for (var i = 0; i < digest.Length / 4 && k < hashes; i++)
                {
                    var h = 0;
                    for (var j = i * 4; j < i * 4 + 4; j++)
                    {
                        h <<= 8;
                        h  |= digest[j] & 0xFF;
                    }
                    result[k] = h;
                    k++;
                }
            }
            return(result);
        }
Beispiel #19
0
        public static byte[] Encrypt <Text>(Text plain) where Text : class
        {
            if (!plain.GetType().IsSerializable)
            {
                throw new SerializationException("Object is not serializable.");
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (SymmetricAlgorithm crypto = CreateSymmetricAlgorithm())
                {
                    using (CryptoStream cs = new CryptoStream(ms, crypto.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        (new BinaryFormatter()).Serialize(cs, plain);

                        cs.FlushFinalBlock();

                        using (KeyedHashAlgorithm hash = CreateHashAlgorithm())
                        {
                            hash.Key = crypto.Key;
                            ms.Seek(0, SeekOrigin.Begin);
                            hash.ComputeHash(ms);
                            ms.Write(hash.Hash, 0, hash.Hash.Length);
                        }
                    }
                }

                return(ms.ToArray());
            }
        }
Beispiel #20
0
        /// <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));
        }
Beispiel #21
0
        /// <summary>
        /// Computes RFC 2104-compliant HMAC signature
        /// </summary>
        /// <param name="data">The data to be signed</param>
        /// <param name="key">The secret signing key</param>
        /// <param name="algorithm">The algorithm to sign the data with</param>
        /// <exception cref="T:System.ArgumentNullException"/>
        /// <returns>A string representing the HMAC signature</returns>
        public static string HMACSign(string data, string key, KeyedHashAlgorithm algorithm)
        {
            if (String.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");
            }

            if (String.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException("data", "Please specify data to sign.");
            }

            if (null == algorithm)
            {
                throw new ArgumentNullException("algorithm", "Please specify a KeyedHashAlgorithm to use.");
            }

            try
            {
                algorithm.Key = Encoding.UTF8.GetBytes(key);
                return(Convert.ToBase64String(algorithm.ComputeHash(
                                                  Encoding.UTF8.GetBytes(data))
                                              ));
            }
            finally
            {
                algorithm.Clear();
            }
        }
Beispiel #22
0
        protected string _getSignature(TeaRequest request, string secret)
        {
            Dictionary <string, string> queries = request.Query;
            List <string> sortedKeys            = queries.Keys.ToList();

            sortedKeys.Sort();
            StringBuilder canonicalizedQueryString = new StringBuilder();

            foreach (string key in sortedKeys)
            {
                canonicalizedQueryString.Append("&")
                .Append(PercentEncode(key)).Append("=")
                .Append(PercentEncode(queries[key]));
            }
            StringBuilder stringToSign = new StringBuilder();

            stringToSign.Append(request.Method);
            stringToSign.Append(SEPARATOR);
            stringToSign.Append(PercentEncode("/"));
            stringToSign.Append(SEPARATOR);
            stringToSign.Append(PercentEncode(
                                    canonicalizedQueryString.ToString().Substring(1)));
            byte[] signData;
            using (KeyedHashAlgorithm algorithm = CryptoConfig.CreateFromName(ALGORITHM_NAME) as KeyedHashAlgorithm)
            {
                algorithm.Key = URL_ENCODING.GetBytes(secret + SEPARATOR);
                signData      = algorithm.ComputeHash(URL_ENCODING.GetBytes(stringToSign.ToString().ToCharArray()));
            }
            string signedStr = Convert.ToBase64String(signData);

            return(signedStr);
        }
Beispiel #23
0
        /// <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));
        }
Beispiel #24
0
        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();
            }
        }
Beispiel #25
0
        /// <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));
        }
Beispiel #26
0
            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 = CreateKeyedHashAlgorithm(algorithmName);

                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.Dispose();
                }
            }
Beispiel #27
0
        /// <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));
        }
Beispiel #28
0
 /// <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));
     }
 }
Beispiel #29
0
        internal static byte[] SignatureMethod(string secret, string source, string signatureAlgorithm)
        {
            if (signatureAlgorithm == "ACS3-HMAC-SHA256")
            {
                byte[] signData;
                using (KeyedHashAlgorithm algorithm = CryptoConfig.CreateFromName("HMACSHA256") as KeyedHashAlgorithm)
                {
                    algorithm.Key = Encoding.UTF8.GetBytes(secret);
                    signData      = algorithm.ComputeHash(Encoding.UTF8.GetBytes(source.ToSafeString().ToCharArray()));
                }
                return(signData);
            }
            else if (signatureAlgorithm == "ACS3-HMAC-SM3")
            {
                byte[] signData;
                HMac   hmacInstance = new HMac(new SM3Digest());
                hmacInstance.Init(new KeyParameter(Encoding.UTF8.GetBytes(secret)));
                signData = new byte[hmacInstance.GetMacSize()];
                var raw = Encoding.UTF8.GetBytes(source);
                hmacInstance.BlockUpdate(raw, 0, raw.Length);
                hmacInstance.DoFinal(signData, 0);

                return(signData);
            }
            else if (signatureAlgorithm == "ACS3-RSA-SHA256")
            {
                return(RSASign(source, secret));
            }
            return(null);
        }
Beispiel #30
0
        /// <summary>バイト配列のハッシュ値を計算して返す。</summary>
        /// <param name="asb">バイト配列</param>
        /// <param name="ekha">ハッシュ(キー付き)アルゴリズム列挙型</param>
        /// <param name="password">使用するパスワード</param>
        /// <param name="salt">ソルト</param>
        /// <param name="stretchCount">ストレッチ回数</param>
        /// <returns>ハッシュ値(バイト配列)</returns>
        public static byte[] GetKeyedHashBytes(byte[] asb, EnumKeyedHashAlgorithm ekha, string password, byte[] salt, int stretchCount)
        {
            // キーを生成する。
            Rfc2898DeriveBytes passwordKey = new Rfc2898DeriveBytes(password, salt, stretchCount);
            // HMACMD5      :どのサイズのキーでも受け入れる ◯
            // HMACRIPEMD160:どのサイズのキーでも受け入れる ◯
            // HMACSHA1     :どのサイズのキーでも受け入れる ◯
            // HMACSHA256   :どのサイズのキーでも受け入れる ◯
            // HMACSHA384   :どのサイズのキーでも受け入れる ◯
            // HMACSHA512   :どのサイズのキーでも受け入れる ◯
            // MACTripleDES :長さが 16 または 24 バイトのキーを受け入れる

            // ハッシュ(キー付き)サービスプロバイダを生成
            KeyedHashAlgorithm kha = GetKeyedHash.CreateKeyedHashAlgorithmServiceProvider(
                ekha,
                passwordKey.GetBytes(24)     // 上記より、24 決め打ちとする。
                );

            // ハッシュ(キー付き)を生成して返す。
            byte[] temp = kha.ComputeHash(asb);

            kha.Clear(); // devps(1725)

            return(temp);
        }
 /**
  * Computes RFC 2104-compliant HMAC signature.
  */
 private static String Sign(String data, String key, KeyedHashAlgorithm algorithm)
 {
     Encoding encoding = new UTF8Encoding();
     algorithm.Key = encoding.GetBytes(key);
     return Convert.ToBase64String(algorithm.ComputeHash(
         encoding.GetBytes(data.ToCharArray())));
 }