Пример #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); }
        }
Пример #2
0
        public void DoFailuresWithWmiEnabled()
        {
            int numberOfEvents = 50;

            using (WmiEventWatcher eventListener = new WmiEventWatcher(numberOfEvents))
            {
                HashAlgorithmProvider          hashProvider    = new HashAlgorithmProvider(typeof(SHA1Managed), false);
                InstrumentationAttacherFactory attacherFactory = new InstrumentationAttacherFactory();
                IInstrumentationAttacher       binder          = attacherFactory.CreateBinder(hashProvider.GetInstrumentationEventProvider(), new object[] { "foo", true, true, true }, new ConfigurationReflectionCache());
                binder.BindInstrumentation();

                for (int i = 0; i < numberOfEvents; i++)
                {
                    try
                    {
                        hashProvider.CreateHash(null);
                    }
                    catch (Exception)
                    {
                    }
                }

                eventListener.WaitForEvents();

                Assert.AreEqual(numberOfEvents, eventListener.EventsReceived.Count);
            }
        }
Пример #3
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);
            }
        }
Пример #4
0
        /// <summary>
        /// Проверка лицензии
        /// </summary>
        /// <returns></returns>
        public bool IsLicenseValid()
        {
            bool res = false;

            try
            {
                IBuffer SignatureBuffer       = Signature.AsBuffer();
                IBuffer ServerPublicKeyBuffer = Convert.FromBase64String(GlobalVars.ServerPublicKey).AsBuffer();
                AsymmetricKeyAlgorithmProvider RSAVerifyProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha512);
                CryptographicKey ServerPublicKey             = RSAVerifyProv.ImportPublicKey(ServerPublicKeyBuffer, CryptographicPublicKeyBlobType.Capi1PublicKey);
                byte[]           tmpuseridbytes   = Encoding.UTF8.GetBytes(UserID);
                byte[]           tmpregdtbytes    = BitConverter.GetBytes(RegistrationDateTime);
                byte[]           tmpregdtstrbytes = Encoding.UTF8.GetBytes(RegistrationDateTimeStr);
                byte[]           tmpdevcountbytes = BitConverter.GetBytes(DeviceCountLimit);
                byte[]           tmpendpointbytes = Encoding.UTF8.GetBytes(ServerEndPoint);
                byte[]           tmpbytes         = new byte[tmpuseridbytes.Length + tmpregdtbytes.Length + tmpregdtstrbytes.Length + tmpdevcountbytes.Length + tmpendpointbytes.Length];
                Array.Copy(tmpuseridbytes, tmpbytes, tmpuseridbytes.Length);
                Array.Copy(tmpregdtbytes, 0, tmpbytes, tmpuseridbytes.Length, tmpregdtbytes.Length);
                Array.Copy(tmpregdtstrbytes, 0, tmpbytes, tmpuseridbytes.Length + tmpregdtbytes.Length, tmpregdtstrbytes.Length);
                Array.Copy(tmpdevcountbytes, 0, tmpbytes, tmpuseridbytes.Length + tmpregdtbytes.Length + tmpregdtstrbytes.Length, tmpdevcountbytes.Length);
                Array.Copy(tmpendpointbytes, 0, tmpbytes, tmpuseridbytes.Length + tmpregdtbytes.Length + tmpregdtstrbytes.Length + tmpdevcountbytes.Length, tmpendpointbytes.Length);
                string strAlgName = HashAlgorithmNames.Sha512;
                HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);
                CryptographicHash     objHash    = objAlgProv.CreateHash();
                objHash.Append(tmpbytes.AsBuffer());
                IBuffer tmpbyteshash = objHash.GetValueAndReset();
                res = CryptographicEngine.VerifySignatureWithHashInput(ServerPublicKey, tmpbyteshash, SignatureBuffer);
            }
            catch /*(Exception ex)*/
            {
            }
            return(res);
        }
