Esempio n. 1
0
        public static async Task <string> track_love(MusicProperties id3)
        {
            try
            {
                string scrb_track_sig = "api_key" + Globalv.lfm_api_key + "artist" + id3.Artist + "methodtrack.love" + "sk" + Globalv.session_key + "track" + id3.Title + "0e6e780c3cfa3faedf0c58d5aa6de92f";

                //UTF8Encoding utf8e = new System.Text.UTF8Encoding();
                //scrb_track_sig = utf8e.GetString(utf8e.GetBytes(scrb_track_sig));

                HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm("MD5");
                CryptographicHash     objHash    = objAlgProv.CreateHash();
                IBuffer buffSig = CryptographicBuffer.ConvertStringToBinary(scrb_track_sig, BinaryStringEncoding.Utf8);
                objHash.Append(buffSig);
                IBuffer buffSighash = objHash.GetValueAndReset();

                scrb_track_sig = CryptographicBuffer.EncodeToHexString(buffSighash);

                HttpClient cli = new HttpClient();
                cli.DefaultRequestHeaders.ExpectContinue = false; //important
                string track_love = @"method=track.love&track=" + id3.Title + @"&artist=" + id3.Artist + @"&api_key=" + Globalv.lfm_api_key + @"&api_sig=" + scrb_track_sig + @"&sk=" + Globalv.session_key;

                cli.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                HttpContent tscr = new StringContent(track_love);

                tscr.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

                var loved_resp = await cli.PostAsync(new Uri("http://ws.audioscrobbler.com/2.0", UriKind.Absolute), tscr);

                return(await loved_resp.Content.ReadAsStringAsync());
            }
            catch (Exception) { return(null); }
        }
Esempio n. 2
0
        public static string AES_Ecrypt(string input, string pass)
        {
            GenerateIV();
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey AES;
            //Key
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            string encrypted = "";

            try
            {
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
                //pass->key
                byte[] temp;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 16, 16);
                //totally 32 bits,16 bits once,temp-> hash

                AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
                IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(input));
                encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, IV));
                //key,data,Initialization vector
                return(encrypted + "!" + CryptographicBuffer.EncodeToBase64String(IV));
                //line break
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Esempio n. 3
0
        public static string Decrypt(this string str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return("");
            }

            var key = StringWithAES.GetHardwareId().Remove(32);

            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            var hash = new byte[32];

            Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(key)));
            byte[] temp;
            CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

            Array.Copy(temp, 0, hash, 0, 16);
            Array.Copy(temp, 0, hash, 15, 16);

            AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

            IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(str);

            byte[] Decrypted;
            CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
            return(System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length));
        }
        private string MakeSignature(string basestring)
        {
            // Encrypt with either SHA1 or SHA256, creating the Signature
            byte[] keyBytes  = Encoding.UTF8.GetBytes(this.oauth_consumer_secret + "&");
            byte[] dataBytes = Encoding.UTF8.GetBytes(basestring);

            MacAlgorithm      a         = oauth_signature_method == "HMAC-SHA1" ? MacAlgorithm.HmacSha1 : MacAlgorithm.HmacSha256;
            var               algorithm = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(a);
            CryptographicHash hasher    = algorithm.CreateHash(keyBytes);

            hasher.Append(dataBytes);
            byte[] mac      = hasher.GetValueAndReset();
            string hmacsha1 = BitConverter.ToString(mac).Replace("-", "").ToLower();

            byte[] resultantArray = new byte[hmacsha1.Length / 2];

            for (int i = 0; i < resultantArray.Length; i++)
            {
                resultantArray[i] = Convert.ToByte(hmacsha1.Substring(i * 2, 2), 16);
            }

            string base64 = Convert.ToBase64String(resultantArray);
            string result = WebUtility.UrlEncode(base64);

            return(result);
        }
