예제 #1
0
        private string GenerateSignature(Dictionary <string, string> parameters)
        {
            List <string> signatureParts = new List <string>();

            List <string> keyList = new List <string>(parameters.Keys);

            keyList.Sort();

            StringBuilder b = new StringBuilder();

            foreach (string s in keyList)
            {
                b.Append(s);
                b.Append(parameters[s]);
            }

            b.Append(API_SECRET);


            var     Md5      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            var     buffer   = CryptographicBuffer.ConvertStringToBinary(b.ToString(), BinaryStringEncoding.Utf8);
            IBuffer buffHash = Md5.HashData(buffer);


            return(CryptographicBuffer.EncodeToHexString(buffHash));
        }
예제 #2
0
        public static string Md5Encrypt(IBuffer data)
        {
            HashAlgorithmProvider md5 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            IBuffer hashedData        = md5.HashData(data);

            return(CryptographicBuffer.EncodeToHexString(hashedData));
        }
예제 #3
0
        private void setHeaders()
        {
            int    timeMilliseconds = (int)(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
            string cookieString     = "";

            if (CookieUri == null)
            {
                return;
            }

            foreach (Cookie cookie in cookieContainer.GetCookies(CookieUri))
            {
                cookieString = cookie.Value;
            }

            var    bufferString = CryptographicBuffer.ConvertStringToBinary(cookieString, BinaryStringEncoding.Utf8);
            var    bufferHash   = hashAlgorithmProvider.HashData(bufferString);
            string hexHash      = CryptographicBuffer.EncodeToHexString(bufferHash);
            string sapiSidHash  = String.Format("{0}_{1}", timeMilliseconds, hexHash);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SAPISIDHASH", sapiSidHash);
            client.DefaultRequestHeaders.TryAddWithoutValidation("x-goog-authuser", "0");
            client.DefaultRequestHeaders.TryAddWithoutValidation("x-origin", "https://hangouts.google.com");
            Debug.WriteLine("Setting headers...");
            foreach (var header in client.DefaultRequestHeaders)
            {
                Debug.WriteLine(String.Format("header: {0}: {1}", header.Key, header.Value.First()));
            }
        }
예제 #4
0
 //Get请求获取Stream类型数据
 private void Button_Click_2(object sender, RoutedEventArgs e)
 {
     HttpRequestAsync(async() => {
         string resourceAddress       = server + "extraData=2000";
         StringBuilder responseBody   = new StringBuilder();
         HttpRequestMessage request   = new HttpRequestMessage(HttpMethod.Get, new Uri(resourceAddress));
         HttpResponseMessage response = await httpClient.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead);
         using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
         {
             int read             = 0;
             byte[] responseBytes = new byte[1024];
             do
             {
                 read = await responseStream.ReadAsync(responseBytes, 0, responseBytes.Length);
                 responseBody.AppendFormat("Bytes read from stream :{0}", read);
                 responseBody.AppendLine();
                 //把byte[] 转化为Ibuffer类型
                 IBuffer responseBuffer = CryptographicBuffer.CreateFromByteArray(responseBytes);
                 responseBuffer.Length  = (uint)read;
                 //转化为Hex字符串
                 responseBody.AppendFormat(CryptographicBuffer.EncodeToHexString(responseBuffer));
                 responseBody.AppendLine();
             } while (read != 0);
         }
         return(responseBody.ToString());
     });
 }
예제 #5
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);
        }
예제 #6
0
        public string GenerateSha1Hash(string str)
        {
            var hashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
            var hash         = hashProvider.HashData(CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8));

            return(CryptographicBuffer.EncodeToHexString(hash));
        }
