public async Task DecryptFileAes(FileItemViewModel fileToDecrypt) { if (fileToDecrypt.IsEncrypted) { XmlSerializer serializer = new XmlSerializer(typeof(SerialisableAuthData)); SerialisableAuthData tagData = null; using (Stream stream = await fileToDecrypt.File.OpenStreamForReadAsync()) { tagData = serializer.Deserialize(stream) as SerialisableAuthData; stream.Dispose(); } if (tagData != null) { IBuffer data = tagData.GetData(); IBuffer tag = tagData.GetTag(); var decryptedData = CryptographicEngine.DecryptAndAuthenticate(aesKey, data, fileToDecrypt.Nonce, tag, null); await FileIO.WriteBufferAsync(fileToDecrypt.File, decryptedData); } fileToDecrypt.IsEncrypted = false; } else { throw new Exception("Tried to dencrypt file with encrypted flag already set to false"); } }
public void AuthenticatedDecryptionSender( String strAlgName, string key, string message, string nonce, string tag) { // Open a SymmetricKeyAlgorithmProvider object for the specified algorithm. SymmetricKeyAlgorithmProvider objAlgProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); IBuffer encryptedAESKey = CryptographicBuffer.DecodeFromBase64String(key); asymmetricDecryptAESKeySender(strAsymmetricAlgName, encryptedAESKey); IBuffer decryptedAESKeyBuff = CryptographicBuffer.DecodeFromBase64String(keyMaterialStringSender); CryptographicKey keyFromEncryptedString = objAlgProv.CreateSymmetricKey(decryptedAESKeyBuff); IBuffer encryptedDataFromStringBuff = CryptographicBuffer.DecodeFromBase64String(message); IBuffer nonceFromString = CryptographicBuffer.DecodeFromBase64String(nonce); IBuffer authenticationTagFromString = CryptographicBuffer.DecodeFromBase64String(tag); // The input key must be securely shared between the sender of the encrypted message // and the recipient. The nonce must also be shared but does not need to be shared // in a secure manner. If the sender encodes the message string to a buffer, the // binary encoding method must also be shared with the recipient. // The recipient uses the DecryptAndAuthenticate() method as follows to decrypt the // message, authenticate it, and verify that it has not been altered in transit. buffDecrypted = CryptographicEngine.DecryptAndAuthenticate( keyFromEncryptedString, encryptedDataFromStringBuff, nonceFromString, authenticationTagFromString, null); strDecrypted = CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted); }
/// <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) { String algName = AlgorithmNames.SelectionBoxItem.ToString(); UInt32 keySize = UInt32.Parse(KeySizes.SelectionBoxItem.ToString()); Scenario6Text.Text = ""; IBuffer Decrypted; IBuffer Data; IBuffer Nonce; String Cookie = "Some Cookie to Encrypt"; // Data to encrypt. Data = CryptographicBuffer.ConvertStringToBinary(Cookie, BinaryStringEncoding.Utf16LE); // Created a SymmetricKeyAlgorithmProvider object for the algorithm specified on input. SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algName); Scenario6Text.Text += "*** Sample Authenticated Encryption\n"; Scenario6Text.Text += " Algorithm Name: " + Algorithm.AlgorithmName + "\n"; Scenario6Text.Text += " Key Size: " + keySize + "\n"; Scenario6Text.Text += " Block length: " + Algorithm.BlockLength + "\n"; // Generate a random key. IBuffer keymaterial = CryptographicBuffer.GenerateRandom((keySize + 7) / 8); CryptographicKey key = Algorithm.CreateSymmetricKey(keymaterial); // Microsoft GCM implementation requires a 12 byte Nonce. // Microsoft CCM implementation requires a 7-13 byte Nonce. Nonce = GetNonce(); // Encrypt and create an authenticated tag on the encrypted data. EncryptedAndAuthenticatedData Encrypted = CryptographicEngine.EncryptAndAuthenticate(key, Data, Nonce, null); Scenario6Text.Text += " Plain text: " + Data.Length + " bytes\n"; Scenario6Text.Text += " Encrypted: " + Encrypted.EncryptedData.Length + " bytes\n"; Scenario6Text.Text += " AuthTag: " + Encrypted.AuthenticationTag.Length + " bytes\n"; // Create another instance of the key from the same material. CryptographicKey key2 = Algorithm.CreateSymmetricKey(keymaterial); if (key.KeySize != key2.KeySize) { Scenario6Text.Text += "CreateSymmetricKey failed! The imported key's size did not match the original's!"; return; } // Decrypt and verify the authenticated tag. Decrypted = CryptographicEngine.DecryptAndAuthenticate(key2, Encrypted.EncryptedData, Nonce, Encrypted.AuthenticationTag, null); if (!CryptographicBuffer.Compare(Decrypted, Data)) { Scenario6Text.Text += "Decrypted does not match original!"; return; } }
public byte[] Decrypt([ReadOnlyArray] byte[] aad, [ReadOnlyArray] byte[] cek, [ReadOnlyArray] byte[] iv, [ReadOnlyArray] byte[] cipherText, [ReadOnlyArray] byte[] authTag) { Ensure.BitSize(cek, keySizeBits, string.Format("AesGcmEncryptor expected key of size {0} bits, but was given {1} bits", keySizeBits, cek.Length * 8)); SymmetricKeyAlgorithmProvider alg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesGcm); CryptographicKey key = alg.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(cek)); return(Buffer.ToBytes( CryptographicEngine.DecryptAndAuthenticate(key, CryptographicBuffer.CreateFromByteArray(cipherText), CryptographicBuffer.CreateFromByteArray(iv), CryptographicBuffer.CreateFromByteArray(authTag), CryptographicBuffer.CreateFromByteArray(aad)))); }
public void DecryptString(StringItemViewModel stringToDecrypt) { if (stringToDecrypt.IsEncrypted) { IBuffer stringBuffer = CryptographicBuffer.ConvertStringToBinary(stringToDecrypt.Content, BinaryStringEncoding.Utf8); var decryptedString = CryptographicEngine.DecryptAndAuthenticate(aesKey, stringBuffer, stringToDecrypt.Nonce, stringToDecrypt.AuthenticationTag, null); stringToDecrypt.Content = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedString); stringToDecrypt.IsEncrypted = false; } else { throw new Exception("Tried to encrypt string with encrypted flag set to false"); } }
/// <summary> /// The decrypt symmetric. /// </summary> /// <param name="keyBuffer"> /// The key buffer. /// </param> /// <param name="data"> /// The data. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> private string DecryptSymmetric(IBuffer keyBuffer, string data) { IBuffer initializationBuffer = null; IBuffer authenticationTag = null; IBuffer message; if (this.HasAuthentication) { var parts = data.Split('|'); if (parts.Length != 2) { throw new Exception("Missing authentication tag, encrypted data, or both."); } authenticationTag = CryptographicBuffer.DecodeFromBase64String(parts[0]); message = CryptographicBuffer.DecodeFromBase64String(parts[1]); } else { message = CryptographicBuffer.DecodeFromBase64String(data); } var algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(this.AlgorithmName); CryptographicKey keyMaterial = algorithm.CreateSymmetricKey(EnsureLength(keyBuffer, 32, true)); if (this.ModeOfOperation.Equals(ModeOfOperation.CBC)) { var initialationVector = CryptographicBuffer.ConvertStringToBinary(Iv, Encoding); initializationBuffer = EnsureLength( initialationVector, (int)algorithm.BlockLength, true); } if (this.HasAuthentication) { var authenticationData = CryptographicBuffer.ConvertStringToBinary(AuthenticationData, Encoding); var decryptedData = CryptographicEngine.DecryptAndAuthenticate( keyMaterial, message, GetNonce(), authenticationTag, authenticationData); return(CryptographicBuffer.ConvertBinaryToString(Encoding, decryptedData)); } var decryptedBuffer = CryptographicEngine.Decrypt( keyMaterial, message, initializationBuffer); return(CryptographicBuffer.ConvertBinaryToString(Encoding, decryptedBuffer)); }
public void AuthenticatedDecryption( String strAlgName, String buffNonce) { // Open a SymmetricKeyAlgorithmProvider object for the specified algorithm. SymmetricKeyAlgorithmProvider objAlgProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); IBuffer encryptedAESKey = CryptographicBuffer.DecodeFromBase64String(encryptedKeyString); asymmetricDecryptAESKey(strAsymmetricAlgName, encryptedAESKeyBuff); IBuffer decryptedAESKeyBuff = CryptographicBuffer.DecodeFromBase64String(decryptedAesKeyString); CryptographicKey keyFromEncryptedString = objAlgProv.CreateSymmetricKey(decryptedAESKeyBuff); IBuffer encryptedDataFromStringBuff = CryptographicBuffer.DecodeFromBase64String(plaintext); IBuffer nonceFromString = CryptographicBuffer.DecodeFromBase64String(nonceString); IBuffer authenticationTagFromString = CryptographicBuffer.DecodeFromBase64String(authenticationTagString); // The input key must be securely shared between the sender of the encrypted message // and the recipient. The nonce must also be shared but does not need to be shared // in a secure manner. If the sender encodes the message string to a buffer, the // binary encoding method must also be shared with the recipient. // The recipient uses the DecryptAndAuthenticate() method as follows to decrypt the // message, authenticate it, and verify that it has not been altered in transit. buffDecrypted = CryptographicEngine.DecryptAndAuthenticate( keyFromEncryptedString, encryptedDataFromStringBuff, nonceFromString, authenticationTagFromString, null); // Convert the decrypted buffer to a string (for display). If the sender created the // original message buffer from a string, the sender must tell the recipient what // BinaryStringEncoding value was used. Here, BinaryStringEncoding.Utf8 is used to // convert the message to a buffer before encryption and to convert the decrypted // buffer back to the original plaintext. String strDecrypted = CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted); plaintext = strDecrypted; plain.Text = plaintext; cipher.Text = plaintext; }
/// <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 RunEncryption_Click(object sender, RoutedEventArgs e) { EncryptDecryptText.Text = ""; IBuffer encrypted; IBuffer decrypted; IBuffer iv = null; IBuffer data; IBuffer nonce; String algName = AlgorithmNames.SelectionBoxItem.ToString(); CryptographicKey key = null; if (bSymAlgs.IsChecked.Value || bAuthEncrypt.IsChecked.Value) { key = GenerateSymmetricKey(); } else { key = GenerateAsymmetricKey(); } data = GenearetData(); if ((bool)bAuthEncrypt.IsChecked) { nonce = GetNonce(); EncryptedAndAuthenticatedData encryptedData = CryptographicEngine.EncryptAndAuthenticate(key, data, nonce, null); EncryptDecryptText.Text += " Plain text: " + data.Length + " bytes\n"; EncryptDecryptText.Text += " Encrypted: " + encryptedData.EncryptedData.Length + " bytes\n"; EncryptDecryptText.Text += " AuthTag: " + encryptedData.AuthenticationTag.Length + " bytes\n"; decrypted = CryptographicEngine.DecryptAndAuthenticate(key, encryptedData.EncryptedData, nonce, encryptedData.AuthenticationTag, null); if (!CryptographicBuffer.Compare(decrypted, data)) { EncryptDecryptText.Text += "Decrypted does not match original!"; return; } } else { // CBC mode needs Initialization vector, here just random data. // IV property will be set on "Encrypted". if (algName.Contains("CBC")) { SymmetricKeyAlgorithmProvider algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algName); iv = CryptographicBuffer.GenerateRandom(algorithm.BlockLength); } // Encrypt the data. try { encrypted = CryptographicEngine.Encrypt(key, data, iv); } catch (ArgumentException ex) { EncryptDecryptText.Text += ex.Message + "\n"; EncryptDecryptText.Text += "An invalid key size was selected for the given algorithm.\n"; return; } EncryptDecryptText.Text += " Plain text: " + data.Length + " bytes\n"; EncryptDecryptText.Text += " Encrypted: " + encrypted.Length + " bytes\n"; // Decrypt the data. decrypted = CryptographicEngine.Decrypt(key, encrypted, iv); if (!CryptographicBuffer.Compare(decrypted, data)) { EncryptDecryptText.Text += "Decrypted data does not match original!"; return; } } }