Esempio n. 5
0
        /// <summary>
        /// Derives the base key used by <see cref="HmacBlockHandler"/> given
        /// a database's master seed and the user's composite key.
        ///
        /// The derived key is a SHA-512 hash of the result of concatenating
        /// these values together, with the byte 0x1 appended at the end.
        /// </summary>
        /// <param name="compositeKey">The user's composite key.</param>
        /// <param name="masterSeed">The database's master seed.</param>
        /// <returns>A buffer to use for an HMAC block key.</returns>
        public static IBuffer DeriveHmacKey(IBuffer compositeKey, IBuffer masterSeed)
        {
            if (compositeKey == null)
            {
                throw new ArgumentNullException(nameof(compositeKey));
            }

            if (masterSeed == null)
            {
                throw new ArgumentNullException(nameof(masterSeed));
            }

            if (compositeKey.Length != 32)
            {
                throw new ArgumentException("Composite key should be 32 bytes", nameof(compositeKey));
            }

            if (masterSeed.Length != 32)
            {
                throw new ArgumentException("Master seed should be 32 bytes", nameof(masterSeed));
            }

            byte[] buffer = new byte[compositeKey.Length + masterSeed.Length + 1];

            masterSeed.CopyTo(buffer);
            compositeKey.CopyTo(0, buffer, (int)masterSeed.Length, (int)compositeKey.Length);
            buffer[buffer.Length - 1] = 1;

            HashAlgorithmProvider sha512 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512);
            CryptographicHash     hash   = sha512.CreateHash();

            hash.Append(buffer.AsBuffer());
            return(hash.GetValueAndReset());
        }
Esempio n. 6
0
        /// <summary>
        /// SignRequest
        /// </summary>
        /// <param name="request"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public string SignRequest(System.Net.HttpWebRequest request, byte[] body)
        {
            Uri u = request.RequestUri;

            var algorithm            = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha1);
            CryptographicHash hasher = algorithm.CreateHash(secretKey);

            hasher.Append(body);
            byte[] mac       = hasher.GetValueAndReset();
            string macBase64 = Convert.ToBase64String(mac);

            string pathAndQuery = request.RequestUri.PathAndQuery;

            byte[] pathAndQueryBytes = Config.Encoding.GetBytes(pathAndQuery);
            using (MemoryStream buffer = new MemoryStream())
            {
                buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length);
                buffer.WriteByte((byte)'\n');
                if (body.Length > 0)
                {
                    buffer.Write(body, 0, body.Length);
                }
                hasher.Dispose();
                return(this.accessKey + ":" + macBase64);
            }
        }
Esempio n. 7
0
        public static byte[] AES_Decrypt(byte[] input, byte[] pass)
        {
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            //string decrypted = "";
            //try
            //{
            byte[] hash = new byte[32];
            Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(pass));
            byte[] temp;
            CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

            Array.Copy(temp, 0, hash, 0, 16);    //key1
            Array.Copy(temp, 0, hash, 15, 16);   //key2

            AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
            //IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
            IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(input);

            byte[] Decrypted;
            CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
            //decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);

            return(Decrypted);
            //}
            //catch (Exception ex)
            //{
            //    return null;
            //}
        }
Esempio n. 8
0
        public static string Encrypt(string data, string publicKey)
        {
            //byte[] publicKeyBytes = Convert.FromBase64String(publicKey);

            byte[]            keyBytes  = Encoding.UTF8.GetBytes(publicKey);
            byte[]            dataBytes = Encoding.UTF8.GetBytes(data);
            var               algorithm = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha1);
            CryptographicHash hasher    = algorithm.CreateHash(keyBytes);

            hasher.Append(dataBytes);
            byte[] mac = hasher.GetValueAndReset();

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < mac.Length; i++)
            {
                sBuilder.Append(mac[i].ToString("X2"));
            }
            return(sBuilder.ToString().ToLower());

            //You can then easily import the key parameters into RSACryptoServiceProvider:
            //RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            //rsa.ImportParameters(rsaParameters);

            ////Finally, do your encryption:
            //byte[] dataToEncrypt = Encoding.UTF8.GetBytes(data);
            //// Sign data with Pkcs1
            //byte[] encryptedData = rsa.Encrypt(dataToEncrypt, false);
            //// Convert Bytes to Hash
            //var hash = Convert.ToBase64String(encryptedData);

            //return hash;
        }
