public byte[] ComputeHash(byte[] buffer) { _hash.Append(buffer); var hash = _hash.GetValueAndReset().ToArray(); return(hash); }
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); }
public string Hash(string str) { var _buffer = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8); hashobj.Append(_buffer); var _resbuffer = hashobj.GetValueAndReset(); return(CryptographicBuffer.EncodeToBase64String(_resbuffer)); }
public byte[] ComputeHash(byte[] buffer) { IBuffer inputBuffer = CryptographicBuffer.CreateFromByteArray(buffer); _hash.Append(inputBuffer); var hash = _hash.GetValueAndReset().ToArray(); return(hash); }
// Appends a given number of bytes to the hash private static void Append(CryptographicHash hash, int bytesRead, byte[] buffer) { if (bytesRead == buffer.Length) { // append the whole buffer hash.Append(buffer); } else { // only a part of the buffer should be appended, so need a smaller buffer var partialBuffer = new byte[bytesRead]; Array.Copy(buffer, partialBuffer, bytesRead); hash.Append(partialBuffer); } }
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)); }
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; }
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); } }
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); } }
/// <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> /// 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()); }
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); }
/// <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); } }
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); } }
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) { }; }
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); }
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; //} }
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 "); } }
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); } }
/// <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); }
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); }
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); }
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); } }
/// <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; } }
private BEncodedString GetToken(Node node, byte[] s) { //refresh secret needed if (_lastSecretGeneration.Add(Timeout) < DateTime.UtcNow) { _lastSecretGeneration = DateTime.UtcNow; _secret.CopyTo(_previousSecret, 0); _secret = CryptographicBuffer.GenerateRandom((uint)_secret.Length).ToArray(); } var n = node.CompactPort().TextBytes; _hash.Append(n.AsBuffer()); _hash.Append(s.AsBuffer()); return(_hash.GetValueAndReset().ToArray()); }
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)); }
/// <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()); }
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); }
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(); } }
void HashCore (byte[] block, int offset, int size) { var array = new byte[size]; Buffer.BlockCopy (block, offset, array, 0, size); var buffer = CryptographicBuffer.CreateFromByteArray (array); hash.Append (buffer); }