Example #1
0
        public static string HMACSign(string data, System.Security.SecureString key, KeyedHashAlgorithm algorithm)
#endif
        {
#if UNITY
            if (String.IsNullOrEmpty(key))
#else
            if (null == key)
#endif
            {
                throw new ArgumentNullException("key", "The AWS Secret Access Key specified is NULL!");
            }

            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.");
            }
#if UNITY
            try
            {
                algorithm.Key = Encoding.UTF8.GetBytes(key);
                return Convert.ToBase64String(algorithm.ComputeHash(
                    Encoding.UTF8.GetBytes(data.ToCharArray()))
                    );
            }
            finally
            {
                algorithm.Clear();
            }
#else
            // pointer to hold unmanaged reference to SecureString instance
            IntPtr bstr = IntPtr.Zero;
            char[] charArray = new char[key.Length];
            try
            {
                // Marshal SecureString into byte array
                bstr = Marshal.SecureStringToBSTR(key);
                Marshal.Copy(bstr, charArray, 0, charArray.Length);
                algorithm.Key = Encoding.UTF8.GetBytes(charArray);
                return Convert.ToBase64String(algorithm.ComputeHash(
                    Encoding.UTF8.GetBytes(data.ToCharArray()))
                    );
            }
            finally
            {
                // Make sure that the clear text data is zeroed out
                Marshal.ZeroFreeBSTR(bstr);
                algorithm.Clear();
                Array.Clear(charArray, 0, charArray.Length);
            }
#endif
        }
		static string GetStringHash (KeyedHashAlgorithm kha, string str)
		{
			if (String.IsNullOrEmpty (str))
				return String.Empty;

			string result;
			Dictionary <string, string> cache = StringHashCache;
			if (cache.TryGetValue (str, out result))
				return result;
			
			result = Convert.ToBase64String (kha.ComputeHash (Encoding.UTF8.GetBytes (str)));
			cache.Add (str, result);
			return result;
		}
Example #3
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(byte[] data, string key, KeyedHashAlgorithm algorithm)
        {
            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.");
            }

            if (null == algorithm)
            {
                throw new ArgumentNullException("algorithm", "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();
            }
        }
Example #4
0
        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);

        }