Esempio n. 9
0
        public static async void track_updateNowPlaying(MusicProperties id3)
        {
            //try
            //{
            string updtrack_sig = "album" + id3.Album + "api_key" + Globalv.lfm_api_key + "artist" + id3.Artist + "methodtrack.updateNowPlaying" + "sk" + Globalv.session_key + "track" + id3.Title + "0e6e780c3cfa3faedf0c58d5aa6de92f";

            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm("MD5");
            CryptographicHash     objHash    = objAlgProv.CreateHash();
            IBuffer buffSig = CryptographicBuffer.ConvertStringToBinary(updtrack_sig, BinaryStringEncoding.Utf8);

            objHash.Append(buffSig);
            IBuffer buffSighash = objHash.GetValueAndReset();

            updtrack_sig = CryptographicBuffer.EncodeToHexString(buffSighash);

            HttpClient cli = new HttpClient();

            cli.DefaultRequestHeaders.ExpectContinue = false;     //important
            string track_updateNowPlaying = @"method=track.updateNowPlaying&track=" + id3.Title + @"&artist=" + id3.Artist + @"&album=" + id3.Album + @"&api_key=" + Globalv.lfm_api_key + @"&api_sig=" + updtrack_sig + @"&sk=" + Globalv.session_key;

            cli.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            HttpContent tunp = new StringContent(track_updateNowPlaying);

            tunp.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            var upd_now_playing = await cli.PostAsync(new Uri("http://ws.audioscrobbler.com/2.0", UriKind.Absolute), tunp);

            //}
            // catch (Exception) { };
        }
Esempio n. 10
0
        public static string AES_Encrypt(string input, string pass)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(null);
            }
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            string encrypted = string.Empty;

            try
            {
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
                byte[] temp;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);

                AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

                IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(input));
                encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));

                return(encrypted);
            }
            catch
            {
                throw new T360Exception(T360ErrorCodes.EncryptionFailed);
            }
        }
Esempio n. 11
0
        internal static string DecryptThisCipher(string input, string pass)
        {
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            string decrypted = "";

            try
            {
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(pass)));
                byte[] temp;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);

                AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

                IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
                byte[]  Decrypted;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
                decrypted = Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);

                return(decrypted);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(null);
            }
        }
Esempio n. 12
0
        public override byte[] GetHashAndReset()
        {
            IBuffer result  = hasher.GetValueAndReset();
            var     asBytes = WindowsRuntimeBufferExtensions.ToArray(result);

            return(asBytes);
        }
Esempio n. 13
0
        /// <summary>
        /// Parse and save the user related data sent by the Netsoul server.
        /// </summary>
        /// <param name="buffer">Data to parse received from the server</param>
        private async void ConnectionInfoParsing(string buffer)
        {
#if NETFX_CORE
            string[] parsing = buffer.Split(' ');
            this.ClientSocket = parsing[1];
            this.RandomMD5    = parsing[2];
            this.ClientIp     = parsing[3];
            this.ClientPort   = parsing[4];
            this.TimeStamp    = parsing[5];

            HashAlgorithmProvider md5    = HashAlgorithmProvider.OpenAlgorithm("MD5");
            CryptographicHash     Hasher = md5.CreateHash();
            IBuffer bufferMessage        = CryptographicBuffer.ConvertStringToBinary(this.RandomMD5
                                                                                     + "-" + this.ClientIp + "/" + this.ClientPort.ToString()
                                                                                     + this.UserPassword, BinaryStringEncoding.Utf8);
            Hasher.Append(bufferMessage);
            IBuffer NewMD5Buffer = Hasher.GetValueAndReset();
            this.NewMD5 = CryptographicBuffer.EncodeToHexString(NewMD5Buffer);
            this.NewMD5 = this.NewMD5.ToLower();

            this.StreamWriter.WriteString("auth_ag ext_user none none\n");
            this.Verif.Add(">>> " + "auth_ag ext_user none none\n");
            await this.StreamWriter.StoreAsync();
#endif
        }
        /// <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)
        {
            Scenario2Text.Text = "";
            String algName = AlgorithmNames.SelectionBoxItem.ToString();

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

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

            // Compute the hash in one call.
            IBuffer digest = Algorithm.HashData(vector);

            if (digest.Length != Algorithm.HashLength)
            {
                Scenario2Text.Text += "HashAlgorithmProvider failed to generate a hash of proper length!\n";
                return;
            }

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

            // Use a reusable hash object to hash the data by using multiple calls.
            CryptographicHash reusableHash = Algorithm.CreateHash();

            reusableHash.Append(vector);

            // Note that calling GetValue resets the data that has been appended to the
            // CryptographicHash object.
            IBuffer digest2 = reusableHash.GetValueAndReset();

            if (!CryptographicBuffer.Compare(digest, digest2))
            {
                Scenario2Text.Text += "CryptographicHash failed to generate the same hash data!\n";
                return;
            }

            reusableHash.Append(vector);
            digest2 = reusableHash.GetValueAndReset();

            if (!CryptographicBuffer.Compare(digest, digest2))
            {
                Scenario2Text.Text += "Reusable CryptographicHash failed to generate the same hash data!\n";
                return;
            }
        }