예제 #7
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());
        }
        private string getSHA256Hash(string tbh)
        {
            HashAlgorithmProvider hap = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            IBuffer hashed            = hap.HashData(CryptographicBuffer.ConvertStringToBinary(tbh, BinaryStringEncoding.Utf8));

            return(CryptographicBuffer.EncodeToHexString(hashed).ToUpper());
        }
        public async Task <DecodeResult> decode(byte[] bytes)
        {
            var stream      = (new MemoryStream(bytes)).AsRandomAccessStream();
            var dataReader  = new DataReader(stream);
            var bytesLoaded = await dataReader.LoadAsync((uint)stream.Size);

            stream.Seek(0);
            var result = await decode(stream, "");

            // Hash sum
            var iBuffer = dataReader.ReadBuffer(bytesLoaded);
            var hasher  = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5).CreateHash();

            hasher.Append(iBuffer);
            result.Md5 = CryptographicBuffer.EncodeToHexString(hasher.GetValueAndReset());
            hasher     = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1).CreateHash();
            hasher.Append(iBuffer);
            result.Sha1 = CryptographicBuffer.EncodeToHexString(hasher.GetValueAndReset());
            //hasher = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256).CreateHash();
            //hasher.Append(iBuffer);
            //result.Sha256 = CryptographicBuffer.EncodeToHexString(hasher.GetValueAndReset());
            //hasher = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha384).CreateHash();
            //hasher.Append(iBuffer);
            //result.Sha384 = CryptographicBuffer.EncodeToHexString(hasher.GetValueAndReset());
            //hasher = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512).CreateHash();
            //hasher.Append(iBuffer);
            //result.Sha512 = CryptographicBuffer.EncodeToHexString(hasher.GetValueAndReset());
            return(result);
        }
        async public void Decrypt()
        {
            CryptographicKey cryptographicKey = null;
            FileOpenPicker   fileOpenPicker   = new FileOpenPicker();

            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileOpenPicker.FileTypeFilter.Add("*");
            StorageFile file = await fileOpenPicker.PickSingleFileAsync();

            IBuffer bufferPrivateKey = await FileIO.ReadBufferAsync(file);

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

            try { cryptographicKey = provider.ImportKeyPair(bufferPrivateKey); }
            catch (Exception er) {
            }


            try { decryptedkey = CryptographicEngine.Decrypt(cryptographicKey, buffEncryptedSessionKey, null); }

            catch (Exception er)
            {
                ContentDialog contentDialog = new ContentDialog();
                contentDialog.Title           = "Wrong private key";
                contentDialog.Content         = "Try another private key";
                contentDialog.CloseButtonText = "Ok";

                await contentDialog.ShowAsync();
            }



            T8.Text = "Decrypted Key Base64: " + CryptographicBuffer.EncodeToBase64String(decryptedkey);
            T9.Text = "Decrypted Key BaseHex: " + CryptographicBuffer.EncodeToHexString(decryptedkey);
        }
예제 #11
0
        private static void Compute()
        {
            if (Debugger.IsAttached)
            {
                Debug.WriteLine(ApplicationData.Current.LocalSettings.Values["Result"]);
                Debug.Write(ApplicationData.Current.LocalSettings.Values["Time"]);
            }
            else
            {
                var hasher = HashAlgorithmProvider.OpenAlgorithm("SHA256");

                const String initialText = "wdmpOY6OosH6ltmhqxQAkt6yWRkiokDPgZCnsYHIgvNI9eClMEl7xTkxCW6uOlLU";
                var          input       = Encoding.ASCII.GetBytes(initialText).AsBuffer();

                var sw = Stopwatch.StartNew();

                for (var i = 0; i < 1000000; i++)
                {
                    input = hasher.HashData(input);
                    input = CryptographicBuffer.ConvertStringToBinary(CryptographicBuffer.EncodeToBase64String(input), BinaryStringEncoding.Utf8);
                }

                GC.Collect(2, GCCollectionMode.Forced, true);

                sw.Stop();

                ApplicationData.Current.LocalSettings.Values["Result"] = CryptographicBuffer.EncodeToHexString(input);
                ApplicationData.Current.LocalSettings.Values["Time"]   = sw.ElapsedMilliseconds;

                CoreApplication.Exit();
            }
        }
