Esempio n. 1
0
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                var crypt = MacAlgorithmProvider.OpenAlgorithm(ConvertToAlgorithName(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.");
                }

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

                IBuffer dataBuffer = CryptographicBuffer.CreateFromByteArray(data);
                var     keyBuffer  = CryptographicBuffer.CreateFromByteArray(key);
                var     cryptoKey  = crypt.CreateKey(keyBuffer);

                var sigBuffer = CryptographicEngine.Sign(cryptoKey, dataBuffer);

                return(sigBuffer.ToArray());
            }
        private string _generateConfirmationHashForTime(long time, string tag)
        {
            int n2 = tag != null?Math.Min(40, 8 + tag.Length) : 8;

            var array = new byte[n2];

            for (var n4 = 7; n4 >= 0; n4--)
            {
                array[n4] = (byte)time;
                time    >>= 8;
            }
            if (tag != null)
            {
                Array.Copy(Encoding.UTF8.GetBytes(tag), 0, array, 8, n2 - 8);
            }

            try
            {
                IBuffer identitySecretArray = CryptographicBuffer.DecodeFromBase64String(this.IdentitySecret);

                MacAlgorithmProvider hmacsha1 = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
                CryptographicKey     hmacKey  = hmacsha1.CreateKey(identitySecretArray);

                string encodedData = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Sign(hmacKey, CryptographicBuffer.CreateFromByteArray(array)));
                string hash        = WebUtility.UrlEncode(encodedData);
                return(hash);
            }
            catch (Exception)
            {
                return(null); //Fix soon: catch-all is BAD!
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Calculates OTPs
        /// </summary>
        static long HmacSha1(byte[] key, byte[] value)
        {
            MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
            IBuffer keyMaterial           = CryptographicBuffer.CreateFromByteArray(key);
            var     cKey = provider.CreateKey(keyMaterial);

            byte[] hmacComputedHash;

            IBuffer data   = CryptographicBuffer.CreateFromByteArray(value);
            IBuffer buffer = CryptographicEngine.Sign(cKey, data);

            CryptographicBuffer.CopyToByteArray(buffer, out hmacComputedHash);


            // The RFC has a hard coded index 19 in this value.
            // This is the same thing but also accomodates SHA256 and SHA512
            // hmacComputedHash[19] => hmacComputedHash[hmacComputedHash.Length - 1]

            int offset = hmacComputedHash[hmacComputedHash.Length - 1] & 0xF;

            return
                ((hmacComputedHash[offset] & 0x7f) << 24
                 | (hmacComputedHash[offset + 1]) << 16
                 | (hmacComputedHash[offset + 2]) << 8
                 | (hmacComputedHash[offset + 3]));
        }
Esempio n. 4
0
            public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName)
            {
                var crypt = MacAlgorithmProvider.OpenAlgorithm(ConvertToAlgorithName(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.");
                }

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

                IBuffer dataBuffer = CryptographicBuffer.CreateFromByteArray(data);
                var     keyBuffer  = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
                var     cryptoKey  = crypt.CreateKey(keyBuffer);

                var    sigBuffer = CryptographicEngine.Sign(cryptoKey, dataBuffer);
                string signature = CryptographicBuffer.EncodeToBase64String(sigBuffer);

                return(signature);
            }
Esempio n. 5
0
        public string OAuthSignature(string SigBaseString, SignatureAuthType signType)
        {
            string signingKey = string.Empty;

            //Debug.WriteLine("In OAuthSignature function");

            switch (signType)
            {
            case SignatureAuthType.ConsumerSecret:
                signingKey = string.Format("{0}&{1}", OAuth.OAuthTypes.OAuthConsumerSecret, "");
                break;

            case SignatureAuthType.RequestSecretToken:
                signingKey = string.Format("{0}&{1}", OAuth.OAuthTypes.OAuthConsumerSecret, !string.IsNullOrEmpty(OAuth.OAuthTypes.OAuthRequestTokenSecretKey) ? OAuth.OAuthTypes.OAuthRequestTokenSecretKey : String.Empty);
                break;

            case SignatureAuthType.AccessSecretToken:
                signingKey = string.Format("{0}&{1}", OAuth.OAuthTypes.OAuthConsumerSecret, !string.IsNullOrEmpty(OAuth.OAuthTypes.OAuthAccessTokenSecretKey) ? OAuth.OAuthTypes.OAuthAccessTokenSecretKey : String.Empty);
                break;

            default:
                break;
            }

            IBuffer KeyBuffer = CryptographicBuffer.ConvertStringToBinary(signingKey, BinaryStringEncoding.Utf8);
            MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
            CryptographicKey     MacKey           = HmacSha1Provider.CreateKey(KeyBuffer);
            IBuffer DataToBeSigned  = CryptographicBuffer.ConvertStringToBinary(SigBaseString, BinaryStringEncoding.Utf8);
            IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);
            String  Signature       = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);

            //Debug.WriteLine("Signed Signature: " + Signature);
            return(Signature);
        }
