public static Func<Func<HttpMessageHandler>, IYousScribeHttpClient> GetBaseClientFactory(byte[] secretKey, int applicationId, IHMAC hmac)
 {
     return (c) =>
     {
         return c == null ? new YousScribeHMACHttpClientDecorator(new HttpClient(), secretKey, applicationId, hmac) : new YousScribeHMACHttpClientDecorator(new HttpClient(c()), secretKey, applicationId, hmac);
     };
 }
 public void CalculateKeyFromText(string a_text, string a_key)
 {
     if (HashFunction is ICrypto)
     {
         IHMAC hmac = HashFactory.HMAC.CreateHMAC(HashFunction);
         hmac.Key = Converters.ConvertStringToBytes(a_key, Encoding.ASCII);
         Hash     = hmac.ComputeString(a_text, Encoding.ASCII).ToString();
     }
     else if (HashFunction is IWithKey)
     {
         IWithKey hash_with_key = HashFunction as IWithKey;
         try
         {
             var key_bytes = Converters.ConvertStringToBytes(a_key, Encoding.ASCII);
             if (key_bytes.Length == 0)
             {
                 key_bytes = null;
             }
             hash_with_key.Key = key_bytes;
             Hash = hash_with_key.ComputeString(a_text, Encoding.ASCII).ToString();
         }
         catch
         {
             Hash = "Error";
         }
     }
     else
     {
         Debug.Assert(false);
     }
 }
 private YousScribeHMACHttpClientDecorator(HttpClient BaseClient, byte[] secretKey, int applicationId, IHMAC hmac)
     : base(BaseClient)
 {
     this.secretKey = secretKey;
     this.applicationId = applicationId;
     this.random = new Random();
     this.randBytes = new byte[8];
     this.hmac = hmac;
 }
示例#4
0
 private YousScribeHMACHttpClientDecorator(HttpClient BaseClient, byte[] secretKey, int applicationId, IHMAC hmac)
     : base(BaseClient)
 {
     this.secretKey     = secretKey;
     this.applicationId = applicationId;
     this.random        = new Random();
     this.randBytes     = new byte[8];
     this.hmac          = hmac;
 }
        /// <summary>
        /// Generates an hmac of the passed data using the passed key and a SHA512 hash
        /// </summary>
        public static string GenerateSha512Hmac(byte[] key, string data)
        {
            IHMAC hmac = HashFactory.HMAC.CreateHMAC(HashFactory.Crypto.CreateSHA512());

            hmac.Key = key;
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            var    hash      = hmac.ComputeBytes(dataBytes);

            return(Convert.ToBase64String(hash.GetBytes()));
        }
示例#6
0
        public void TestHMACWithDefaultDataAndShortKey()
        {
            IHMAC hmac = HashFactory.HMAC.CreateHMAC(hash,
                                                     Converters.ConvertStringToBytes(TestConstants.HMACShortStringKey,
                                                                                     Encoding.UTF8));
            string ActualString = hmac.ComputeString(TestConstants.DefaultData,
                                                     Encoding.UTF8).ToString();

            Assert.AreEqual(ExpectedHashOfDefaultDataWithHMACWithShortKey, ActualString,
                            String.Format("Expected {0} but got {1}.",
                                          ExpectedHashOfDefaultDataWithHMACWithShortKey, ActualString));
        }