Example #5
0
        public MFTestResults HmacTest_Compare()
        {
            bool testResult = false;

            if (!m_isEmulator) return MFTestResults.Skip;

            try
            {
                CryptokiAttribute[] secretKey = new CryptokiAttribute[]
                    {
                        new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class  , new byte[] {    4, 0, 0, 0}),
                        new CryptokiAttribute(CryptokiAttribute.CryptokiType.KeyType, new byte[] { 0x10, 0, 0, 0}),
                        new CryptokiAttribute(CryptokiAttribute.CryptokiType.Value  , new byte[20])
                    };
                Mechanism mech = new Mechanism(MechanismType.SHA_1_HMAC);

                using (Session openSession = new Session("", mech.Type))
                {
                    using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(openSession))
                    {
                        rng.GetBytes(secretKey[2].Value);
                    }

                    using (CryptoKey keyOpen = CryptoKey.LoadKey(openSession, secretKey))
                    {
                        string dataToSign = "This is a simple message to be encrypted";

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

                        using (KeyedHashAlgorithm hmacOpenSSL = new KeyedHashAlgorithm(KeyedHashAlgorithmType.HMACSHA1, keyOpen))
                        {
                            byte[] hmac1 = hmacOpenSSL.ComputeHash(data);

                            using (Session emuSession = new Session("Emulator_Crypto", mech.Type))
                            {
                                using (CryptoKey keyEmu = CryptoKey.LoadKey(emuSession, secretKey))
                                {

                                    using (KeyedHashAlgorithm hmacEmu = new KeyedHashAlgorithm(KeyedHashAlgorithmType.HMACSHA1, keyEmu))
                                    {
                                        byte[] hmac2 = hmacEmu.ComputeHash(data);

                                        testResult = true;

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

            return (testResult ? MFTestResults.Pass : MFTestResults.Fail);

        }
Example #6
0
		public void ComputeSignature (KeyedHashAlgorithm macAlg) 
		{
			if (macAlg == null)
				throw new ArgumentNullException ("macAlg");

			string method = null;

			if (macAlg is HMACSHA1) {
				method = XmlDsigHMACSHA1Url;
			} else if (macAlg is HMACSHA256) {
				method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
			} else if (macAlg is HMACSHA384) {
				method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
			} else if (macAlg is HMACSHA512) {
				method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
			} else if (macAlg is HMACRIPEMD160) {
				method = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160";
			}

			if (method == null)
				throw new CryptographicException ("unsupported algorithm");

			DigestReferences ();
			m_signature.SignedInfo.SignatureMethod = method;
			m_signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
		}
Example #7
0
		public bool CheckSignature (KeyedHashAlgorithm macAlg) 
		{
			if (macAlg == null)
				throw new ArgumentNullException ("macAlg");

			pkEnumerator = null;

			// Is the signature (over SignedInfo) valid ?
			Stream s = SignedInfoTransformed ();
			if (s == null)
				return false;

			byte[] actual = macAlg.ComputeHash (s);
			// HMAC signature may be partial and specified by <HMACOutputLength>
			if (m_signature.SignedInfo.SignatureLength != null) {
				int length = Int32.Parse (m_signature.SignedInfo.SignatureLength);
				// we only support signatures with a multiple of 8 bits
				// and the value must match the signature length
				if ((length & 7) != 0)
					throw new CryptographicException ("Signature length must be a multiple of 8 bits.");

				// SignatureLength is in bits (and we works on bytes, only in multiple of 8 bits)
				// and both values must match for a signature to be valid
				length >>= 3;
				if (length != m_signature.SignatureValue.Length)
					throw new CryptographicException ("Invalid signature length.");

				// is the length "big" enough to make the signature meaningful ? 
				// we use a minimum of 80 bits (10 bytes) or half the HMAC normal output length
				// e.g. HMACMD5 output 128 bits but our minimum is 80 bits (not 64 bits)
				int minimum = Math.Max (10, actual.Length / 2);
				if (length < minimum)
					throw new CryptographicException ("HMAC signature is too small");

				if (length < actual.Length) {
					byte[] trunked = new byte [length];
					Buffer.BlockCopy (actual, 0, trunked, 0, length);
					actual = trunked;
				}
			}

			if (Compare (m_signature.SignatureValue, actual)) {
				// some parts may need to be downloaded
				// so where doing it last
				return CheckReferenceIntegrity (m_signature.SignedInfo.References);
			}
			return false;
		}
        static Boolean Test(Session session)
        {
            Boolean bRes = true;
            Byte[] abKey1 = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b };
            Byte[] abData1 = (new System.Text.UTF8Encoding()).GetBytes("Hi There");
            Byte[] abDigest1 = { 0xb6, 0x17, 0x31, 0x86, 0x55, 0x05, 0x72, 0x64, 0xe2, 0x8b, 0xc0, 0xb6, 0xfb, 0x37, 0x8c, 0x8e, 0xf1, 0x46, 0xbe, 0x00 };
            Byte[] abKey2 = (new System.Text.UTF8Encoding()).GetBytes("Jefe");
            Byte[] abData2 = (new System.Text.UTF8Encoding()).GetBytes("what do ya want for nothing?");
            Byte[] abDigest2 = { 0xef, 0xfc, 0xdf, 0x6a, 0xe5, 0xeb, 0x2f, 0xa2, 0xd2, 0x74, 0x16, 0xd5, 0xf1, 0x84, 0xdf, 0x9c, 0x25, 0x9a, 0x7c, 0x79 };

            CryptoKey key1 = CryptoKey.LoadKey(session, new CryptokiAttribute[] { 
                    new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class  , Utility.ConvertToBytes((int)CryptokiClass.SECRET_KEY)),
                    new CryptokiAttribute(CryptokiAttribute.CryptokiType.KeyType, Utility.ConvertToBytes((int)CryptoKey.KeyType.GENERIC_SECRET)),
                    new CryptokiAttribute(CryptokiAttribute.CryptokiType.Value  , abKey1)
            });

            CryptoKey key2 = CryptoKey.LoadKey(session, new CryptokiAttribute[] { 
                    new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class  , Utility.ConvertToBytes((int)CryptokiClass.SECRET_KEY)),
                    new CryptokiAttribute(CryptokiAttribute.CryptokiType.KeyType, Utility.ConvertToBytes((int)CryptoKey.KeyType.GENERIC_SECRET)),
                    new CryptokiAttribute(CryptokiAttribute.CryptokiType.Value  , abKey2)
            });

            Log.Comment("Testing rc21 hash...");
            using(KeyedHashAlgorithm rc21 = new KeyedHashAlgorithm(KeyedHashAlgorithmType.HMACSHA1, key1))
            using (KeyedHashAlgorithm rc22 = new KeyedHashAlgorithm(KeyedHashAlgorithmType.HMACSHA1, key2))
            {
                rc21.ComputeHash(abData1);
                rc22.ComputeHash(abData2);
                Log.Comment("The computed hash #1 is : ");
                PrintByteArray(rc21.Hash);
                Log.Comment("The correct hash #1 is : ");
                PrintByteArray(abDigest1);
                if (Compare(rc21.Hash, abDigest1))
                {
                    Log.Comment("CORRECT");
                }
                else
                {
                    Log.Comment("INCORRECT");
                    bRes = false;
                }
                Log.Comment("The computed hash #2 is : ");
                PrintByteArray(rc22.Hash);
                Log.Comment("The correct hash #2 is : ");
                PrintByteArray(abDigest2);
                if (Compare(rc22.Hash, abDigest2))
                {
                    Log.Comment("CORRECT");
                }
                else
                {
                    Log.Comment("INCORRECT");
                    bRes = false;
                }
            }
            return bRes;
        }
        public static bool RunTest(KeyedHashAlgorithm hmac, TestVectorInfo[] vectors)
        {
            byte[] computedHash = null;
            byte[] computedHashTruncated = null;

            foreach (TestVectorInfo vector in vectors)
            {
                CryptoKey key = CryptoKey.LoadKey(hmac.Session, new CryptokiAttribute[] { 
                    new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class  , Utility.ConvertToBytes((int)CryptokiClass.SECRET_KEY)),
                    new CryptokiAttribute(CryptokiAttribute.CryptokiType.KeyType, Utility.ConvertToBytes((int)CryptoKey.KeyType.GENERIC_SECRET)),
                    new CryptokiAttribute(CryptokiAttribute.CryptokiType.Value  , vector.key)
                });

                hmac.Key = key;
                computedHash = hmac.ComputeHash(vector.data);

                if (vector.truncation > 0)
                {
                    computedHashTruncated = new byte[vector.truncation / 8];
                    Array.Copy(computedHash, computedHashTruncated, vector.truncation / 8);
                }
                else
                {
                    computedHashTruncated = computedHash;
                }

                if (!CompareBytes(computedHashTruncated, vector.value))
                {
                    Log.Comment("Error - HMAC value miscomparison");
                    Log.Comment("Data: " + ByteArrayToString(vector.data));
                    Log.Comment("Key: " + ByteArrayToString(vector.key));
                    Log.Comment("Actual Result: " + ByteArrayToString(computedHash));
                    Log.Comment("Expected Result: " + ByteArrayToString(vector.value));
                    return false;
                }
            }

            return true;
        }
Example #10
0
 public static string HMACSign(string data, SecureString key, KeyedHashAlgorithm algorithm)
 {
     string str;
     if (key == null)
     {
         throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");
     }
     if (string.IsNullOrEmpty(data))
     {
         throw new ArgumentNullException("data", "Please specify data to sign.");
     }
     if (algorithm == null)
     {
         throw new ArgumentNullException("algorithm", "Please specify a KeyedHashAlgorithm to use.");
     }
     IntPtr zero = IntPtr.Zero;
     char[] destination = new char[key.Length];
     try
     {
         zero = Marshal.SecureStringToBSTR(key);
         Marshal.Copy(zero, destination, 0, destination.Length);
         algorithm.Key = Encoding.UTF8.GetBytes(destination);
         str = Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(data.ToCharArray())));
     }
     finally
     {
         Marshal.ZeroFreeBSTR(zero);
         algorithm.Clear();
         Array.Clear(destination, 0, destination.Length);
     }
     return str;
 }
 private static byte[] HashDataUsingKeyedAlgorithm(KeyedHashAlgorithm hashAlgo, byte[] buf, byte[] modifier, int start, int length, byte[] validationKey)
 {
     int num = length + ((modifier != null) ? modifier.Length : 0);
     byte[] dst = new byte[num];
     Buffer.BlockCopy(buf, start, dst, 0, length);
     if (modifier != null)
     {
         Buffer.BlockCopy(modifier, 0, dst, length, modifier.Length);
     }
     hashAlgo.Key = validationKey;
     return hashAlgo.ComputeHash(dst);
 }