Esempio n. 6
0
        private static IBuffer ComputeHMAC(IBuffer data, IBuffer hmacKeyBuffer)
        {
            var provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            var key      = provider.CreateKey(hmacKeyBuffer);

            return(CryptographicEngine.Sign(key, data));
        }
Esempio n. 7
0
        /// <summary>
        /// HTTP请求签名
        /// </summary>
        /// <param name="url">请求目标的URL</param>
        /// <param name="body">请求的主体数据</param>
        /// <returns></returns>
        public string SignRequest(string url, byte[] body)
        {
            Uri    u            = new Uri(url);
            string pathAndQuery = u.PathAndQuery;

            byte[] pathAndQueryBytes = Encoding.UTF8.GetBytes(pathAndQuery);

            using (MemoryStream buffer = new MemoryStream())
            {
                buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length);
                buffer.WriteByte((byte)'\n');
                if (body != null && body.Length > 0)
                {
                    buffer.Write(body, 0, body.Length);
                }
#if WINDOWS_UWP
                var    hma        = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
                var    skBuffer   = CryptographicBuffer.ConvertStringToBinary(mac.SecretKey, BinaryStringEncoding.Utf8);
                var    hmacKey    = hma.CreateKey(skBuffer);
                var    dataBuffer = CryptographicBuffer.CreateFromByteArray(buffer.ToArray());
                var    signBuffer = CryptographicEngine.Sign(hmacKey, dataBuffer);
                byte[] digest;
                CryptographicBuffer.CopyToByteArray(signBuffer, out digest);
#else
                HMACSHA1 hmac   = new HMACSHA1(Encoding.UTF8.GetBytes(mac.SecretKey));
                byte[]   digest = hmac.ComputeHash(buffer.ToArray());
#endif
                string digestBase64 = Base64.UrlSafeBase64Encode(digest);
                return(string.Format("{0}:{1}", mac.AccessKey, digestBase64));
            }
        }