示例#7
0
        protected void TestHMAC(IHMAC a_build_in_hmac, IHMAC a_not_build_in_hmac)
        {
            Assert.AreEqual(a_not_build_in_hmac.HashSize, a_build_in_hmac.HashSize);
            Assert.AreEqual(a_not_build_in_hmac.BlockSize, a_build_in_hmac.BlockSize);

            Assert.IsTrue(a_not_build_in_hmac is HMACNotBuildInAdapter);
            Assert.IsTrue(a_build_in_hmac is HMACBuildInAdapter);

            List <int> keys_length = new List <int>()
            {
                0, 1, 7, 51, 121, 512, 1023
            };

            keys_length.Add(a_build_in_hmac.BlockSize - 1);
            keys_length.Add(a_build_in_hmac.BlockSize);
            keys_length.Add(a_build_in_hmac.BlockSize + 1);

            List <int> msgs_length = new List <int>();

            msgs_length.AddRange(keys_length);
            msgs_length.Add(a_build_in_hmac.BlockSize * 4 - 1);
            msgs_length.Add(a_build_in_hmac.BlockSize * 4);
            msgs_length.Add(a_build_in_hmac.BlockSize * 4 + 1);

            foreach (int key_length in keys_length)
            {
                byte[] key = m_random.NextBytes(key_length);

                a_not_build_in_hmac.Key = key;
                a_build_in_hmac.Key     = key;

                foreach (int msg_length in msgs_length)
                {
                    byte[] msg = m_random.NextBytes(msg_length);

                    a_not_build_in_hmac.Initialize();
                    a_not_build_in_hmac.TransformBytes(msg);
                    HashResult h1 = a_not_build_in_hmac.TransformFinal();

                    a_build_in_hmac.Initialize();
                    a_build_in_hmac.TransformBytes(msg);
                    HashResult h2 = a_build_in_hmac.TransformFinal();

                    Assert.AreEqual(h1, h2, a_build_in_hmac.Name);

                    h1 = a_not_build_in_hmac.ComputeString(BitConverter.ToString(msg));
                    h2 = a_build_in_hmac.ComputeString(BitConverter.ToString(msg));

                    Assert.AreEqual(h1, h2, a_build_in_hmac.Name);
                }
            }
        }
        public void CalculateKeyFromFile(string a_file, string a_key)
        {
            if (!(HashFunction is IHMAC) && (HashFunction is INonBlockHash))
            {
                if (new FileInfo(a_file).Length > 200 * 1024 * 1024)
                {
                    Hash = "Hashing skipped. File is too big and algorithm does not provide multiple transforms capabilities";
                    return;
                }
            }

            if (HashFunction is ICrypto)
            {
                IHMAC hmac = HashFactory.HMAC.CreateHMAC(HashFunction);
                hmac.Key = Converters.ConvertStringToBytes(a_key, Encoding.ASCII);
                Hash     = hmac.ComputeFile(a_file).ToString();
            }
            else if (HashFunction is IWithKey)
            {
                IWithKey hash_with_key = HashFunction as IWithKey;
                try
                {
                    var key_bytes = Converters.ConvertStringToBytes(a_key, Encoding.ASCII);
                    if (key_bytes.Length == 0)
                    {
                        key_bytes = null;
                    }
                    hash_with_key.Key = key_bytes;
                    Hash = hash_with_key.ComputeFile(a_file).ToString();
                }
                catch
                {
                    Hash = "Error";
                }
            }
            else
            {
                Debug.Assert(false);
            }
        }
示例#9
0
        private void Test(IHMAC a_base_hmac, IHMAC a_hmac)
        {
            Assert.AreEqual(a_base_hmac.HashSize, a_hmac.HashSize);
            Assert.AreEqual(a_base_hmac.BlockSize, a_hmac.BlockSize);

            var keys_length = new List<int> {0, 1};
            keys_length.Add(a_hmac.BlockSize - 1);
            keys_length.Add(a_hmac.BlockSize);
            keys_length.Add(a_hmac.BlockSize + 1);

            var msgs_length = new List<int>();
            msgs_length.AddRange(keys_length);
            msgs_length.Add(a_hmac.BlockSize * 4 - 1);
            msgs_length.Add(a_hmac.BlockSize * 4);
            msgs_length.Add(a_hmac.BlockSize * 4 + 1);

            foreach(int key_length in keys_length)
            {
                byte[] key = m_random.NextBytes(key_length);

                a_base_hmac.Key = key;
                a_hmac.Key = key;

                foreach(int msg_length in msgs_length)
                {
                    byte[] msg = m_random.NextBytes(msg_length);

                    a_base_hmac.Initialize();
                    a_base_hmac.TransformBytes(msg);
                    HashResult h1 = a_base_hmac.TransformFinal();

                    a_hmac.Initialize();
                    a_hmac.TransformBytes(msg);
                    HashResult h2 = a_hmac.TransformFinal();

                    Assert.AreEqual(h1, h2, a_hmac.Name);
                }
            }
        }