예제 #12
0
        public static string Sha256(string value)
        {
            var buffer   = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);
            var provider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);

            return(CryptographicBuffer.EncodeToHexString(provider.HashData(buffer)));
        }
예제 #13
0
파일: Netsoul.cs 프로젝트: Laxyus/Netsoul
        /// <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
        }
예제 #14
0
        private async Task <string> ComputeMD5(IStorageFile file)
        {
            string res = string.Empty;

            using (var streamReader = await file.OpenAsync(FileAccessMode.Read))
            {
                var alg     = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
                var algHash = alg.CreateHash();

                using (BinaryReader reader = new BinaryReader(streamReader.AsStream()))
                {
                    byte[] chunk;

                    chunk = reader.ReadBytes(CHUNK_SIZE);
                    while (chunk.Length > 0)
                    {
                        algHash.Append(CryptographicBuffer.CreateFromByteArray(chunk));
                        chunk = reader.ReadBytes(CHUNK_SIZE);
                    }
                }

                res = CryptographicBuffer.EncodeToHexString(algHash.GetValueAndReset());
                return(res);
            }
        }
예제 #15
0
        private async void ProtectStreamAsync_Click(object sender, RoutedEventArgs e)
        {
            string outputStr = "";

            Byte[] byteStream = { 1, 2, 3, 4, 5 };

            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0);
            var           writer       = new DataWriter(outputStream);

            writer.WriteBytes(byteStream);
            await writer.StoreAsync();

            IInputStream source = randomAccessStream.GetInputStreamAt(0);

            m_protectedStream = new InMemoryRandomAccessStream();
            IOutputStream destination = m_protectedStream.GetOutputStreamAt(0);

            await DataProtectionManager.ProtectStreamAsync(source, Scenario1.m_enterpriseId, destination);

            var reader = new DataReader(m_protectedStream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)m_protectedStream.Size);

            IBuffer protectedStreamBuffer = reader.ReadBuffer((uint)m_protectedStream.Size);

            outputStr += "\n Protected Stream buffer:" + CryptographicBuffer.EncodeToHexString(protectedStreamBuffer);

            rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
        }
예제 #16
0
파일: AESProvider.cs 프로젝트: Tsual/PSK
        public string Encrypt(string metaStr)
        {
            #region metaStr_buffer Add0
            byte[] metaStr_byte         = Encoding.UTF8.GetBytes(metaStr);
            int    metaStr_byte_count   = metaStr_byte.Count();
            int    metaStr_byte_f_count = (metaStr_byte_count / 16 + 1) * 16;
            byte[] metaStr_byte_f       = new byte[metaStr_byte_f_count];
            for (int i = 0; i < metaStr_byte_f_count; i++)
            {
                if (i < metaStr_byte_count)
                {
                    metaStr_byte_f[i] = metaStr_byte[i];
                }
                else
                {
                    metaStr_byte_f[i] = 0;
                }
            }
            var metaStr_buffer = CryptographicBuffer.CreateFromByteArray(metaStr_byte_f);
            #endregion

            #region _Key
            var _SymmetricKeyAlgorithmProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);
            var _Key = _SymmetricKeyAlgorithmProvider.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(this._key));
            #endregion

            #region IV_buffer
            var IV_buffer = CryptographicBuffer.CreateFromByteArray(_iv);
            #endregion

            IBuffer _result_buffer = CryptographicEngine.Encrypt(_Key, metaStr_buffer, IV_buffer);
            return(CryptographicBuffer.EncodeToHexString(_result_buffer));
        }