Esempio n. 8
0
        public byte[] Sign(byte[] securedInput, object key)
        {
            //using (var sha = HashAlgorithm)
            //{
            //var privateKey = Ensure.Type<AsymmetricAlgorithm>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type.");

            AsymmetricKeyAlgorithmProvider provider =
                AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha256);

            //CryptographicKey cryptographicKey = (CryptographicKey)key;
            CryptographicKey cryptographicKey = provider.ImportKeyPair(((CryptographicKey)key).Export(CryptographicPrivateKeyBlobType.BCryptPrivateKey),
                                                                       CryptographicPrivateKeyBlobType.BCryptPrivateKey);

            //provider.ImportKeyPair(null, CryptographicPrivateKeyBlobType.)

            IBuffer signedData =
                CryptographicEngine.Sign(cryptographicKey, CryptographicBuffer.CreateFromByteArray(securedInput));

            byte[] result;
            CryptographicBuffer.CopyToByteArray(signedData, out result);

            return(result);

            //var pkcs1 = new RSAPKCS1SignatureFormatter(privateKey);
            //pkcs1.SetHashAlgorithm(hashMethod);

            //return pkcs1.CreateSignature(sha.ComputeHash(securedInput));
            //}
        }
        public byte[] ComputeHash(byte[] buffer)
        {
            var crypt     = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
            var sigBuffer = CryptographicEngine.Sign(crypt.CreateKey(CryptographicBuffer.CreateFromByteArray(hmackey)), CryptographicBuffer.CreateFromByteArray(buffer));

            return(sigBuffer.ToArray());
        }
        private byte[] getMac(byte[] key, byte[] message)
        {
            try
            {
                MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);

                IBuffer          buffPrk = CryptographicBuffer.CreateFromByteArray(key);
                CryptographicKey hmacKey = provider.CreateKey(buffPrk);

                IBuffer buffMsg = CryptographicBuffer.CreateFromByteArray(message);

                IBuffer buffHMAC = CryptographicEngine.Sign(hmacKey, buffMsg);

                byte[] ret;
                CryptographicBuffer.CopyToByteArray(buffHMAC, out ret);

                /*Mac mac = Mac.getInstance("HmacSHA256");
                 * mac.init(new SecretKeySpec(key, "HmacSHA256"));*/

                return(ret);
            }
            catch (/*NoSuchAlgorithmException | java.security.InvalidKeyException*/ Exception e) {
                throw new Exception(e.Message);
            }
        }
Esempio n. 11
0
        /*
         * 计算 HMAC-SHA1
         */
        public static String HMACSha1(String data, String key)
        {
            String result = "";

            //使用CodePagesEncodingProvider去注册扩展编码。
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //注册GBK编码
            Encoding encodingGbk = Encoding.GetEncoding("GBK");

            byte[] dataByte = encodingGbk.GetBytes(data);
            byte[] keyByte  = encodingGbk.GetBytes(key);


            byte[] DataBt = encodingGbk.GetBytes(data);
            byte[] KeyBt  = encodingGbk.GetBytes(key);
            data = Encoding.UTF8.GetString(DataBt);
            key  = Encoding.UTF8.GetString(KeyBt);

            string  SHA1Name                = MacAlgorithmNames.HmacSha1;
            IBuffer buffUtf8Msg             = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8);
            IBuffer buffKeyMaterial         = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
            MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(SHA1Name);
            CryptographicKey     hmacKey    = objMacProv.CreateKey(buffKeyMaterial);
            IBuffer buffHMAC                = CryptographicEngine.Sign(hmacKey, buffUtf8Msg);

            byte[] hashValue = Buffer2Bytes(buffHMAC);
            result = Convert.ToBase64String(hashValue);
            return(result);
        }
Esempio n. 12
0
        /// <summary>
        /// Asymmetrically signs a data blob.
        /// </summary>
        /// <param name="data">The data to sign.</param>
        /// <param name="signingPrivateKey">The private key used to sign the data.</param>
        /// <returns>
        /// The signature.
        /// </returns>
        public override byte[] Sign(byte[] data, byte[] signingPrivateKey)
        {
            var key             = SignatureProvider.ImportKeyPair(signingPrivateKey.ToBuffer());
            var signatureBuffer = CryptographicEngine.Sign(key, data.ToBuffer());

            return(signatureBuffer.ToArray());
        }
Esempio n. 13
0
        private IBuffer HMac(MacAlgorithmProvider macProv, IBuffer macKey, IBuffer keyMaterial)
        {
            var     saltKey   = macProv.CreateKey(macKey);
            IBuffer hMacValue = CryptographicEngine.Sign(saltKey, keyMaterial);

            return(hMacValue);
        }
        private static byte[] ComputeHmacSha1Hash(byte[] data, byte[] key)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            //https://channel9.msdn.com/Forums/TechOff/Porting-to-WinRT/4df7586e1ef5400682eda00f0143b610

            MacAlgorithmProvider macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
            //BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;

            CryptographicKey hmacKey       = macAlgorithmProvider.CreateKey(key.AsBuffer());
            IBuffer          signedMessage = CryptographicEngine.Sign(hmacKey, data.AsBuffer());

            //var hashedString  = CryptographicBuffer.EncodeToBase64String(signedMessage);

            return(signedMessage.ToArray());


            ////using (var crypto = new System.Security.Cryptography.HMACSHA1(key))
            ////{
            ////    return crypto.ComputeHash(data);
            ////}
        }
