Exemplo n.º 1
0
        internal byte[] GetPasswordSeed(string siteName, int count)
        {
            byte[] myKeyScopeBytes             = Encoding.UTF8.GetBytes(MP_ScopeName);
            byte[] siteNameLengthBytes         = BinaryConverter.BytesForInt(siteName.Length);
            byte[] siteNameBytes               = Encoding.UTF8.GetBytes(siteName);
            byte[] countBytes                  = BinaryConverter.BytesForInt(count);
            byte[] concatenated                = myKeyScopeBytes.Concat(siteNameLengthBytes).Concat(siteNameBytes).Concat(countBytes).ToArray();
            MacAlgorithmProvider provider      = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            CryptographicHash    masterKeyHash = provider.CreateHash(masterKeyBytes.AsBuffer());

            masterKeyHash.Append(concatenated.AsBuffer());
            byte[] seed = masterKeyHash.GetValueAndReset().ToArray();
            return(seed);
        }
Exemplo n.º 2
0
        public static string Sign(byte[] key, string stringToSign)
        {
#if NETFX_CORE
            MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            CryptographicHash    hash     = provider.CreateHash(key.AsBuffer());
            hash.Append(CryptographicBuffer.ConvertStringToBinary(stringToSign, BinaryStringEncoding.Utf8));
            return(CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset()));
#else
            var hmac = new HMACSHA256();
            hmac.Key = key;
            byte[] sig = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
            return(Convert.ToBase64String(sig));
#endif
        }
Exemplo n.º 3
0
        private CryptographicHash CreateHmacCryptographicHash()
        {
            String algName = AlgorithmNames.SelectionBoxItem.ToString();

            // Create a HashAlgorithmProvider object.
            MacAlgorithmProvider Algorithm = MacAlgorithmProvider.OpenAlgorithm(algName);
            IBuffer vector = CryptographicBuffer.DecodeFromBase64String("uiwyeroiugfyqcajkds897945234==");

            HashingText.Text += "\n*** Sample Hash Algorithm: " + Algorithm.AlgorithmName + "\n";
            HashingText.Text += "    Initial vector:  uiwyeroiugfyqcajkds897945234==\n";

            IBuffer hmacKeyMaterial = CryptographicBuffer.GenerateRandom(Algorithm.MacLength);

            // Compute the hash in one call.
            CryptographicHash hash = Algorithm.CreateHash(hmacKeyMaterial);

            hash.Append(vector);
            digest = hash.GetValueAndReset();

            HashingText.Text += "    Hash:  " + CryptographicBuffer.EncodeToHexString(digest) + "\n";

            return(Algorithm.CreateHash(hmacKeyMaterial));
        }
        public static string ComputeHmac256(byte[] key, string message)
        {
#if NETFX_CORE
            MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            CryptographicHash    hash     = provider.CreateHash(key.AsBuffer());
            hash.Append(CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8));
            return(CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset()));
#else
            using (HashAlgorithm hashAlgorithm = new HMACSHA256(key))
            {
                byte[] messageBuffer = Encoding.UTF8.GetBytes(message);
                return(Convert.ToBase64String(hashAlgorithm.ComputeHash(messageBuffer)));
            }
#endif
        }
Exemplo n.º 5
0
        // Generate an authorization header.

        public Windows.Web.Http.Headers.HttpCredentialsHeaderValue AuthorizationHeader(string method, DateTime now, HttpRequestMessage request, long contentLength, string ifMatch = "", string md5 = "")
        {
            string MessageSignature;

            if (IsTableStorage)
            {
                MessageSignature = String.Format("{0}\n\n{1}\n{2}\n{3}",
                                                 method,
                                                 "application/atom+xml",
                                                 now.ToString("R", System.Globalization.CultureInfo.InvariantCulture),
                                                 GetCanonicalizedResource(request.RequestUri, StorageAccount)
                                                 );
            }
            else
            {
                MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
                                                 method,
                                                 (method == "GET" || method == "HEAD") ? String.Empty : contentLength.ToString(),
                                                 ifMatch,
                                                 GetCanonicalizedHeaders(request),
                                                 GetCanonicalizedResource(request.RequestUri, StorageAccount),
                                                 md5
                                                 );
            }

            //Debug.WriteLine(MessageSignature);
            var key = CryptographicBuffer.DecodeFromBase64String(StorageKey);
            var msg = CryptographicBuffer.ConvertStringToBinary(MessageSignature, BinaryStringEncoding.Utf8);

            MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            //CryptographicKey cryptKey = objMacProv.CreateKey(key);
            //var buff = CryptographicEngine.Sign(cryptKey, msg);
            CryptographicHash hash = objMacProv.CreateHash(key);

            hash.Append(msg);

            var authorizationHeader = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("SharedKey", StorageAccount + ":" + CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset()));

            //Debug.WriteLine(authorizationHeader.ToString());
            return(authorizationHeader);
        }