Пример #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());
        }
        public static string AES_Decrypt(String EncryptedText, String DecryptionKey)
        {
            string decrypted = "";
            SymmetricKeyAlgorithmProvider SAP      = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            HashAlgorithmProvider         HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash             Hash_AES = HAP.CreateHash();

            try
            {
                //byte[] KeyBytes = System.Text.Encoding.UTF8.GetBytes(password);
                byte[] KeyBytes16 = new byte[16];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(DecryptionKey)));
                byte[] KeyBytes;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out KeyBytes);
                for (int i = 0; i < KeyBytes.Length; i++)
                {
                    KeyBytes16[i] = KeyBytes[i];
                }

                CryptographicKey key = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(KeyBytes16));


                IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(EncryptedText);
                byte[]  Decrypted;

                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(key, Buffer, null), out Decrypted);
                decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
                return(decrypted);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return("Error in Decryption:With Aes ");
            }
        }
Пример #7
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);
            }
        }
Пример #8
0
        public int dbEncrypt(String partition, int size, String data, out String dataOut)
        {
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            try{
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(partition)));
                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));

                Windows.Storage.Streams.IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(data);
                byte[] Decrypted;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
                dataOut = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
            }
            catch (Exception ex)
            {
                dataOut = "";
                return(getErrorCode() == 0 ? 1 : 0);
            }

            return(getErrorCode() == 0 ? 1 : 0);
        }
Пример #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) { };
        }
Пример #10
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);
            }
        }
Пример #11
0
        private static string GetHash(Stream input, string algName)
        {
            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(algName);

            CryptographicHash cryptoHash = objAlgProv.CreateHash();

            using ( input )
            {
                byte[] b = new byte[2048];
                int    r;
                while ((r = input.Read(b, 0, b.Length)) > 0)
                {
                    cryptoHash.Append(b.AsBuffer(0, r));
                }
            }

            // Hash the message.
            IBuffer buffHash = cryptoHash.GetValueAndReset();

            // Convert the hash to a string (for display).
            string strHashBase64 = CryptographicBuffer.EncodeToHexString(buffHash);

            // Return the encoded string
            return(strHashBase64);
        }
Пример #12
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
        }
Пример #13
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;
            //}
        }
Пример #14
0
        public async Task <string> GetHashForFile(ListedItem fileItem, string nameOfAlg)
        {
            HashAlgorithmProvider algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(nameOfAlg);
            var itemFromPath = await StorageFile.GetFileFromPathAsync(fileItem.ItemPath);

            var stream = await itemFromPath.OpenStreamForReadAsync();

            var  inputStream = stream.AsInputStream();
            uint capacity    = 100000000;

            Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity);
            var hash = algorithmProvider.CreateHash();

            while (true)
            {
                await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None);

                if (buffer.Length > 0)
                {
                    hash.Append(buffer);
                }
                else
                {
                    break;
                }
            }
            inputStream.Dispose();
            stream.Dispose();
            return(CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset()).ToLower());
        }
		public void DoFailuresWithWmiEnabled()
		{
			int numberOfEvents = 50;
			using (WmiEventWatcher eventListener = new WmiEventWatcher(numberOfEvents))
			{
				HashAlgorithmProvider hashProvider = new HashAlgorithmProvider(typeof(SHA1Managed), false);
				InstrumentationAttacherFactory attacherFactory = new InstrumentationAttacherFactory();
				IInstrumentationAttacher binder = attacherFactory.CreateBinder(hashProvider.GetInstrumentationEventProvider(), new object[] { "foo", true, true, true }, new ConfigurationReflectionCache());
				binder.BindInstrumentation();

				for (int i = 0; i < numberOfEvents; i++)
				{
					try
					{
						hashProvider.CreateHash(null);
					}
					catch (Exception)
					{
					}
				}

				eventListener.WaitForEvents();

				Assert.AreEqual(numberOfEvents, eventListener.EventsReceived.Count);
			}
		}
Пример #16
0
        public static string AES_Decrypt(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(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.DecodeFromBase64String(input);
                byte[]  Decrypted;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(aes, Buffer, null), out Decrypted);
                decrypted = Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);

                return(decrypted);
            }
            catch
            {
                return(null);
            }
        }
