Esempio n. 1
0
        private static string GetHashedPassword(string password)
        {
            string key = string.Join(":", new string[] { password, Salt });

            using (HMAC hmac = HMAC.Create(Algorithm))
            {
                // Hash the key.
                hmac.Key = Encoding.UTF8.GetBytes(Salt);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
                return(Convert.ToBase64String(hmac.Hash));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Creates a SHA512 hash of the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="algo">algorithmName: MD5,SHA1,SHA256,SHA384,SHA512 default: SHA256</param>
        /// <returns>A hash</returns>
        public static string HmacBase64(this Stream input, AlgorithmNameEnum algo = AlgorithmNameEnum.HMACSHA256)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            using (var sha = HMAC.Create(algo.ToString()))
            {
                return(sha.ComputeHash(input).ToBase64());
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Creates a SHA512 hash of the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="algo">algorithmName: MD5,SHA1,SHA256,SHA384,SHA512 default: SHA256</param>
        /// <returns>A hash.</returns>
        public static string HmacBase64(this byte[] input, AlgorithmNameEnum algo = AlgorithmNameEnum.HMACSHA256)
        {
            if (input == null)
            {
                return(null);
            }

            using (var sha = HMAC.Create(algo.ToString()))
            {
                return(sha.ComputeHash(input).ToBase64());
            }
        }
Esempio n. 4
0
        public static string HashWithHMAC(EnvironmentProfile profile, string data)
        {
            Contract.Requires(profile != null);
            Contract.Requires(data != null);
            var hmacAlgo = HMAC.Create();

            hmacAlgo.Key = CreateHmacKey(profile);
            byte[] hmacHash = hmacAlgo.ComputeHash(Encoding.UTF8.GetBytes(data));
            string result   = Hexify(hmacHash);

            return(result);
        }
Esempio n. 5
0
        //raturns the claim
        public static byte[] authenticateUser(String username,
                                              String password,
                                              String poolName,
                                              Tuple <BigInteger, BigInteger> TupleAa,
                                              String saltString,
                                              String srp_b,
                                              String secretBlock,
                                              String formattedTimestamp)
        {
            byte[] authSecretBlock = System.Convert.FromBase64String(secretBlock);


            BigInteger B = new BigInteger(srp_b, 16);

            if (B.Mod(AuthenticationHelper.N).Equals(BigInteger.Zero))
            {
                throw new Exception("B cannot be zero");
            }

            BigInteger salt = new BigInteger(saltString, 16);

            // We need to generate the key to hash the response based on our A and what AWS sent back
            byte[] key = getPasswordAuthenticationKey(username, password, poolName, TupleAa, B, salt);

            // HMAC our data with key (HKDF(S)) (the shared secret)
            byte[] hmac;
            try
            {
                HMAC mac = HMAC.Create("HMACSHA256");
                mac.Key = key;

                //bytes bytes bytes....
                byte[] poolNameByte = Encoding.UTF8.GetBytes(poolName);
                byte[] name         = Encoding.UTF8.GetBytes(username);
                //secretBlock here
                byte[] timeByte = Encoding.UTF8.GetBytes(formattedTimestamp);
                byte[] content  = new byte[poolNameByte.Length + name.Length + authSecretBlock.Length + timeByte.Length];

                Buffer.BlockCopy(poolNameByte, 0, content, 0, poolNameByte.Length);
                Buffer.BlockCopy(name, 0, content, poolNameByte.Length, name.Length);
                Buffer.BlockCopy(authSecretBlock, 0, content, poolNameByte.Length + name.Length, authSecretBlock.Length);
                Buffer.BlockCopy(timeByte, 0, content, poolNameByte.Length + name.Length + authSecretBlock.Length, timeByte.Length);

                hmac = mac.ComputeHash(content);
            }
            catch (Exception e)
            {
                throw new Exception("Exception in authentication", e);
            }

            return(hmac);
        }
Esempio n. 6
0
        private static byte[] GetHash([CanBeNull] string input, EHashType hash)
        {
            var inputBytes = Encoding.ASCII.GetBytes(input);

            switch (hash)
            {
            case EHashType.HMAC:
                return(HMAC.Create().ComputeHash(inputBytes));

#pragma warning disable RECS0030                                   // Suggests using the class declaring a static function when calling it
            case EHashType.HMACMD5:                                // DevSkim: ignore DS126858
                return(HMACMD5.Create().ComputeHash(inputBytes));  // DevSkim: ignore DS126858

            case EHashType.HMACSHA1:                               // DevSkim: ignore DS126858
                return(HMACSHA1.Create().ComputeHash(inputBytes)); // DevSkim: ignore DS126858

            case EHashType.HMACSHA256:
                return(HMACSHA256.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA384:
                return(HMACSHA384.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA512:
                return(HMACSHA512.Create().ComputeHash(inputBytes));

#pragma warning restore RECS0030                               // Suggests using the class declaring a static function when calling it

            case EHashType.MD5:                                // DevSkim: ignore DS126858
#pragma warning disable SG0006                                 // Weak hashing function
                return(MD5.Create().ComputeHash(inputBytes));  // DevSkim: ignore DS126858

#pragma warning restore SG0006                                 // Weak hashing function

            case EHashType.SHA1:                               // DevSkim: ignore DS126858
#pragma warning disable SG0006                                 // Weak hashing function
                return(SHA1.Create().ComputeHash(inputBytes)); // DevSkim: ignore DS126858

#pragma warning restore SG0006                                 // Weak hashing function

            case EHashType.SHA256:
                return(SHA256.Create().ComputeHash(inputBytes));

            case EHashType.SHA384:
                return(SHA384.Create().ComputeHash(inputBytes));

            case EHashType.SHA512:
                return(SHA512.Create().ComputeHash(inputBytes));

            default:
                return(inputBytes);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// 计算 HMAC 散列。
        /// </summary>
        /// <typeparam name="THmac">指定的 HMAC 类型。</typeparam>
        /// <param name="buffer">给定的字节数组。</param>
        /// <param name="key">给定的密钥。</param>
        /// <returns>返回字节数组。</returns>
        public static byte[] ComputeHmacHash<THmac>(this byte[] buffer, byte[] key)
            where THmac : HMAC
        {
            var algo = HmacAlgorithms.GetOrAdd(typeof(THmac).Name,
                key => HMAC.Create(key));
            
            return ExtensionSettings.Preference.RunLocker(() =>
            {
                algo.Key = key.NotEmpty(nameof(key));

                return algo.ComputeHash(buffer);
            });
        }
Esempio n. 8
0
        /// <summary>
        ///     Common HMAC for hash input text.
        /// </summary>
        /// <param name="algorithm"></param>
        /// <param name="key"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        private static string CommonHmacHash(string algorithm,
                                             ref byte[] key,
                                             string text)
        {
            key ??= GenerateHashedKey();

            using var crypto = HMAC.Create(algorithm);
            crypto.Key       = key;
            var hashed = crypto.ComputeHash(Encoding.UTF8.GetBytes(text));

            return(BitConverter.ToString(hashed)
                   .Replace("-", string.Empty));
        }
Esempio n. 9
0
        public string CalculateSignature(IRequest r, ISignatureSpecification spec, string key)
        {
            var algorithm       = spec.Algorithm;
            var signatureString = signatureStringExtractor.ExtractSignatureString(r, spec);
            var hmac            = HMAC.Create(algorithm.Replace("-", "").ToUpper());

            hmac.Initialize();
            hmac.Key = Convert.FromBase64String(key);
            var bytes     = hmac.ComputeHash(new MemoryStream(Encoding.UTF8.GetBytes(signatureString)));
            var signature = Convert.ToBase64String(bytes);

            return(signature);
        }
        /// <summary>
        /// Get the hash algorithm and hmac algorithm for V2.
        /// </summary>
        /// <param name="hashAlgo">The hash algorithm value</param>
        /// <returns>The hash algorithm and hmac algorithm</returns>
        public static void GetHashAlgorithm(dwHashAlgoV2_Values hashAlgo, out HashAlgorithm hashAlgorithm, out HMAC hmacAlgorithm)
        {
            switch (hashAlgo)
            {
            case dwHashAlgoV2_Values.TRUNCATED_SHA512:
                hashAlgorithm = HashAlgorithm.Create("SHA512");
                hmacAlgorithm = HMAC.Create("HMACSHA512");
                break;

            default:
                throw new NotImplementedException();
            }
        }
        //todo for when requires username and password
        /// <summary>
        /// its just a hashed password for use as token key
        /// </summary>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public static string CreateTokenKeyWithPassword(string password, string salt)
        {
            const string alg = "HmacSHA256";

            var key = string.Join(":", new string[] { password, salt });

            using (var hmac = HMAC.Create(alg))
            {
                hmac.Key = Encoding.UTF8.GetBytes(salt);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
                return(Convert.ToBase64String(hmac.Hash));
            }
        }
Esempio n. 12
0
        public HMACSignatureAlgorithm(string secret, HashAlgorithmName hashAlgorithm)
        {
            if (secret == null)
            {
                throw new ArgumentNullException(nameof(secret));
            }
            var algorithmName = $"HMAC{hashAlgorithm}";

            HashAlgorithm      = hashAlgorithm;
            Secret             = secret;
            _realAlgorithm     = HMAC.Create(algorithmName);
            _realAlgorithm.Key = Encoding.UTF8.GetBytes(secret);
        }
 /// <summary>
 /// Creates a hashed signature from the string and private key provided.
 /// </summary>
 /// <param name="dataBytes">
 /// A byte array generated from the string to be signed.
 /// </param>
 /// <param name="keyBytes">
 /// The private key to use in hashing
 /// </param>
 /// <returns>
 /// the hashed signature
 /// </returns>
 private static byte[] Sign(byte[] dataBytes, byte[] keyBytes)
 {
     try
     {
         HMAC mac = HMAC.Create(HmacAlgorithm);
         mac.Key = keyBytes;
         return(mac.ComputeHash(dataBytes));
     }
     catch (CryptographicException ike)
     {
         throw new SigningException(ike.Message, ike);
     }
 }
Esempio n. 14
0
        public static void NamedKeyedHashAlgorithmCreate(string identifier, Type actualType)
        {
            using (KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(identifier))
            {
                Assert.IsType(actualType, kha);

                // .NET Core only has HMAC keyed hash algorithms, so combine the two tests
                using (HMAC hmac = HMAC.Create(identifier))
                {
                    Assert.IsType(actualType, hmac);
                }
            }
        }
Esempio n. 15
0
        private static byte[] GetHash(string Source, HashType hash)
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(Source);

            switch (hash)
            {
            case HashType.HMAC:
                return(HMAC.Create().ComputeHash(inputBytes));

            case HashType.HMACMD5:
                return(HMACMD5.Create().ComputeHash(inputBytes));

            case HashType.HMACSHA1:
                return(HMACSHA1.Create().ComputeHash(inputBytes));

            case HashType.HMACSHA256:
                return(HMACSHA256.Create().ComputeHash(inputBytes));

            case HashType.HMACSHA384:
                return(HMACSHA384.Create().ComputeHash(inputBytes));

            case HashType.HMACSHA512:
                return(HMACSHA512.Create().ComputeHash(inputBytes));

            /*
             * case HashType.MACTripleDES:
             * return MACTripleDES.Create().ComputeHash(inputBytes);
             */
            case HashType.MD5:
                return(MD5.Create().ComputeHash(inputBytes));

            /*
             * case HashType.RIPEMD160:
             * return RIPEMD160.Create().ComputeHash(inputBytes);
             */
            case HashType.SHA1:
                return(SHA1.Create().ComputeHash(inputBytes));

            case HashType.SHA256:
                return(SHA256.Create().ComputeHash(inputBytes));

            case HashType.SHA384:
                return(SHA384.Create().ComputeHash(inputBytes));

            case HashType.SHA512:
                return(SHA512.Create().ComputeHash(inputBytes));

            default:
                return(inputBytes);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Generates a HOTP token
        /// </summary>
        /// <param name="Key">Shared secret</param>
        /// <param name="Counter">HOTP Counter. Use <see cref="GetCounter(int, int, DateTime)"/> to use as TOTP</param>
        /// <param name="DigitCount">Number of digits to extract (1-10)</param>
        /// <returns>HOTP token</returns>
        public static int GetHOTP(byte[] Key, long Counter, int DigitCount = DIGIT_COUNT)
        {
            //Verify basic parameter conditions
            if (Counter < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(Counter));
            }
            if (Key == null || Key.Length == 0)
            {
                throw new ArgumentNullException(nameof(Key));
            }
            if (DigitCount < 1 || DigitCount > 10)
            {
                throw new ArgumentOutOfRangeException(nameof(DigitCount));
            }

            //Convert integer to an 8 byte big endian byte array and discard the sign bit
            var CounterBytes = new byte[] {
                (byte)(Counter >> 56 & 0x7F),
                (byte)(Counter >> 48 & 0xFF),
                (byte)(Counter >> 40 & 0xFF),
                (byte)(Counter >> 32 & 0xFF),
                (byte)(Counter >> 24 & 0xFF),
                (byte)(Counter >> 16 & 0xFF),
                (byte)(Counter >> 8 & 0xFF),
                (byte)(Counter & 0xFF)
            };

            using (var Hasher = HMAC.Create(HMAC_ALGO))
            {
                //Compute the HMAC of the data
                Hasher.Key = Key;
                var Result = Hasher.ComputeHash(CounterBytes);

                //Get the offset we extract data from. This can range from 0 to 15
                var ResultOffset = Result[Result.Length - 1] & 0x0F;

                //Convert byte array to big endian 4 byte integer and discard sign bit
                var ResultDigits =
                    (Result[ResultOffset + 0] << 24 & 0x7F000000) |
                    Result[ResultOffset + 1] << 16 |
                        Result[ResultOffset + 2] << 8 |
                        Result[ResultOffset + 3];

                //Return the Number that is the token.
                return(ResultDigits % (int)Math.Pow(10, DigitCount));
                //Note:
                //You are supposed to pad the number to the left with zeros to ensure it's "DigitCount" digits long.
                //You can do this using "SomeNumber.ToString("".PadRight(DigitCount,'0'));"
            }
        }
        public static Cryptography SetHashAlgorithm(this Cryptography cryptography,
                                                    CryptoServiceProviderType providerType)
        {
            cryptography.HashAlgorithm?.Clear();

            switch (providerType)
            {
            default:
            case CryptoServiceProviderType.MD5:
                cryptography.HashAlgorithm = MD5.Create();
                break;

            case CryptoServiceProviderType.SHA1:
                cryptography.HashAlgorithm = SHA1.Create();
                break;

            case CryptoServiceProviderType.SHA256:
                cryptography.HashAlgorithm = SHA256.Create();
                break;

            case CryptoServiceProviderType.SHA384:
                cryptography.HashAlgorithm = SHA384.Create();
                break;

            case CryptoServiceProviderType.SHA512:
                cryptography.HashAlgorithm = SHA512.Create();
                break;

            case CryptoServiceProviderType.HMACMD5:
                cryptography.HashAlgorithm = HMAC.Create();
                break;

            case CryptoServiceProviderType.HMACSHA1:
                cryptography.HashAlgorithm = HMAC.Create();
                break;

            case CryptoServiceProviderType.HMACSHA256:
                cryptography.HashAlgorithm = HMAC.Create();
                break;

            case CryptoServiceProviderType.HMACSHA384:
                cryptography.HashAlgorithm = HMAC.Create();
                break;

            case CryptoServiceProviderType.HMACSHA512:
                cryptography.HashAlgorithm = HMAC.Create();
                break;
            }

            return(cryptography);
        }
Esempio n. 18
0
        public static HMAC Create(string algorithmName, byte[] key)
        {
            HMAC hmac = HMAC.Create(algorithmName);

            try
            {
                hmac.Key = key;
                return(hmac);
            }
            catch {
                hmac.Dispose();
                throw;
            }
        }
    public override Task Invoke(IOutgoingPhysicalMessageContext context, Func <Task> next)
    {
        using (var hmac = HMAC.Create("hmacsha256"))
        {
            hmac.Key = SharedKeys.SigningKey;

            var hashBytes        = hmac.ComputeHash(context.Body);
            var hashBase64String = Convert.ToBase64String(hashBytes);

            context.Headers.Add("X-Message-Signature", hashBase64String);
        }

        return(next());
    }
Esempio n. 20
0
        public void HmacCompute_KnownUTF8ValuesFromE5RWordAndKey(string algorithmName,
                                                                 string expectedValue)
        {
            var inputKey      = new byte[] { 5, 5, 18 };
            var inputE5RBytes = Encoding.UTF8.GetBytes("E5R");
            var algorithm     = HMAC.Create(algorithmName);

            algorithm.Key = inputKey;

            var output       = inputE5RBytes.Hash(algorithm);
            var outputString = string.Concat(output.Select(c => c.ToString("x2")));

            Assert.Equal(expectedValue, outputString);
        }
Esempio n. 21
0
        /// <summary>
        /// Creates a HMAC signature from the supplied data.
        /// </summary>
        /// <param name="signatureData">The data to create a signature from.</param>
        /// <returns>The signature as a <see cref="string"/>.</returns>
        /// <exception cref="ArgumentNullException">The signature data is null.</exception>
        /// <exception cref="ArgumentException">The key from the signature data is null or empty.</exception>
        /// <exception cref="HmacConfigurationException">One or more of the configuration parameters are invalid.</exception>
        public virtual string CreateSignature(HmacSignatureData signatureData)
        {
            if (signatureData == null)
            {
                throw new ArgumentNullException(nameof(signatureData), "The signature data cannot be null.");
            }
            if (HmacConfiguration.SignatureEncoding == null)
            {
                throw new HmacConfigurationException("The character encoding cannot be null.");
            }
            if (string.IsNullOrEmpty(signatureData.Key))
            {
                throw new ArgumentException("The key cannot be null or empty.", nameof(signatureData));
            }

            string headerString = signatureData.Headers != null
                ? CreateCanonicalizedHeadersString(signatureData.Headers)
                : null;

            string requestUri = CreateCanonicalizedUriString(signatureData.RequestUri);

            string representation = string.Join(
                HmacConfiguration.SignatureDataSeparator ?? string.Empty,
                signatureData.HttpMethod?.Trim().ToUpperInvariant(),
                signatureData.ContentMd5?.Trim(),
                signatureData.ContentType?.Trim().ToLowerInvariant(),
                signatureData.Date?.Trim(),
                signatureData.Username,
                headerString,
                requestUri);

            byte[] keyBytes            = SignatureEncoding.GetBytes(signatureData.Key);
            byte[] representationBytes = SignatureEncoding.GetBytes(representation);

            HMAC hmac;

            try
            {
                hmac = HMAC.Create(HmacConfiguration.HmacAlgorithm);
            }
            catch (Exception ex)
            {
                throw new HmacConfigurationException("The HMAC implemenation instance could not be created from the configured algorithm name.", ex);
            }

            hmac.Key = keyBytes;
            byte[] hash = hmac.ComputeHash(representationBytes);
            return(Convert.ToBase64String(hash));
        }
Esempio n. 22
0
        private static byte[] GetHash(string input, EHashType hash)
        {
            var inputBytes = Encoding.ASCII.GetBytes(input);

            switch (hash)
            {
            case EHashType.HMAC:
                return(HMAC.Create().ComputeHash(inputBytes));

            case EHashType.HMACMD5:
                return(HMACMD5.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA1:
                return(HMACSHA1.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA256:
                return(HMACSHA256.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA384:
                return(HMACSHA384.Create().ComputeHash(inputBytes));

            case EHashType.HMACSHA512:
                return(HMACSHA512.Create().ComputeHash(inputBytes));

            case EHashType.MACTripleDES:
                return(MACTripleDES.Create().ComputeHash(inputBytes));

            case EHashType.MD5:
                return(MD5.Create().ComputeHash(inputBytes));

            case EHashType.RIPEMD160:
                return(RIPEMD160.Create().ComputeHash(inputBytes));

            case EHashType.SHA1:
                return(SHA1.Create().ComputeHash(inputBytes));

            case EHashType.SHA256:
                return(SHA256.Create().ComputeHash(inputBytes));

            case EHashType.SHA384:
                return(SHA384.Create().ComputeHash(inputBytes));

            case EHashType.SHA512:
                return(SHA512.Create().ComputeHash(inputBytes));

            default:
                return(inputBytes);
            }
        }
Esempio n. 23
0
        public HMACFixup(DataElement parent, Dictionary <string, Variant> args)
            : base(parent, args, "ref")
        {
            ParameterParser.Parse(this, args);
            HMAC hashSizeTest = HMAC.Create(Hash.ToString());

            if (Length > (hashSizeTest.HashSize / 8))
            {
                throw new PeachException("The truncate length is greater than the hash size for the specified algorithm.");
            }
            if (Length < 0)
            {
                throw new PeachException("The truncate length must be greater than or equal to 0.");
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Creates an HMAC-SHA algorithm with the specified name and key.
        /// </summary>
        /// <param name="algorithmName">A name from the available choices in the static const members of this class.</param>
        /// <param name="key">The secret key used as the HMAC.</param>
        /// <returns>The HMAC algorithm instance.</returns>
        internal static HMAC Create(string algorithmName, byte[] key)
        {
            Requires.NotNullOrEmpty(algorithmName, "algorithmName");
            Requires.NotNull(key, "key");

            HMAC hmac = HMAC.Create(algorithmName);

            try {
                hmac.Key = key;
                return(hmac);
            } catch {
                hmac.Dispose();
                throw;
            }
        }
 /// <summary>
 ///     Get encryption hash.
 /// </summary>
 /// <param name="key">The encryption key.</param>
 /// <param name="data">The string data.</param>
 /// <returns>The hash.</returns>
 /// <exception cref="EncryptionException">On compute hash fail.</exception>
 private static string Encrypt(string key, string data)
 {
     try
     {
         var encoding = Encoding.GetEncoding("utf-8");
         var hmac     = HMAC.Create("HMACSHA256");
         hmac.Key = encoding.GetBytes(key);
         var hash = hmac.ComputeHash(encoding.GetBytes(data));
         return(string.Concat(Array.ConvertAll(hash, hex => hex.ToString("X2"))));
     }
     catch (System.Exception e)
     {
         throw new EncryptionException(e);
     }
 }
Esempio n. 26
0
        public static string GenerateToken(string username, string passwordHash, string ip, string userAgent, long ticks)
        {
            string hash      = string.Join(":", new string[] { username, ip, userAgent, ticks.ToString() });
            string hashLeft  = "";
            string hashRight = "";

            using (HMAC hmac = HMAC.Create(_alg))
            {
                hmac.Key = Encoding.UTF8.GetBytes(passwordHash);
                hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
                hashLeft  = Convert.ToBase64String(hmac.Hash);
                hashRight = string.Join(":", new string[] { username, ticks.ToString() });
            }
            return(Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(":", hashLeft, hashRight))));
        }
Esempio n. 27
0
 public static void StaticCreateMethods()
 {
     // These are not supported because CryptoConfig exists in Algorithms assembly.
     // CryptoConfig exists in Algorithms partly because it requires the Oid class in Encoding assembly.
     Assert.Throws <PlatformNotSupportedException>(() => AsymmetricAlgorithm.Create());
     Assert.Throws <PlatformNotSupportedException>(() => AsymmetricAlgorithm.Create(null));
     Assert.Throws <PlatformNotSupportedException>(() => HashAlgorithm.Create());
     Assert.Throws <PlatformNotSupportedException>(() => HashAlgorithm.Create(null));
     Assert.Throws <PlatformNotSupportedException>(() => KeyedHashAlgorithm.Create());
     Assert.Throws <PlatformNotSupportedException>(() => KeyedHashAlgorithm.Create(null));
     Assert.Throws <PlatformNotSupportedException>(() => HMAC.Create());
     Assert.Throws <PlatformNotSupportedException>(() => HMAC.Create(null));
     Assert.Throws <PlatformNotSupportedException>(() => SymmetricAlgorithm.Create());
     Assert.Throws <PlatformNotSupportedException>(() => SymmetricAlgorithm.Create(null));
 }
        public static ShellSettings CreateEncryptionEnabled()
        {
            const string encryptionAlgorithm = "AES";
            const string hashAlgorithm       = "HMACSHA256";

            return(new ShellSettings {
                Name = "Alpha",
                RequestUrlHost = "wiki.example.com",
                RequestUrlPrefix = "~/foo",
                EncryptionAlgorithm = encryptionAlgorithm,
                EncryptionKey = SymmetricAlgorithm.Create(encryptionAlgorithm).Key.ToHexString(),
                HashAlgorithm = hashAlgorithm,
                HashKey = HMAC.Create(hashAlgorithm).Key.ToHexString()
            });
        }
Esempio n. 29
0
        protected override System.Security.Cryptography.HashAlgorithm Create()
        {
            HMAC mac;

            if (string.IsNullOrWhiteSpace(AlgorithmName))
            {
                mac = HMAC.Create();
            }
            else
            {
                mac = HMAC.Create(AlgorithmName);
            }
            mac.Key = Encoding.GetBytes(Key);
            return(mac);
        }
Esempio n. 30
0
        private static HMAC CreateHMAC(HashAlgorithmName hashAlgorithmName, byte[] key)
        {
            if (!HMACCreators.TryGetValue(hashAlgorithmName, out var creatorFunc))
            {
                var fallback = HMAC.Create($"HMAC{hashAlgorithmName.Name}");
                if (fallback == null)
                {
                    throw new NotSupportedException($"The specified hash algorithm '{hashAlgorithmName.Name}' is not supported.");
                }
                fallback.Key = key;
                return(fallback);
            }

            return(creatorFunc(key));
        }