예제 #17
0
        /// <summary>
        /// Get the hash representing the string
        /// </summary>
        /// <param name="target">The bytes array to hash</param>
        /// <param name="algorithm">The hash algortihm to use</param>
        /// <returns>The hash value</returns>
        public static string GetHash(this byte[] target, HashAlgorithms algorithm)
        {
            if (algorithm == HashAlgorithms.Md5)
            {
                var md5    = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
                var buffer = CryptographicBuffer.CreateFromByteArray(target);
                var hashed = md5.HashData(buffer);
                return(CryptographicBuffer.EncodeToHexString(hashed));
            }
            else if (algorithm == HashAlgorithms.Sha512 || algorithm == HashAlgorithms.Sha256)
            {
                var sha    = HashAlgorithmProvider.OpenAlgorithm(algorithm == HashAlgorithms.Sha512 ? HashAlgorithmNames.Sha256 : HashAlgorithmNames.Sha512);
                var buffer = CryptographicBuffer.CreateFromByteArray(target);

                var    hashed = sha.HashData(buffer);
                byte[] bytes;

                CryptographicBuffer.CopyToByteArray(hashed, out bytes);
                return(Convert.ToBase64String(bytes));
            }
            else
            {
                throw new NotSupportedException("Unsupported hash algorithm");
            }
        }
        private async Task ValidateSelfSignedCert(Certificate cert)
        {
            var thumbprint = CryptographicBuffer.EncodeToHexString(CryptographicBuffer.CreateFromByteArray(cert.GetHashValue())).ToUpper();
            var dialog     = new MessageDialog(App.ResourceLoader.GetString("TrustCertificateQuestion") + Environment.NewLine + $"SHA1-{App.ResourceLoader.GetString("Fingerprint")}: " + thumbprint);

            dialog.Title = App.ResourceLoader.GetString("InvalidCA");

            dialog.Commands.Add(new UICommand(App.ResourceLoader.GetString("Yes"))
            {
                Id = 0
            });
            dialog.Commands.Add(new UICommand(App.ResourceLoader.GetString("No"))
            {
                Id = 1
            });
            var result = await dialog.ShowAsync();

            if ((int)result.Id == 0)
            {
                CertificateStore store = CertificateStores.TrustedRootCertificationAuthorities;
                store.Add(cert);
                await CheckServerStatus();
            }
            if ((int)result.Id == 1)
            {
                ResponseCode = App.ResourceLoader.GetString("InvalidCA");
            }
        }
예제 #19
0
        private async void DeleteCerts_Click(object sender, RoutedEventArgs e)
        {
            DeleteCertsCompleted.Visibility = Visibility.Collapsed;

            try
            {
                IReadOnlyCollection <Certificate> certs = await CertificateStores.FindAllAsync();

                StringBuilder builder = new StringBuilder();

                // Append count.
                builder.AppendFormat("Count: {0}\r\n", certs.Count);

                foreach (var cert in certs)
                {
                    builder.Append("--------------------\r\n");
                    builder.AppendFormat("Issuer: {0}\r\n", cert.Issuer);
                    builder.AppendFormat("Subject: {0}\r\n", cert.Subject);

                    string thumbprint = CryptographicBuffer.EncodeToHexString(CryptographicBuffer.CreateFromByteArray(cert.GetHashValue()));
                    builder.AppendFormat("Thumbprint: {0}\r\n", thumbprint);

                    // Not working:
                    CertificateStores.IntermediateCertificationAuthorities.Delete(cert);
                }

                CertsBlock.Text = builder.ToString();
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }

            DeleteCertsCompleted.Visibility = Visibility.Visible;
        }
예제 #20
0
		private JSONObject GetPasswordObj(string password) {
#if WINDOWS_UWP
            // Convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);

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

            // Demonstrate how to retrieve the name of the hashing algorithm.
            string strAlgNameUsed = objAlgProv.AlgorithmName;

            // Hash the message.
            IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

            // Verify that the hash length equals the length specified for the algorithm.
            if (buffHash.Length != objAlgProv.HashLength)
            {
                throw new Exception("There was an error creating the hash");
            }

            // Convert the hash to a string (for display).
            string digest = CryptographicBuffer.EncodeToHexString(buffHash);
#else
            string digest = BitConverter.ToString(
				new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(password)));