Пример #17
0
        public static void ce()
        {
            //可以选择MD5 Sha1 Sha256 Sha384 Sha512
            string strAlgName = HashAlgorithmNames.Md5;

            // 创建一个 HashAlgorithmProvider 对象
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);

            // 创建一个可重用的CryptographicHash对象
            CryptographicHash objHash = objAlgProv.CreateHash();


            string  strMsg1  = "这是一段待加密的字符串";
            IBuffer buffMsg1 = CryptographicBuffer.ConvertStringToBinary(strMsg1, BinaryStringEncoding.Utf16BE);

            objHash.Append(buffMsg1);
            IBuffer buffHash1 = objHash.GetValueAndReset();
            string  strHash1  = CryptographicBuffer.EncodeToBase64String(buffHash1);


            string  strMsg2  = "和前面一串不相同的字符串";
            IBuffer buffMsg2 = CryptographicBuffer.ConvertStringToBinary(strMsg2, BinaryStringEncoding.Utf16BE);

            objHash.Append(buffMsg2);
            IBuffer buffHash2 = objHash.GetValueAndReset();
            string  strHash2  = CryptographicBuffer.EncodeToBase64String(buffHash2);


            string  strMsg3  = "每个都不相同";
            IBuffer buffMsg3 = CryptographicBuffer.ConvertStringToBinary(strMsg3, BinaryStringEncoding.Utf16BE);

            objHash.Append(buffMsg3);
            IBuffer buffHash3 = objHash.GetValueAndReset();
            string  strHash3  = CryptographicBuffer.EncodeToBase64String(buffHash3);
        }
Пример #18
0
        public static string GetHashedValue(string plainText)
        {
            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm("SHA1");

            // Create a CryptographicHash object. This object can be reused to continually
            // hash new messages.
            CryptographicHash objHash = objAlgProv.CreateHash();

            // Hash message 1.
            IBuffer buffMsg1 = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8);

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

            byte[] bytes = null; //new byte[buffHash1.Length];
            CryptographicBuffer.CopyToByteArray(buffHash1, out bytes);

            var data = new StringBuilder((int)bytes.Length * 2);

            for (var i = 0; i < bytes.Length; ++i)
            {
                data.Append(bytes[i].ToString("x2"));
            }

            return(data.ToString());
            //return CryptographicBuffer.EncodeToBase64String(buffHash1);
        }
Пример #19
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));
        }
Пример #20
0
        private async Task <string> GetHashForFileAsync(ListedItem fileItem, string nameOfAlg, CancellationToken token, ProgressBar progress, IShellPage associatedInstance)
        {
            HashAlgorithmProvider algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(nameOfAlg);
            StorageFile           file = await StorageItemHelpers.ToStorageItem <StorageFile>((fileItem as ShortcutItem)?.TargetPath ?? fileItem.ItemPath, associatedInstance);

            if (file == null)
            {
                return("");
            }

            Stream stream = await FilesystemTasks.Wrap(() => file.OpenStreamForReadAsync());

            if (stream == null)
            {
                return("");
            }

            var  inputStream = stream.AsInputStream();
            var  str         = inputStream.AsStreamForRead();
            var  cap         = (long)(0.5 * str.Length) / 100;
            uint capacity;

            if (cap >= uint.MaxValue)
            {
                capacity = uint.MaxValue;
            }
            else
            {
                capacity = Convert.ToUInt32(cap);
            }

            Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity);
            var hash = algorithmProvider.CreateHash();

            while (!token.IsCancellationRequested)
            {
                await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None);

                if (buffer.Length > 0)
                {
                    hash.Append(buffer);
                }
                else
                {
                    break;
                }
                if (progress != null)
                {
                    progress.Value = (double)str.Position / str.Length * 100;
                }
            }
            inputStream.Dispose();
            stream.Dispose();
            if (token.IsCancellationRequested)
            {
                return("");
            }
            return(CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset()).ToLower());
        }
Пример #21
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 void HashFailureThrowsWithInstrumentationEnabled()
        {
            HashAlgorithmProvider           hashProvider = new HashAlgorithmProvider(typeof(SHA1Managed), false);
            ReflectionInstrumentationBinder binder       = new ReflectionInstrumentationBinder();

            binder.Bind(hashProvider.GetInstrumentationEventProvider(), new HashAlgorithmInstrumentationListener("foo", true, true, true));

            hashProvider.CreateHash(null);
        }