Esempio n. 15
0
        private byte[] Hi()
        {
            var prev = new byte[20];

            // Add 1 to the end of salt with most significat octet first
            var key = new byte[_salt.Length + 4];

            Array.Copy(_salt, key, _salt.Length);
            byte[] g = { 0, 0, 0, 1 };
            Array.Copy(g, 0, key, _salt.Length, 4);

            // Compute initial hash
            var hmac = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");

            // Create Key
            var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(Stringprep.SASLPrep(Password), BinaryStringEncoding.Utf8);
            var hmacKey        = hmac.CreateKey(passwordBuffer);

            var result = CryptographicEngine.Sign(hmacKey, key.AsBuffer()).ToArray();

            Array.Copy(result, prev, (int)result.Length);

            for (var i = 1; i < _i; ++i)
            {
                var temp = CryptographicEngine.Sign(hmacKey, prev.AsBuffer()).ToArray();
                for (var j = 0; j < temp.Length; ++j)
                {
                    result[j] ^= temp[j];
                }

                Array.Copy(temp, prev, temp.Length);
            }

            return(result);
        }
Esempio n. 16
0
        /// <summary>
        /// Generate the signature value based on the given signature base and hash algorithm
        /// </summary>
        /// <param name="macAlgorithm">The hash algorithm used to perform the hashing</param>
        /// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
        /// <param name="key">The key to generate signatrure with macAlgorithm.</param>
        /// <returns>A base64 string of the hash value</returns>
        public string GenerateSignatureUsingHash(MacAlgorithmProvider macAlgorithm, string data, string key)
        {
            if (macAlgorithm == null)
            {
                throw new ArgumentNullException("macAlgorithm");
            }

            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException("data");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("key");
            }

            // Convert the key to a buffer.
            IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);

            // Generate key to sign by specified algorithm.
            CryptographicKey MacKey = macAlgorithm.CreateKey(KeyMaterial);

            // Convert the data to a buffer.
            IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8);

            // Sign the data by specified algorithm with generated key.
            IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);

            // Get signature with Base64.
            string signature = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);

            return(signature);
        }
Esempio n. 17
0
        static IBuffer HMACHandle(IBuffer data, IBuffer key, string hmacType)
        {
            MacAlgorithmProvider hmacAlgorithm = MacAlgorithmProvider.OpenAlgorithm(hmacType);
            CryptographicKey     hmacKey       = hmacAlgorithm.CreateKey(key);

            return(CryptographicEngine.Sign(hmacKey, data));
        }
Esempio n. 18
0
        /// <summary>
        /// This is the click handler for the 'RunSample' button.  It is responsible for executing the sample code.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RunSample_Click(object sender, RoutedEventArgs e)
        {
            SignVerifyText.Text = "";

            String  cookie = "Some Data to sign";
            IBuffer Data   = CryptographicBuffer.ConvertStringToBinary(cookie, BinaryStringEncoding.Utf16BE);

            CryptographicKey key = null;

            if ((bool)bHmac.IsChecked)
            {
                key = GenerateHMACKey();
            }
            else
            {
                key = GenerateAsymmetricKey();
            }

            if (key != null)
            {
                // Sign the data by using the generated key.
                IBuffer Signature = CryptographicEngine.Sign(key, Data);
                SignVerifyText.Text += "    Data was successfully signed.\n";

                // Verify the signature by using the public key.
                if (!CryptographicEngine.VerifySignature(key, Data, Signature))
                {
                    SignVerifyText.Text += "Signature verification failed!";
                    return;
                }
                SignVerifyText.Text += "    Signature was successfully verified.\n";
            }
        }
        void CreateHMAC(String strMsg, String strAlgName, out IBuffer buffMsg, out CryptographicKey hmacKey, out IBuffer buffHMAC)
        {
            // Create a MacAlgorithmProvider object for the specified algorithm.
            MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Demonstrate how to retrieve the name of the algorithm used.
            String strNameUsed = objMacProv.AlgorithmName;

            // Create a buffer that contains the message to be signed.
            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;

            buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

            // Create a key to be signed with the message.
            IBuffer buffKeyMaterial = CryptographicBuffer.GenerateRandom(objMacProv.MacLength);

            hmacKey = objMacProv.CreateKey(buffKeyMaterial);

            // Sign the key and message together.
            buffHMAC = CryptographicEngine.Sign(hmacKey, buffMsg);

            // Verify that the HMAC length is correct for the selected algorithm
            if (buffHMAC.Length != objMacProv.MacLength)
            {
                throw new Exception("Error computing digest");
            }
        }