示例#10
0
        /// <summary>
        /// Try get algorithm from mechanism.
        /// </summary>
        /// <param name="mechanism">Algorithm mechanism.</param>
        /// <param name="algorithm">Algorithm.</param>
        /// <returns></returns>
        public static bool TryGetAlgorithm(string mechanism, out IHMAC algorithm)
        {
            mechanism = mechanism.Replace('_', '-').ToUpperInvariant();
            if (mechanism.EndsWith("HMAC"))
            {
                if (mechanism.EndsWith("/HMAC") || mechanism.EndsWith("-HMAC"))
                {
                    mechanism = mechanism.Substring(0, mechanism.Length - 5);
                }
                else
                {
                    mechanism = mechanism.Substring(0, mechanism.Length - 4);
                }
            }
            if (mechanism.StartsWith("HMAC"))
            {
                if (mechanism.StartsWith("HMAC/") || mechanism.StartsWith("HMAC-"))
                {
                    mechanism = mechanism.Substring(5);
                }
                else
                {
                    mechanism = mechanism.Substring(4);
                }
            }
            mechanism = mechanism.Replace('/', '-');
            switch (mechanism)
            {
            case "BLAKE2B-256": algorithm = BLAKE2b_256_HMAC; return(true);

            case "BLAKE2B-384": algorithm = BLAKE2b_384_HMAC; return(true);

            case "BLAKE2B-512": algorithm = BLAKE2b_512_HMAC; return(true);

            case "BLAKE2S-256": algorithm = BLAKE2s_256_HMAC; return(true);

            case "DSTU7564-256": algorithm = DSTU7564_256_HMAC; return(true);

            case "DSTU7564-384": algorithm = DSTU7564_384_HMAC; return(true);

            case "DSTU7564-512": algorithm = DSTU7564_512_HMAC; return(true);

            case "GOST3411": algorithm = GOST3411_HMAC; return(true);

            case "GOST3411-2012-256": algorithm = GOST3411_2012_256_HMAC; return(true);

            case "GOST3411-2012-512": algorithm = GOST3411_2012_512_HMAC; return(true);

            case "KECCAK-128":
            case "KECCAK128": algorithm = Keccak_128_HMAC; return(true);

            case "KECCAK-224":
            case "KECCAK224": algorithm = Keccak_224_HMAC; return(true);

            case "KECCAK-256":
            case "KECCAK256": algorithm = Keccak_256_HMAC; return(true);

            case "KECCAK-288":
            case "KECCAK288": algorithm = Keccak_288_HMAC; return(true);

            case "KECCAK-384":
            case "KECCAK384": algorithm = Keccak_384_HMAC; return(true);

            case "KECCAK-512":
            case "KECCAK512": algorithm = Keccak_512_HMAC; return(true);

            case "MD2": algorithm = MD2_HMAC; return(true);

            case "MD4": algorithm = MD4_HMAC; return(true);

            case "MD5": algorithm = MD5_HMAC; return(true);

            case "RIPEMD128":
            case "RIPEMD-128": algorithm = RIPEMD128_HMAC; return(true);

            case "RIPEMD160":
            case "RIPEMD-160": algorithm = RIPEMD160_HMAC; return(true);

            case "RIPEMD256":
            case "RIPEMD-256": algorithm = RIPEMD256_HMAC; return(true);

            case "RIPEMD320":
            case "RIPEMD-320": algorithm = RIPEMD320_HMAC; return(true);

            case "SHA1":
            case "SHA-1": algorithm = SHA1_HMAC; return(true);

            case "SHA224":
            case "SHA-224": algorithm = SHA224_HMAC; return(true);

            case "SHA256":
            case "SHA-256": algorithm = SHA256_HMAC; return(true);

            case "SHA384":
            case "SHA-384": algorithm = SHA384_HMAC; return(true);

            case "SHA512":
            case "SHA-512": algorithm = SHA512_HMAC; return(true);

            case "SHA512-224":
            case "SHA-512-224": algorithm = SHA512_224_HMAC; return(true);

            case "SHA512-256":
            case "SHA-512-256": algorithm = SHA512_256_HMAC; return(true);

            case "SHA3-224":
            case "SHA-3-224": algorithm = SHA3_224_HMAC; return(true);

            case "SHA3-256":
            case "SHA-3-256": algorithm = SHA3_256_HMAC; return(true);

            case "SHA3-384":
            case "SHA-3-384": algorithm = SHA3_384_HMAC; return(true);

            case "SHA3-512":
            case "SHA-3-512": algorithm = SHA3_512_HMAC; return(true);

            case "SHAKE128":
            case "SHAKE-128": algorithm = SHAKE_128_HMAC; return(true);

            case "SHAKE256":
            case "SHAKE-256": algorithm = SHAKE_256_HMAC; return(true);

            case "SKEIN-256-256": algorithm = Skein_256_256_HMAC; return(true);

            case "SKEIN-512-512": algorithm = Skein_512_512_HMAC; return(true);

            case "SKEIN-1024-1024": algorithm = Skein_1024_1024_HMAC; return(true);

            case "SM3": algorithm = SM3_HMAC; return(true);

            case "TIGER": algorithm = Tiger_HMAC; return(true);

            case "WHIRLPOOL": algorithm = Whirlpool_HMAC; return(true);

            default: break;
            }
            if (HashAlgorithmHelper.TryGetNanoAlgorithm(mechanism, out IHashAlgorithm hashAlgorithm))
            {
                algorithm = new HMAC(hashAlgorithm);
                return(true);
            }
            else
            {
                algorithm = null;
                return(false);
            }
        }