Exemplo n.º 6
0
        public void DeriveEncryptionKey(byte[] passphrase, byte[] salt, ref byte[] encryptionKey)
        {
            var tokenData = SettingsHelper.LoadSetting <TFTokenData>(Consts.SETTINGS_TOKEN_SECRET_KEY);

            IBuffer passphraseBuffer = CryptographicBuffer.CreateFromByteArray(passphrase);
            IBuffer hmacKeyBuffer    = CryptographicBuffer.CreateFromByteArray(tokenData.SecretKey);

            MacAlgorithmProvider hmacProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
            CryptographicHash    saltHMAC     = hmacProvider.CreateHash(hmacKeyBuffer);
            IBuffer saltBuffer = saltHMAC.GetValueAndReset();

            KeyDerivationAlgorithmProvider pbkdf2Provider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            KeyDerivationParameters        pbkdf2Parms    = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, (uint)NumberOfOterations);
            CryptographicKey pbkdf2Key = pbkdf2Provider.CreateKey(passphraseBuffer);

            IBuffer derivedKeyBuffer = CryptographicEngine.DeriveKeyMaterial(pbkdf2Key, pbkdf2Parms, (uint)encryptionKey.Length);

            byte[] derivedKeyBytes = derivedKeyBuffer.ToArray();
            Array.Copy(derivedKeyBytes, encryptionKey, encryptionKey.Length);
            Array.Clear(derivedKeyBytes, 0, derivedKeyBytes.Length);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Authenticates at the Event Hub and refreshes the authentication token
        /// </summary>
        public void Authenticate()
        {
            TimeSpan fromEpochStart = DateTime.UtcNow - new DateTime(1970, 1, 1);
            string   expiry         = Convert.ToString((int)fromEpochStart.TotalSeconds + 86400); // 86400s = 24h
            string   stringToSign   = WebUtility.UrlEncode(eventHubBaseAddress) + "\n" + expiry;

            // Create hash
            MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            var hash = provider.CreateHash(CryptographicBuffer.ConvertStringToBinary(sasKeyValue, BinaryStringEncoding.Utf8));

            hash.Append(CryptographicBuffer.ConvertStringToBinary(stringToSign, BinaryStringEncoding.Utf8));

            // Generate token
            var    signature = CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset());
            string token     = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
                                             WebUtility.UrlEncode(eventHubBaseAddress), WebUtility.UrlEncode(signature), expiry, sasKeyName);

            // Set HTTP Access token
            httpClient.DefaultRequestHeaders.Clear();
            httpClient.DefaultRequestHeaders.ExpectContinue = false;
            httpClient.DefaultRequestHeaders.Authorization  = AuthenticationHeaderValue.Parse(token);
        }