Esempio n. 20
0
        public byte[] ComputeHash(byte[] buffer, int offset, int count)
        {
#if WINDOWS_STORE
            MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(algorithmName);

            CryptographicKey hmacKey;
            if (Key != null)
            {
                hmacKey = provider.CreateKey(CryptographicBuffer.CreateFromByteArray(Key));
            }
            else
            {
                hmacKey = provider.CreateKey(CryptographicBuffer.GenerateRandom(provider.MacLength));
            }

            IBuffer hmacValue = CryptographicEngine.Sign(hmacKey, CryptographicBuffer.CreateFromByteArray(buffer));

            byte[] result;
            CryptographicBuffer.CopyToByteArray(hmacValue, out result);

            return(result);
#else
            return(hmac.ComputeHash(buffer, offset, count));
#endif
        }
        public string PubnubAccessManagerSign(string key, string data)
        {
            string secret  = key;
            string message = data;

            var encoding = new System.Text.UTF8Encoding();

            byte[] keyByte      = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);

#if NETFX_CORE
            var     hmacsha256      = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            IBuffer valueBuffer     = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);
            IBuffer buffKeyMaterial = CryptographicBuffer.ConvertStringToBinary(secret, BinaryStringEncoding.Utf8);

            CryptographicKey cryptographicKey = hmacsha256.CreateKey(buffKeyMaterial);

            // Sign the key and message together.
            IBuffer bufferProtected = CryptographicEngine.Sign(cryptographicKey, valueBuffer);

            DataReader dataReader  = DataReader.FromBuffer(bufferProtected);
            byte[]     hashmessage = new byte[bufferProtected.Length];
            dataReader.ReadBytes(hashmessage);

            return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_'));
#else
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_'));
            }
#endif
        }
        public static byte[] sha256sum(byte[] key, byte[] message)
        {
            IMacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha256);
            ICryptographicKey     hmacKey  = provider.CreateKey(key);

            byte [] hmac = CryptographicEngine.Sign(hmacKey, message);
            return(hmac);
        }
        public byte[] Sign([ReadOnlyArray] byte[] securedInput, object key)
        {
            var sharedKey = Ensure.Type <byte[]>(key, "HmacUsingSha expects key to be byte[] array.");

            CryptographicKey hmacKey = AlgProvider.CreateKey(CryptographicBuffer.CreateFromByteArray(sharedKey));

            return(Buffer.ToBytes(CryptographicEngine.Sign(hmacKey, CryptographicBuffer.CreateFromByteArray(securedInput))));
        }
Esempio n. 24
0
        /// <summary>
        /// Asymmetrically signs a data blob.
        /// </summary>
        /// <param name="data">The data to sign.</param>
        /// <param name="signingPrivateKey">The private key used to sign the data.</param>
        /// <returns>
        /// The signature.
        /// </returns>
        public override byte[] Sign(byte[] data, byte[] signingPrivateKey)
        {
            var signer          = this.GetSignatureProvider(this.AsymmetricHashAlgorithmName);
            var key             = signer.ImportKeyPair(signingPrivateKey.ToBuffer());
            var signatureBuffer = CryptographicEngine.Sign(key, data.ToBuffer());

            return(signatureBuffer.ToArray());
        }