示例#11
0
        public static void Main(string[] args)
        {
            // Prepare temp file.
            string file_name = Path.GetTempFileName();

            using (var fs = new FileStream(file_name, FileMode.Open))
            {
                byte[] v = new byte[256];
                new Random().NextBytes(v);
                fs.Write(v, 0, v.Length);
            }

            // Prepare stream.
            MemoryStream ms = new MemoryStream(new byte[] { 2, 3, 4, 5, 6, 7 });

            // Choose algorithm. Explore HashFactory for more algorithms.
            IHash hash = HashFactory.Crypto.CreateSHA256();

            // Hash data immediate.
            HashResult r = hash.ComputeString("test", Encoding.ASCII);

            // Hash data.
            hash.Initialize(); // Not mandatory after Compute and TransformFinal
            hash.TransformULong(6);
            hash.TransformString("test");
            r = hash.TransformFinal();

            // Calculate 32-bits hash.
            hash = HashFactory.Checksum.CreateCRC32_IEEE();
            uint crc32 = hash.ComputeString("test", Encoding.ASCII).GetUInt();

            // For CRCs you may specify parameters.
            hash = HashFactory.Checksum.CreateCRC32(
                HashLib.Checksum.CRC32Polynomials.IEEE_802_3, uint.MaxValue, uint.MaxValue);
            hash = HashFactory.Checksum.CreateCRC32(
                0xF0F0F0F0, uint.MaxValue, uint.MaxValue);

            // Most hashes can be created in two ways.
            hash = HashFactory.Crypto.CreateHaval(HashRounds.Rounds3, HashSize.HashSize256);
            hash = HashFactory.Crypto.CreateHaval_3_256();

            // Calculate 64-bits hash.
            hash = HashFactory.Hash64.CreateMurmur2();
            ulong crc64 = hash.ComputeString("test", Encoding.ASCII).GetULong();

            // Calculate hash with key.
            var hash_with_key = HashFactory.Hash128.CreateMurmur3_128();

            hash_with_key.Key = new MersenneTwister().NextBytes(hash_with_key.KeyLength.Value);
            r = hash_with_key.ComputeString("test", Encoding.ASCII);
            // This will restore default key.
            hash_with_key.Key = null;

            // Get some information about algorithm. BlockSize has only informative meaning.
            System.Console.WriteLine("{0}, {1}, {2}", hash.BlockSize, hash.HashSize, hash.Name);

            // Here you can find algorithms grouped by its properties.
            foreach (var h in Hashes.CryptoAll)
            {
                System.Console.WriteLine(((IHash)Activator.CreateInstance(h)).Name);
            }
            foreach (var h in Hashes.CryptoNotBuildIn)
            {
                System.Console.WriteLine(((IHash)Activator.CreateInstance(h)).Name);
            }
            foreach (var h in Hashes.CryptoBuildIn)
            {
                System.Console.WriteLine(((IHash)Activator.CreateInstance(h)).Name);
            }
            foreach (var h in Hashes.Checksums)
            {
                System.Console.WriteLine(((IHash)Activator.CreateInstance(h)).Name);
            }
            // ... And more

            // Hash stream.
            r           = hash.ComputeStream(ms);
            ms.Position = 2;
            r           = hash.ComputeStream(ms);    // Compute all bytes starting from 2
            ms.Position = 3;
            r           = hash.ComputeStream(ms, 2); // Compute 2 bytes starting from 3

            hash.TransformInt(111);
            ms.Position = 0;
            hash.TransformStream(ms);
            r = hash.TransformFinal();

            // Hash file
            r = hash.ComputeFile(file_name);
            r = hash.ComputeFile(file_name, 10);     // Compute all bytes starting from 10
            r = hash.ComputeFile(file_name, 12, 10); // Compute 10 bytes starting from 12.

            hash.TransformInt(111);
            hash.TransformFile(file_name);
            r = hash.TransformFinal();

            // Calculate HMAC.
            IHMAC hmac = HashFactory.HMAC.CreateHMAC(HashFactory.Crypto.CreateSHA256());

            hmac.Key = Converters.ConvertStringToBytes("secret", Encoding.ASCII);
            r        = hmac.ComputeString("test", Encoding.ASCII);
            Debug.Assert(hmac.KeyLength == null, "NULL means key can be any length");

            // Get System.Security.Cryptography.HashAlgorithm wrapper for algorithms from this library.
            System.Security.Cryptography.HashAlgorithm hash2 = HashFactory.Wrappers.HashToHashAlgorithm(hash);

            // And back.
            hash = HashFactory.Wrappers.HashAlgorithmToHash(hash2);

            // Some algorithms have fast specialized methods for calculating hashes for all data types.
            // They are designed for calculating good-behaving hash codes for hash-tables.
            hash = HashFactory.Hash32.CreateMurmur2();
            Debug.Assert(hash is IFastHash32);

            // Some algorithms can calculated hashes only when they had all needed data,
            // they accumulated data to the very end.
            hash = HashFactory.Hash32.CreateMurmur2();
            Debug.Assert(hash is INonBlockHash);

            // Use build-in cryptography hash algorithms.
            hash = HashFactory.Crypto.BuildIn.CreateSHA256Cng();

            // Delete temp file.
            new FileInfo(file_name).Delete();
        }