#endif
            digest = digest.Replace("-", "").ToLower();

            JSONObject passwordObj = JSONObject.Create();
			passwordObj.AddField("digest", digest);
			passwordObj.AddField("algorithm", "sha-256");

			return passwordObj;
		}
예제 #21
0
        public static string Set(string jid, byte[] image)
        {
            try
            {
                // Get the sha1 hash of the image for comparing
                var    sha1Algorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
                var    hashBuffer    = sha1Algorithm.HashData(CryptographicBuffer.CreateFromByteArray(image));
                string hash          = CryptographicBuffer.EncodeToHexString(hashBuffer);

                // Get Filename
                var filename = Helper.EncodeBASE64(jid) + "_" + Helper.UnixTimestampFromDateTime(DateTime.Now);

                // Create the file ( and overwrite if neccessary )
                var createTask = Folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting).AsTask();
                createTask.Wait(10000);

                // If creation succeeded, write the image
                if (createTask.IsCompleted && createTask.Result != null)
                {
                    var writeTask = FileIO.WriteBytesAsync(createTask.Result, image).AsTask();
                    writeTask.Wait(10000);

                    // return the hash of the new image if everything went well
                    if (writeTask.IsCompleted)
                    {
                        return(hash);
                    }
                }
            } catch {}

            return(string.Empty);
        }
예제 #22
0
        //Function for MD5 and encode password
        public String EncodeToMd5(String myString)
        {
            String md5Hash = null;

            if (myString != null)
            {
                //var myStringBytes = myString.GetBytes();

                //md5Hash = myStringBytes.ComputeMD5Hash().ToString();
                //// md5Hash = md5Hash.Remove(md5Hash.Length - 1);

                //md5Hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(md5Hash));
                string  strAlgName  = HashAlgorithmNames.Md5;
                IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(myString, BinaryStringEncoding.Utf8);

                HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);
                md5Hash = objAlgProv.AlgorithmName;

                IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);
                md5Hash = CryptographicBuffer.EncodeToHexString(buffHash);

                md5Hash = Convert.ToBase64String(md5Hash.GetBytes());
            }


            return(md5Hash);
        }
예제 #23
0
        static string GetZhiHuSignatureKey(string timestamp)
        {
            var param     = GrantType + ClientId + ZhiHuPacketName + timestamp.ToString();
            var signature = SHA1Handle(CryptographicBuffer.ConvertStringToBinary(param, BinaryStringEncoding.Utf8));

            return(CryptographicBuffer.EncodeToHexString(signature));
        }
예제 #24
0
        /// <summary>
        /// Returns device id
        /// </summary>
        public static string GetDeviceId()
        {
            var token      = HardwareIdentification.GetPackageSpecificToken(null);
            var hardwareId = token.Id;

            return(CryptographicBuffer.EncodeToHexString(hardwareId));
        }
예제 #25
0
        public static string getHashedFilename(string key)
        {
            var alg  = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            var buff = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf16LE);

            return(CryptographicBuffer.EncodeToHexString(alg.HashData(buff)));
        }
예제 #26
0
        private async void DoBufferWork(IBackgroundTaskInstance taskInstance)
        {
            string message            = "Hello World!";
            string unprotectedMessage = "";
            string logFileName        = "Bufferlog.txt";
            string logFileContent     = "";

            StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile   logFile     = await localFolder.CreateFileAsync(logFileName, CreationCollisionOption.OpenIfExists);


            IBuffer inputBuffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);
            BufferProtectUnprotectResult procBuffer = await DataProtectionManager.ProtectAsync(inputBuffer, m_EnterpriseID);

            logFileContent += "\r\n" + DateTime.Now + ":" + "ProtStatus:" + procBuffer.ProtectionInfo.Status + "\n";
            logFileContent += "\r\n" + "Protected Buffer:" + CryptographicBuffer.EncodeToHexString(procBuffer.Buffer).Substring(0, 5);

            // If keys are dropped under lock, unprotectBuffer will fail so don't unprotectbuffer under lock
            if (!m_areKeysDropped)
            {
                BufferProtectUnprotectResult unBuffer = await DataProtectionManager.UnprotectAsync(procBuffer.Buffer);

                unprotectedMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, procBuffer.Buffer);
                logFileContent    += "\n Unprotected string:" + unprotectedMessage;
                if (message != unprotectedMessage)
                {
                    throw new Exception("Original string does not match with unprotectedMessage!");
                }
            }

            await FileIO.AppendTextAsync(logFile, logFileContent);
        }