Esempio n. 25
0
        public static byte[] EncryptHmacSha1(string s)
        {
            IBuffer dataToBeSigned  = CryptographicBuffer.ConvertStringToBinary(s, BinaryStringEncoding.Utf8);
            IBuffer signatureBuffer = CryptographicEngine.Sign(macKey, dataToBeSigned);
            String  signature       = CryptographicBuffer.EncodeToBase64String(signatureBuffer);

            return(Encoding.GetEncoding("iso-8859-1").GetBytes(signature));
        }
Esempio n. 26
0
        private string Hash(string value, string key)
        {
            var provider   = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
            var hmacKey    = provider.CreateKey(CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8));
            var signedData = CryptographicEngine.Sign(hmacKey, CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8));

            return(Convert.ToBase64String(signedData.ToArray()));
        }
Esempio n. 27
0
        public static string HashWith(this string input, MacAlgorithmProvider hashProvider, string key)
        {
            IBuffer          keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
            CryptographicKey cryptoKey   = hashProvider.CreateKey(keyMaterial);
            IBuffer          hash        = CryptographicEngine.Sign(cryptoKey, CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8));

            return(CryptographicBuffer.EncodeToBase64String(hash));
        }
Esempio n. 28
0
        /// <summary>
        /// HMAC(key, str)  := Apply the HMAC keyed hash algorithm (defined in [RFC2104])
        /// </summary>
        public static byte[] ComputeHmacSha1(this byte[] keyMaterial, string value)
        {
            var mac         = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
            var cryptoKey   = mac.CreateKey(keyMaterial.AsBuffer());
            var strMaterial = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);

            return(CryptographicEngine.Sign(cryptoKey, strMaterial).ToArray());
        }
Esempio n. 29
0
        /// <summary>
        /// This method uses the Windows Runtime APIs to provide the crypto algorithm.
        /// HMAC computes a Hashed Message Authentication Code with the
        /// crypto hash algorithm as a parameter.
        /// </summary>
        /// <param name="crypto">The crypto algorithm.</param>
        /// <param name="keyBytes">The bytes to use for the HMAC key.</param>
        /// <param name="text">The message or text to be authenticated.</param>
        /// <returns></returns>
        public static byte[] HmacSha(MacAlgorithmEnum crypto, byte[] keyBytes,
                                     byte[] text)
        {
            // Select crypto algorithm
            MacAlgorithmProvider macAlgorithmProvider = null;

            switch (crypto)
            {
            case MacAlgorithmEnum.HmacSha1:
                macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
                break;

            case MacAlgorithmEnum.HmacSha256:
                macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
                break;

            case MacAlgorithmEnum.HmacSha512:
                macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha512);
                break;
            }
            if (macAlgorithmProvider == null)
            {
                throw new InvalidOperationException("MacAlgorithmProvider failed to initialize.");
            }
            // Get buffer
            var keyBuffer = CryptographicBuffer.CreateFromByteArray(keyBytes);

            if (keyBuffer == null)
            {
                throw new InvalidOperationException("Invaild Key buffer.");
            }
            var key = macAlgorithmProvider.CreateKey(keyBuffer);

            if (key == null)
            {
                throw new InvalidOperationException("Invaild Key.");
            }

            // Get hash
            var dataBuffer = CryptographicBuffer.CreateFromByteArray(text);

            if (dataBuffer == null)
            {
                throw new InvalidOperationException("Invaild data buffer.");
            }

            // Sign hash
            var dataBufferSigned = CryptographicEngine.Sign(key, dataBuffer);

            if (dataBufferSigned == null)
            {
                throw new InvalidOperationException("Invaild signed data.");
            }

            byte[] hashBytes;
            CryptographicBuffer.CopyToByteArray(dataBufferSigned, out hashBytes);
            return(hashBytes);
        }
        public static string GenerateHash(string input, string key)
        {
            MacAlgorithmProvider mac     = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
            IBuffer          keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
            CryptographicKey cryptoKey   = mac.CreateKey(keyMaterial);
            IBuffer          hash        = CryptographicEngine.Sign(cryptoKey, CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8));

            return(CryptographicBuffer.EncodeToBase64String(hash));
        }