Пример #23
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));
        }
 public void HashHMACSHA1FailsUsingHashAlgorithmProvider()
 {
     HashAlgorithmProviderData keyData = new HashAlgorithmProviderData();
     keyData.AlgorithmType = typeof(HMACSHA1).AssemblyQualifiedName;
     keyData.SaltEnabled = false;
     keyData.Name = "BadHMACSHA1";
     IHashProvider hashProvider = new HashAlgorithmProvider();
     hashProvider.Initialize(new TestCryptographyConfigurationView(keyData));
     hashProvider.CreateHash(plainText);
 }
        public void HashWithBadType()
        {
            HashAlgorithmProviderData data = new HashAlgorithmProviderData();

            data.AlgorithmType = "bad type";
            data.Name          = "bad";
            IHashProvider hashProvider = new HashAlgorithmProvider();

            hashProvider.Initialize(new TestCryptographyConfigurationView(data));
            hashProvider.CreateHash(plainText);
        }
Пример #26
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));
        }
Пример #27
0
        //私有化构造函数,禁止通过new创建实例
        private MD5()
        {
            // Create a string that contains the name of the hashing algorithm to use.
            String strAlgName = HashAlgorithmNames.Md5;

            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Create a CryptographicHash object. This object can be reused to continually
            // hash new messages.
            objHash = objAlgProv.CreateHash();
        }
Пример #28
0
        public static byte[] ComputeHash(byte[] data, string hashAlgorithmName)
        {
            //String algorithmName = HashAlgorithmNames.Sha256;
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(hashAlgorithmName);
            CryptographicHash     hasher     = objAlgProv.CreateHash();

            // Hash data
            hasher.Append(data.AsBuffer());
            IBuffer hashBuffer = hasher.GetValueAndReset();

            return(hashBuffer.ToArray());
        }
Пример #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());
        }
        public void HashHMACSHA1FailsUsingHashAlgorithmProvider()
        {
            HashAlgorithmProviderData keyData = new HashAlgorithmProviderData();

            keyData.AlgorithmType = typeof(HMACSHA1).AssemblyQualifiedName;
            keyData.SaltEnabled   = false;
            keyData.Name          = "BadHMACSHA1";
            IHashProvider hashProvider = new HashAlgorithmProvider();

            hashProvider.Initialize(new TestCryptographyConfigurationView(keyData));
            hashProvider.CreateHash(plainText);
        }
Пример #31
0
        /// <summary>
        /// Generates the HMAC key to use for a specific block.
        /// </summary>
        /// <param name="i">The block index.</param>
        /// <returns>The 512-bit key to use for a block at index <paramref name="i"/>.</returns>
        public IBuffer GetKeyForBlock(ulong i)
        {
            byte[] buffer = new byte[BaseKeySize + 8];
            ByteHelper.GetLittleEndianBytes(i, buffer);
            this.key.CopyTo(0, buffer, 8, BaseKeySize);

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

            hash.Append(buffer.AsBuffer());
            return(hash.GetValueAndReset());
        }
Пример #32
0
        public string HashPW(string pw)
        {
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512);
            CryptographicHash     objHash    = objAlgProv.CreateHash();

            IBuffer buffpw = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf16BE);

            objHash.Append(buffpw);
            IBuffer buffHash = objHash.GetValueAndReset();

            return(CryptographicBuffer.EncodeToBase64String(buffpw));
        }
 public void HashWithBadType()
 {
     HashAlgorithmProviderData data = new HashAlgorithmProviderData();
     data.AlgorithmType = "bad type";
     data.Name = "bad";
     IHashProvider hashProvider = new HashAlgorithmProvider();
     hashProvider.Initialize(new TestCryptographyConfigurationView(data));
     hashProvider.CreateHash(plainText);
 }
        public void HashFailureThrowsWithInstrumentationEnabled()
        {
            HashAlgorithmProvider hashProvider = new HashAlgorithmProvider(typeof(SHA1Managed), false, new NullHashAlgorithmInstrumentationProvider());

            hashProvider.CreateHash(null);
        }
 public void HashWithBadTypeThrows()
 {
     HashAlgorithmProvider hashProvider = new HashAlgorithmProvider(typeof(Exception), false, new NullHashAlgorithmInstrumentationProvider());
     hashProvider.CreateHash(plainText);
 }