Esempio n. 15
0
        public static string GetMD5(string inputString)
        {
            CryptographicHash objHash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5).CreateHash();

            objHash.Append(CryptographicBuffer.ConvertStringToBinary(inputString, BinaryStringEncoding.Utf8));
            Windows.Storage.Streams.IBuffer buffHash1 = objHash.GetValueAndReset();
            return(CryptographicBuffer.EncodeToHexString(buffHash1));
        }
Esempio n. 16
0
        /// <summary>
        /// Asynchronously transforms the user's 32-byte key using ECB AES.
        ///
        /// Since Rijndael works on 16-byte blocks, the k is split in half and
        /// each half is encrypted separately the same number of times.
        /// </summary>
        /// <param name="rawKey">The key to transform.</param>
        /// <param name="token">Token used to cancel the transform task.</param>
        /// <returns>The transformed key.</returns>
        public async Task <IBuffer> TransformKeyAsync(IBuffer rawKey, CancellationToken token)
        {
            if (rawKey == null)
            {
                throw new ArgumentNullException(nameof(rawKey));
            }

            if (rawKey.Length != 32)
            {
                throw new ArgumentException("Key must be 32 bytes", nameof(rawKey));
            }

            // Split the k buffer in half
            byte[]  rawKeyBytes = rawKey.ToArray();
            IBuffer lowerBuffer = WindowsRuntimeBuffer.Create(rawKeyBytes, 0, 16, 16);
            IBuffer upperBuffer = WindowsRuntimeBuffer.Create(rawKeyBytes, 16, 16, 16);

            // Set up the encryption parameters
            var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb);
            CryptographicKey key = aes.CreateSymmetricKey(this.algoParams.Seed);
            IBuffer          iv  = null;

            // Run the encryption rounds in two threads (upper and lower)
            ConditionChecker checkForCancel = () => token.IsCancellationRequested;
            Task <bool>      lowerTask      = Task.Run(() =>
            {
                lowerBuffer = KeePassHelper.TransformKey(this.algoParams.Rounds, this.algoParams.Seed, iv, lowerBuffer, checkForCancel);
                return(!checkForCancel());
            }
                                                       );
            Task <bool> upperTask = Task.Run(() =>
            {
                upperBuffer = KeePassHelper.TransformKey(this.algoParams.Rounds, this.algoParams.Seed, iv, upperBuffer, checkForCancel);
                return(!checkForCancel());
            }
                                             );

            // Verify the work was completed successfully
            await Task.WhenAll(lowerTask, upperTask);

            if (!(lowerTask.Result && upperTask.Result))
            {
                return(null);
            }

            // Copy the units of work back into one buffer, hash it, and return.
            IBuffer transformedKey = (new byte[32]).AsBuffer();

            lowerBuffer.CopyTo(0, transformedKey, 0, 16);
            upperBuffer.CopyTo(0, transformedKey, 16, 16);

            var sha256             = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            CryptographicHash hash = sha256.CreateHash();

            hash.Append(transformedKey);

            return(hash.GetValueAndReset());
        }