예제 #27
0
        public string Encrypt(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                throw new ArgumentNullException("plainText");
            }
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("Key");
            }
            if (string.IsNullOrEmpty(iv))
            {
                throw new ArgumentNullException("IV");
            }

            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;

            IBuffer          keyBuffer = CryptographicBuffer.ConvertStringToBinary(key, encoding);
            CryptographicKey cryptoKey = alg.CreateSymmetricKey(keyBuffer);
            IBuffer          ivBuffer  = CryptographicBuffer.ConvertStringToBinary(iv, encoding);

            // Add padding so buffer length is multiple of 16
            plainText = PadString(plainText);

            IBuffer inputBuffer     = CryptographicBuffer.ConvertStringToBinary(plainText, encoding);
            IBuffer encryptedBuffer = CryptographicEngine.Encrypt(cryptoKey, inputBuffer, ivBuffer);

            return(CryptographicBuffer.EncodeToHexString(encryptedBuffer));
        }
예제 #28
0
        private async void UnprotectAsyncBuffer_Click(object sender, RoutedEventArgs e)
        {
            string outputStr = "";

            if (m_protectedStream != null)
            {
                IInputStream source = m_protectedStream.GetInputStreamAt(0);
                m_unprotectedStream = new InMemoryRandomAccessStream();
                await DataProtectionManager.UnprotectStreamAsync(source,
                                                                 m_unprotectedStream
                                                                 );

                var unprotectedReader = new DataReader(m_unprotectedStream.GetInputStreamAt(0));
                await unprotectedReader.LoadAsync((uint)m_unprotectedStream.Size);

                IBuffer unprotectedStreamBuffer = unprotectedReader.ReadBuffer((uint)m_unprotectedStream.Size);
                outputStr += "\n UnProtected Stream buffer:" +
                             CryptographicBuffer.EncodeToHexString(unprotectedStreamBuffer);

                rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser("Please protect a stream to unprotect", NotifyType.ErrorMessage);
            }
        }
예제 #29
0
        public string GetMD5Hash(string input)
        {
            HashAlgorithmProvider algorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            IBuffer buffer = algorithm.HashData(Encoding.Unicode.GetBytes(input).AsBuffer());

            return(CryptographicBuffer.EncodeToHexString(buffer));
        }
예제 #30
0
        private string GetDeviceIdentifyId()
        {
            string deviceUniqeId = string.Empty;

            try
            {
                if (ApiInformation.IsTypePresent("Windows.System.Profile.HardwareIdentification"))
                {
                    var packageSpecificToken = HardwareIdentification.GetPackageSpecificToken(null);
                    var hardwareId           = packageSpecificToken.Id;

                    var hasher           = HashAlgorithmProvider.OpenAlgorithm("MD5");
                    var hashedHardwareId = hasher.HashData(hardwareId);

                    deviceUniqeId = CryptographicBuffer.EncodeToHexString(hashedHardwareId);
                    return(deviceUniqeId);
                }
            }
            catch (Exception)
            {
                // XBOX 目前會取失敗
            }

            // support IoT Device
            var    networkProfiles  = Windows.Networking.Connectivity.NetworkInformation.GetConnectionProfiles();
            var    adapter          = networkProfiles[0].NetworkAdapter;
            string networkAdapterId = adapter.NetworkAdapterId.ToString();

            deviceUniqeId = networkAdapterId.Replace("-", string.Empty);

            return(deviceUniqeId);
        }