示例#12
0
 public HOTP(IHMAC hmac)
 {
     _hmac = hmac;
 }
示例#13
0
        protected void TestHMAC(IHMAC a_build_in_hmac, IHMAC a_not_build_in_hmac)
        {
            Assert.AreEqual(a_not_build_in_hmac.HashSize, a_build_in_hmac.HashSize);
            Assert.AreEqual(a_not_build_in_hmac.BlockSize, a_build_in_hmac.BlockSize);

            Assert.IsTrue(a_not_build_in_hmac is HMACNotBuildInAdapter);
            Assert.IsTrue(a_build_in_hmac is HMACBuildInAdapter);

            List<int> keys_length = new List<int>() { 0, 1, 7, 51, 121, 512, 1023 };
            keys_length.Add(a_build_in_hmac.BlockSize - 1);
            keys_length.Add(a_build_in_hmac.BlockSize);
            keys_length.Add(a_build_in_hmac.BlockSize + 1);

            List<int> msgs_length = new List<int>();
            msgs_length.AddRange(keys_length);
            msgs_length.Add(a_build_in_hmac.BlockSize * 4 - 1);
            msgs_length.Add(a_build_in_hmac.BlockSize * 4);
            msgs_length.Add(a_build_in_hmac.BlockSize * 4 + 1);

            foreach (int key_length in keys_length)
            {
                byte[] key = m_random.NextBytes(key_length);

                a_not_build_in_hmac.Key = key;
                a_build_in_hmac.Key = key;

                foreach (int msg_length in msgs_length)
                {
                    byte[] msg = m_random.NextBytes(msg_length);

                    a_not_build_in_hmac.Initialize();
                    a_not_build_in_hmac.TransformBytes(msg);
                    HashResult h1 = a_not_build_in_hmac.TransformFinal();

                    a_build_in_hmac.Initialize();
                    a_build_in_hmac.TransformBytes(msg);
                    HashResult h2 = a_build_in_hmac.TransformFinal();

                    Assert.AreEqual(h1, h2, a_build_in_hmac.Name);

                    h1 = a_not_build_in_hmac.ComputeString(BitConverter.ToString(msg));
                    h2 = a_build_in_hmac.ComputeString(BitConverter.ToString(msg));

                    Assert.AreEqual(h1, h2, a_build_in_hmac.Name);
                }
            }
        }
示例#14
0
 static public Func <Func <HttpMessageHandler>, IYousScribeHttpClient> GetBaseClientFactory(byte[] secretKey, int applicationId, IHMAC hmac)
 {
     return((c) =>
     {
         return c == null ? new YousScribeHMACHttpClientDecorator(new HttpClient(), secretKey, applicationId, hmac) : new YousScribeHMACHttpClientDecorator(new HttpClient(c()), secretKey, applicationId, hmac);
     });
 }