Esempio n. 17
0
        private static string Md5(string str)
        {
            HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     cryptographic = hashAlgorithm.CreateHash();
            IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);

            cryptographic.Append(buffer);
            return(CryptographicBuffer.EncodeToHexString(cryptographic.GetValueAndReset()));
        }
        public async Task BlockBlobWriteStreamBasicTestAsync()
        {
            byte[] buffer = GetRandomBuffer(3 * 1024 * 1024);

            CryptographicHash hasher     = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            CloudBlobClient   blobClient = GenerateCloudBlobClient();

            blobClient.DefaultRequestOptions.ParallelOperationThreadCount = 2;
            string             name      = GetRandomContainerName();
            CloudBlobContainer container = blobClient.GetContainerReference(name);

            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                using (MemoryStream wholeBlob = new MemoryStream())
                {
                    BlobRequestOptions options = new BlobRequestOptions()
                    {
                        StoreBlobContentMD5 = true,
                    };
                    using (IOutputStream writeStream = await blob.OpenWriteAsync(null, options, null))
                    {
                        Stream blobStream = writeStream.AsStreamForWrite();

                        for (int i = 0; i < 3; i++)
                        {
                            await blobStream.WriteAsync(buffer, 0, buffer.Length);

                            await wholeBlob.WriteAsync(buffer, 0, buffer.Length);

                            Assert.AreEqual(wholeBlob.Position, blobStream.Position);
                            hasher.Append(buffer.AsBuffer());
                        }

                        await blobStream.FlushAsync();
                    }

                    string md5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
                    await blob.FetchAttributesAsync();

                    Assert.AreEqual(md5, blob.Properties.ContentMD5);

                    using (MemoryOutputStream downloadedBlob = new MemoryOutputStream())
                    {
                        await blob.DownloadToStreamAsync(downloadedBlob);

                        TestHelper.AssertStreamsAreEqual(wholeBlob, downloadedBlob.UnderlyingStream);
                    }
                }
            }
            finally
            {
                container.DeleteAsync().AsTask().Wait();
            }
        }
Esempio n. 19
0
        private void SetValue(T value)
        {
            lock (this)
            {
                _salt = CryptographicBuffer.GenerateRandom(CryptographicBuffer.GenerateRandomNumber( ) % 64 + 64);

                _hash.Append(_salt);

                _saltHashCode = _hash.GetValueAndReset( );

                _value = value;

                _hash.Append(ToIBuffer(value));
                _hash.Append(_salt);

                _hashCode = _hash.GetValueAndReset( );
            }
        }
Esempio n. 20
0
        private string MD5(string password)
        {
            string            encrtpt_password;
            CryptographicHash objHash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5).CreateHash();

            objHash.Append(CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf16BE));
            encrtpt_password = CryptographicBuffer.EncodeToBase64String(objHash.GetValueAndReset());
            return(encrtpt_password);
        }
Esempio n. 21
0
        public string Hash(string input)
        {
            IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8);

            cryptHash.Append(buffer);
            buffer = cryptHash.GetValueAndReset();

            return(CryptographicBuffer.EncodeToHexString(buffer));
        }
Esempio n. 22
0
        public static byte[] hash_hmacSha1(byte[] dataBytes, byte[] keyBytes)
        {
            var algorithm            = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha1);
            CryptographicHash hasher = algorithm.CreateHash(keyBytes);

            hasher.Append(dataBytes);
            byte[] mac = hasher.GetValueAndReset();
            return(mac);
        }
Esempio n. 23
0
		byte[] HashFinal ()
		{
			var buffer = hash.GetValueAndReset ();
			byte[] value;

			CryptographicBuffer.CopyToByteArray (buffer, out value);

			return value;
		}
Esempio n. 24
0
        public void CreateHash()
        {
            var algorithm            = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha1);
            CryptographicHash hasher = algorithm.CreateHash(this.keyMaterial);

            Assert.IsNotNull(hasher);
            hasher.Append(this.data);
            byte[] mac = hasher.GetValueAndReset();
            Assert.AreEqual(this.macBase64, Convert.ToBase64String(mac));
        }
Esempio n. 25
0
        public static string HashWith(this string input, HashAlgorithmProvider algorithm)
        {
            CryptographicHash objHash  = algorithm.CreateHash();
            IBuffer           buffMsg1 = CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf16BE);

            objHash.Append(buffMsg1);
            IBuffer buffHash1 = objHash.GetValueAndReset();

            return(CryptographicBuffer.EncodeToBase64String(buffHash1));
        }