Exemplo n.º 8
0
        public static byte[] HmacData(TpmAlgId hashAlgId, byte[] key, byte[] dataToHash)
        {
            string algName;

            switch (hashAlgId)
            {
            case TpmAlgId.Sha1:
                algName = MacAlgorithmNames.HmacSha1;
                break;

            case TpmAlgId.Sha256:
                algName = MacAlgorithmNames.HmacSha256;
                break;

            case TpmAlgId.Sha384:
                algName = MacAlgorithmNames.HmacSha384;
                break;

            case TpmAlgId.Sha512:
                algName = MacAlgorithmNames.HmacSha512;
                break;

            default:
                Globs.Throw <ArgumentException>("HmacData(): Unsupported hash algorithm " + hashAlgId);
                return(null);
            }
            MacAlgorithmProvider algProvider = MacAlgorithmProvider.OpenAlgorithm(algName);
            CryptographicHash    hash        = algProvider.CreateHash(CryptographicBuffer.CreateFromByteArray(key));

            hash.Append(CryptographicBuffer.CreateFromByteArray(dataToHash));
            IBuffer hmacBuffer = hash.GetValueAndReset();

            byte[] hmac;
            CryptographicBuffer.CopyToByteArray(hmacBuffer, out hmac);
            return(hmac);
        }
Exemplo n.º 9
0
        private static String CreateSas(IBuffer accountKey, String version,
                                        String resourceType, String canonicalResourceName,
                                        String signatureIdentifier, UInt32 permissions, DateTimeOffset?startTime, DateTimeOffset?expiryTime,
                                        String tableName         = null,
                                        String startPartitionKey = null, String startRowKey = null,
                                        String endPartitionKey   = null, String endRowKey   = null)
        {
            String signature;

#if true
            MacAlgorithmProvider mac  = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            CryptographicHash    hash = mac.CreateHash(accountKey);
            // String to sign: http://msdn.microsoft.com/en-us/library/azure/dn140255.aspx
            StringBuilder stringToSign = new StringBuilder();
            stringToSign.Append(ToPermissionString(permissions))
            .Append("\n").Append(GetDateTimeOrEmpty(startTime))
            .Append("\n").Append(GetDateTimeOrEmpty(expiryTime))
            .Append("\n").Append(canonicalResourceName)
            .Append("\n").Append(signatureIdentifier)
            .Append("\n").Append(version);
            if (version != "2012-02-12")
            {
                String CacheControl       = String.Empty; // rscc
                String ContentDisposition = String.Empty; // rscd
                String ContentEncoding    = String.Empty; // rsce
                String ContentLanguage    = String.Empty; // rscl
                String ContentType        = String.Empty; // rsct
                stringToSign.Append("\n").Append(CacheControl)
                .Append("\n").Append(ContentDisposition)
                .Append("\n").Append(ContentEncoding)
                .Append("\n").Append(ContentLanguage)
                .Append("\n").Append(ContentType);
            }
            if (tableName != null)
            {
                stringToSign.Append("\n").Append(startPartitionKey)
                .Append("\n").Append(startRowKey)
                .Append("\n").Append(endPartitionKey)
                .Append("\n").Append(endRowKey);
            }
            hash.Append(stringToSign.ToString().Encode().AsBuffer());
            signature = CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset());
#else
            using (HashAlgorithm hashAlgorithm = new HMACSHA256(accountKey)) {
                String stringToSign = String.Format(CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n{5}",
                                                    permissions, GetDateTimeOrEmpty(startTime), GetDateTimeOrEmpty(expiryTime),
                                                    canonicalResourceName, signatureIdentifier, version);
                if (tableName != null)
                {
                    stringToSign = String.Format(CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}",
                                                 stringToSign, startPartitionKey, startRowKey, endPartitionKey, endRowKey);
                }
                signature = Convert.ToBase64String(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
            }
#endif
            // NOTE: The order of query parameters is important
            return(new StringBuilder()
                   .Add("sv", version)
                   .Add("st", startTime == null ? null : GetDateTimeOrEmpty(startTime))
                   .Add("se", expiryTime == null ? null : GetDateTimeOrEmpty(expiryTime))
                   .Add("sr", resourceType)
                   .Add("tn", tableName)
                   .Add("sp", ToPermissionString(permissions))
                   .Add("spk", startPartitionKey).Add("srk", startRowKey)
                   .Add("epk", endPartitionKey).Add("erk", endRowKey)
                   .Add("si", signatureIdentifier)
                   .Add("sk", null /*accountKeyName*/)
                   .Add("sig", signature).ToString());
        }