Example #12
0
 public static string HMACSign(string data, string key, KeyedHashAlgorithm algorithm)
 {
     string str;
     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 (algorithm == null)
     {
         throw new ArgumentNullException("algorithm", "Please specify a KeyedHashAlgorithm to use.");
     }
     try
     {
         algorithm.Key = Encoding.UTF8.GetBytes(key);
         str = Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(data)));
     }
     finally
     {
         algorithm.Clear();
     }
     return str;
 }
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        private static byte[] HashDataUsingKeyedAlgorithm(KeyedHashAlgorithm hashAlgo, byte[] buf, byte[] modifier,
                                                          int start, int length, byte[] validationKey)
        {
            int     totalLength = length + ((modifier != null) ? modifier.Length : 0);
            byte [] bAll        = new byte[totalLength];

            Buffer.BlockCopy(buf, start, bAll, 0, length);
            if (modifier != null) {
                Buffer.BlockCopy(modifier, 0, bAll, length, modifier.Length);
            }
            hashAlgo.Key = validationKey;
            return hashAlgo.ComputeHash(bAll);
        }
Example #14
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;
		}
Example #15
0
 /**
  * Computes RFC 2104-compliant HMAC signature.
  */
 private 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())));
 }
        /// <summary>
        /// Generate a HA1 hash
        /// </summary>
        /// <param name="realm">Realm that the user want to authenticate in</param>
        /// <param name="userName">User Name</param>
        /// <param name="password">Password</param>
        /// /// <para>
        /// A HA1 hash is simply a Md5 encoded string: "UserName:Realm:Password". The quotes should
        /// not be included. Realm is the currently requested Host (as in <c>Request.Headers["host"]</c>).
        /// </para>
        /// <returns></returns>
        private string Encode(string realm, string userName, string password)
        {
            string toHash = String.Concat(userName, ":", realm, ":", password);

            KeyedHashAlgorithm crypto = new KeyedHashAlgorithm(KeyedHashAlgorithmType.HMACMD5);
            byte[] value = crypto.ComputeHash(Encoding.UTF8.GetBytes(toHash));

            return ByteUtility.GetString(value);
        }