Esempio n. 26
0
        private static string HashString(string input, CryptographicHash algorithm)
        {
            var bytes = Encoder.GetBytes(input);

            algorithm.Append(bytes);
            bytes = algorithm.GetValueAndReset();
            var hash = BitConverter.ToString(bytes);

            return(hash.Replace("-", string.Empty).ToLower());
        }
Esempio n. 27
0
        private static String sha256(String inputString)
        {
            HashAlgorithmProvider hap = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            CryptographicHash     ch  = hap.CreateHash();
            Encoding enc = Encoding.UTF8;

            ch.Append(enc.GetBytes(inputString).AsBuffer());
            IBuffer hash = ch.GetValueAndReset();

            return(CryptographicBuffer.EncodeToHexString(hash));
        }
Esempio n. 28
0
        private async Task CloudFileUploadFromStreamAsync(CloudFileShare share, int size, long?copyLength, AccessCondition accessCondition, OperationContext operationContext, int startOffset)
        {
            byte[] buffer = GetRandomBuffer(size);
#if ASPNET_K
            MD5    hasher = MD5.Create();
            string md5    = Convert.ToBase64String(hasher.ComputeHash(buffer, startOffset, copyLength.HasValue ? (int)copyLength : buffer.Length - startOffset));
#else
            CryptographicHash hasher = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            hasher.Append(buffer.AsBuffer(startOffset, copyLength.HasValue ? (int)copyLength.Value : buffer.Length - startOffset));
            string md5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
#endif

            CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
            file.StreamWriteSizeInBytes = 512;

            using (MemoryStream originalFileStream = new MemoryStream())
            {
                originalFileStream.Write(buffer, startOffset, buffer.Length - startOffset);

                using (MemoryStream sourceStream = new MemoryStream(buffer))
                {
                    sourceStream.Seek(startOffset, SeekOrigin.Begin);
                    FileRequestOptions options = new FileRequestOptions()
                    {
                        StoreFileContentMD5 = true,
                    };
                    if (copyLength.HasValue)
                    {
                        await file.UploadFromStreamAsync(sourceStream, copyLength.Value, accessCondition, options, operationContext);
                    }
                    else
                    {
                        await file.UploadFromStreamAsync(sourceStream, accessCondition, options, operationContext);
                    }
                }

                await file.FetchAttributesAsync();

                Assert.AreEqual(md5, file.Properties.ContentMD5);

                using (MemoryStream downloadedFileStream = new MemoryStream())
                {
                    await file.DownloadToStreamAsync(downloadedFileStream);

                    Assert.AreEqual(copyLength ?? originalFileStream.Length, downloadedFileStream.Length);
                    TestHelper.AssertStreamsAreEqualAtIndex(
                        originalFileStream,
                        downloadedFileStream,
                        0,
                        0,
                        copyLength.HasValue ? (int)copyLength : (int)originalFileStream.Length);
                }
            }
        }
Esempio n. 29
0
        public override string CalcMD5(string str)
        {
            HashAlgorithmProvider md5    = HashAlgorithmProvider.OpenAlgorithm("MD5");
            CryptographicHash     Hasher = md5.CreateHash();
            IBuffer bufferMessage        = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);

            Hasher.Append(bufferMessage);
            IBuffer NewMD5Buffer = Hasher.GetValueAndReset();
            var     newMD5       = CryptographicBuffer.EncodeToHexString(NewMD5Buffer);

            return(newMD5.ToLower());
        }
Esempio n. 30
0
        public string HmacSha256(string eventHubSASKey, string serviceBusUriExpiry)
        {
            var keyStrm   = CryptographicBuffer.ConvertStringToBinary(eventHubSASKey, BinaryStringEncoding.Utf8);
            var valueStrm = CryptographicBuffer.ConvertStringToBinary(serviceBusUriExpiry, BinaryStringEncoding.Utf8);

            MacAlgorithmProvider macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            CryptographicHash    cryptographicHash    = macAlgorithmProvider.CreateHash(keyStrm);

            cryptographicHash.Append(valueStrm);

            return(CryptographicBuffer.EncodeToBase64String(cryptographicHash.GetValueAndReset()));
        }