public static string Encrypt(string plainText, string pw, string iv) { IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); IBuffer ivBuffer = CryptographicBuffer.ConvertStringToBinary(iv, BinaryStringEncoding.Utf16LE); IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf16LE); // Derive key material for password size 32 bytes for AES256 algorithm KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); // using iv and 1000 iterations KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(ivBuffer, 1000); // create a key based on original key and derivation parmaters CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); // derive buffer to be used for encryption IV from derived password key IBuffer ivMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); // create symmetric key from derived password key CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); // encrypt data buffer using symmetric key and derived iv material IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, ivMaterial); return(CryptographicBuffer.EncodeToBase64String(resultBuffer)); }
private string AesDecrypt(string encryptionKey, string value) { if (string.IsNullOrEmpty(value)) { return(value); } IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(encryptionKey, BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(passwordBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(passwordBuffer); IBuffer ivBuffer = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); CryptographicKey aesKey = aes.CreateSymmetricKey(keyMaterial); IBuffer decryptedContentBuffer = CryptographicEngine.Decrypt(aesKey, CryptographicBuffer.DecodeFromBase64String(value), ivBuffer); return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedContentBuffer)); }
public static byte[] Encrypt(string plainText, string pw, string salt) { //password buffer is created IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); //salt buffer is created IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf16LE); KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); //key parameters are passed KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); //original key is created and stored CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); //A variable that holds symmetric key provider SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); //Symmetric key is created and stored in symKey CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial); byte[] result; CryptographicBuffer.CopyToByteArray(resultBuffer, out result); return(result); }
public static string AesDecrypt(this byte[] encrypted, string password, string salt) { IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encrypted); // Derive key material for password size 32 bytes for AES256 algorithm KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); // using salt and 1000 iterations KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); // create a key based on original key and derivation parmaters CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); // derive buffer to be used for encryption salt from derived password key IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); // display the keys – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); // create symmetric key from derived password material CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); // encrypt data buffer using symmetric key and derived salt material IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial); string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer); return(result); }
/** * Generate a PBDFK hash * @param string password * @param string salt * @param string algorithm * @param uint iterationCountIn * @param uint target size */ public static IBuffer GetHash(IBuffer buffSecret, IBuffer buffSalt, uint targetSize = 64, uint iterationCountIn = 100000, string algorithm = null) { // Use the provide KeyDerivationAlgorithm if provided, otherwise default to PBKDF2-SHA256 if (algorithm == null) { algorithm = _algorithm; } KeyDerivationAlgorithmProvider provider = KeyDerivationAlgorithmProvider.OpenAlgorithm(algorithm); // This is our secret password //IBuffer buffSecret = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); // Use the provided salt //IBuffer buffSalt = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8); // Create the derivation parameters. KeyDerivationParameters pbkdf2Params = KeyDerivationParameters.BuildForPbkdf2(buffSalt, iterationCountIn); // Create a key from the secret value. CryptographicKey keyOriginal = provider.CreateKey(buffSecret); // Derive a key based on the original key and the derivation parameters. IBuffer keyDerived = CryptographicEngine.DeriveKeyMaterial( keyOriginal, pbkdf2Params, targetSize ); return(keyDerived); // Encode the key to a hexadecimal value (for display) // return CryptographicBuffer.EncodeToHexString(keyDerived); }
public String SampleDeriveFromPbkdf( String strAlgName, UInt32 targetSize) { // Open the specified algorithm. KeyDerivationAlgorithmProvider objKdfProv = KeyDerivationAlgorithmProvider.OpenAlgorithm(strAlgName); // Create a buffer that contains the secret used during derivation. IBuffer buffSecret = CryptographicBuffer.ConvertStringToBinary(SampleConfiguration.strSecret, BinaryStringEncoding.Utf8); // Create a random salt value. IBuffer buffSalt = CryptographicBuffer.GenerateRandom(32); // Specify the number of iterations to be used during derivation. UInt32 iterationCount = 10000; // Create the derivation parameters. KeyDerivationParameters pbkdf2Params = KeyDerivationParameters.BuildForPbkdf2(buffSalt, iterationCount); // Create a key from the secret value. CryptographicKey keyOriginal = objKdfProv.CreateKey(buffSecret); // Derive a key based on the original key and the derivation parameters. IBuffer keyDerived = CryptographicEngine.DeriveKeyMaterial( keyOriginal, pbkdf2Params, targetSize); // Encode the key to a Base64 value (for display) String strKeyBase64 = CryptographicBuffer.EncodeToHexString(keyDerived); // Return the encoded string return(strKeyBase64); }
private void GenerateKeyMaterial(string password, uint iterationCount, out IBuffer keyMaterial, out IBuffer iv) { // setup KDF parameters for the desired salt and iteration count IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(SALT); KeyDerivationParameters kdfParameters = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, iterationCount); // get a KDF provider for PBKDF2, and store the source password in a Cryptographic Key KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(_keyDerivationAlgo); var pwBytes = Encoding.GetEncoding("ASCII").GetBytes(password); IBuffer passwordBuffer = CryptographicBuffer.CreateFromByteArray(pwBytes); //IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); CryptographicKey passwordSourceKey = kdf.CreateKey(passwordBuffer); // generate key material from the source password, salt, and iteration count. Only call DeriveKeyMaterial once, // since calling it twice will generate the same data for the key and IV. int keySize = 256 / 8; int ivSize = 128 / 8; uint totalDataNeeded = (uint)(keySize + ivSize); IBuffer keyAndIv = CryptographicEngine.DeriveKeyMaterial(passwordSourceKey, kdfParameters, totalDataNeeded); // split the derived bytes into a seperate key and IV byte[] keyMaterialBytes = keyAndIv.ToArray(); keyMaterial = WindowsRuntimeBuffer.Create(keyMaterialBytes, 0, keySize, keySize); iv = WindowsRuntimeBuffer.Create(keyMaterialBytes, keySize, ivSize, ivSize); }
public static string Encrypt(string plainText) { //Chuyen password sang IBuffer theo dinh dang Utf8 IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); //Chuyen salt theo dinh dang Utf8 IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8); //Chuyen chuoi can ma hoa sang IBuffer theo dinh dang Utf8 IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8); //Khai bao thuat toan bam KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); //Tao param key gia tri salt voi so lan lap 1000 theo thuat toan PBKDF2_SHA1 KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); //Tao KeyOriginal de ma hoa tu mat khau CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); //Tao KeyMaterial de ma hoa tu keyOriginal va key cua Salt voi kich thuoc 32 byte IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); //Tao saltMaterial de ma hoa tu derivedPwKey va key cua Salt voi kich thuoc la 16 byte IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 16); //Khai bao thuat toan ma hoa SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); //Tao key ma hoa tu keyMaterial CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); //Ma hoa chuoi du lieu IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial); //Chuyen du lieu sau khi ma hoa sang dang chuoi return(CryptographicBuffer.EncodeToBase64String(resultBuffer)); }
// http://stackoverflow.com/questions/23023058/using-pbkdf2-encryption-in-a-metro-winrt-application private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes) { #if Win8 byte[] encryptionKeyOut; IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(salt); KeyDerivationParameters kdfParameters = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, PBKDF2_ITERATIONS); // Get a KDF provider for PBKDF2 and hash the source password to a Cryptographic Key using the SHA256 algorithm. // The generated key for the SHA256 algorithm is 256 bits (32 bytes) in length. KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); CryptographicKey passwordSourceKey = kdf.CreateKey(passwordBuffer); // Generate key material from the source password, salt, and iteration count const int keySize = 256 / 8; // 256 bits = 32 bytes IBuffer key = CryptographicEngine.DeriveKeyMaterial(passwordSourceKey, kdfParameters, keySize); // send the generated key back to the caller CryptographicBuffer.CopyToByteArray(key, out encryptionKeyOut); return(encryptionKeyOut); // success #else return(null); #endif }
public static string Decrypt(byte[] encryptval, string pw, string salt) { IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptval); KeyDerivationAlgorithmProvider key = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); KeyDerivationParameters parm = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); CryptographicKey ckey = key.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(ckey, parm, 32); CryptographicKey dkey = key.CreateKey(pwBuffer); IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(ckey, parm, 16); SymmetricKeyAlgorithmProvider sp = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); CryptographicKey symmKey = sp.CreateSymmetricKey(keyMaterial); IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial); string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer); return(result); }
/// <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(); IBuffer Secret = CryptographicBuffer.ConvertStringToBinary("Master key to derive from", BinaryStringEncoding.Utf8); UInt32 TargetSize = UInt32.Parse(KeySizes.SelectionBoxItem.ToString()); KeyDerivationText.Text = ""; KeyDerivationParameters Params; if (algName.Contains("PBKDF2")) { // Password based key derivation function (PBKDF2). Params = KeyDerivationParameters.BuildForPbkdf2( CryptographicBuffer.GenerateRandom(16), // Salt 10000 // PBKDF2 Iteration Count ); } else if (algName.Contains("SP800_108")) { // SP800_108_CTR_HMAC key derivation function. Params = KeyDerivationParameters.BuildForSP800108( CryptographicBuffer.ConvertStringToBinary("Label", BinaryStringEncoding.Utf8), // Label CryptographicBuffer.DecodeFromHexString("303132333435363738") // Context ); } else if (algName.Contains("SP800_56A")) { Params = KeyDerivationParameters.BuildForSP80056a( CryptographicBuffer.ConvertStringToBinary("AlgorithmId", BinaryStringEncoding.Utf8), CryptographicBuffer.ConvertStringToBinary("VParty", BinaryStringEncoding.Utf8), CryptographicBuffer.ConvertStringToBinary("UParty", BinaryStringEncoding.Utf8), CryptographicBuffer.ConvertStringToBinary("SubPubInfo", BinaryStringEncoding.Utf8), CryptographicBuffer.ConvertStringToBinary("SubPrivInfo", BinaryStringEncoding.Utf8) ); } else { KeyDerivationText.Text += " An invalid algorithm was specified.\n"; return; } // Create a KeyDerivationAlgorithmProvider object for the algorithm specified on input. KeyDerivationAlgorithmProvider Algorithm = KeyDerivationAlgorithmProvider.OpenAlgorithm(algName); KeyDerivationText.Text += "*** Sample Kdf Algorithm: " + Algorithm.AlgorithmName + "\n"; KeyDerivationText.Text += " Secrect Size: " + Secret.Length + "\n"; KeyDerivationText.Text += " Target Size: " + TargetSize + "\n"; // Create a key. CryptographicKey key = Algorithm.CreateKey(Secret); // Derive a key from the created key. IBuffer derived = CryptographicEngine.DeriveKeyMaterial(key, Params, TargetSize); KeyDerivationText.Text += " Derived " + derived.Length + " bytes\n"; KeyDerivationText.Text += " Derived: " + CryptographicBuffer.EncodeToHexString(derived) + "\n"; }
public static byte[] Encrypt(string plainText, string pw, string sult) { IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); IBuffer sultBuffer = CryptographicBuffer.ConvertStringToBinary(sult, BinaryStringEncoding.Utf16LE); IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf16LE); KeyDerivationAlgorithmProvider key = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); KeyDerivationParameters parm = KeyDerivationParameters.BuildForPbkdf2(sultBuffer, 1000); CryptographicKey ckey = key.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(ckey, parm, 32); CryptographicKey dkey = key.CreateKey(pwBuffer); IBuffer sulltMaterial = CryptographicEngine.DeriveKeyMaterial(dkey, parm, 16); SymmetricKeyAlgorithmProvider sp = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); CryptographicKey symKey = sp.CreateSymmetricKey(keyMaterial); IBuffer resultBuffer = CryptographicEngine.Encrypt(symKey, plainBuffer, sulltMaterial); byte[] result; CryptographicBuffer.CopyToByteArray(resultBuffer, out result); return(result); }
public static string Decrypt(byte[] encryptedData, string pw, string salt) { IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptedData); KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_ SHA1"); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial); string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer); return(result); }
public CryptographicKey SampleCreateKDFKey( String strAlgName, IBuffer buffKeyMaterial) { // Create a KeyDerivationAlgorithmProvider object and open the specified algorithm. KeyDerivationAlgorithmProvider objKdfAlgProv = KeyDerivationAlgorithmProvider.OpenAlgorithm(strAlgName); // Create a key by using the KDF parameters. CryptographicKey key = objKdfAlgProv.CreateKey(buffKeyMaterial); return(key); }
/// <summary> /// Performs a single iteration of PBKDF2-SHA-256. /// </summary> /// <param name="keyMaterial">The material from which the key will be derived.</param> /// <param name="salt">The salt used to randomize the derived key.</param> /// <param name="derivedKeyLength">The length of the derived key in bytes.</param> /// <returns>The derived key.</returns> static IBuffer OneRoundPbkdf2Sha256(IBuffer keyMaterial, IBuffer salt, uint derivedKeyLength) { Contract.Requires(keyMaterial != null); Contract.Requires(salt != null); Contract.Ensures(Contract.Result <IBuffer>() != null); Contract.Ensures(Contract.Result <IBuffer>().Length == derivedKeyLength); CryptographicKey key = pbkdf2Sha256.CreateKey(keyMaterial); var parameters = KeyDerivationParameters.BuildForPbkdf2(salt, 1); IBuffer derivedKey = CryptographicEngine.DeriveKeyMaterial(key, parameters, derivedKeyLength); return(derivedKey); }
private IBuffer passwordToKey(IBuffer password, IBuffer salt) { KeyDerivationParameters kdfParameters = KeyDerivationParameters.BuildForPbkdf2(salt, (uint)JSONStoreConstants.JSON_STORE_DEFAULT_PBKDF2_ITERATIONS); // Get a KDF provider for PBKDF2, and store the source password in a Cryptographic Key KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256); CryptographicKey passwordKey = kdf.CreateKey(password); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(passwordKey, kdfParameters, (uint)32); return(keyMaterial); }
public async static Task <byte[]> Encrypt(string filePath) { byte[] fileBytes = await FileManager.ReadBytesFromFile(filePath); IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(key1, BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(key2, BinaryStringEncoding.Utf16LE); IBuffer plainBuffer = CryptographicBuffer.CreateFromByteArray(fileBytes); // Derive key material for password size 32 bytes for AES256 algorithm KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); // using salt and 1000 iterations KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); // create a key based on original key and derivation parmaters CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); // derive buffer to be used for encryption salt from derived password key IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); // display the buffers – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); // create symmetric key from derived password key CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); // encrypt data buffer using symmetric key and derived salt material IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial); byte[] result; CryptographicBuffer.CopyToByteArray(resultBuffer, out result); return(result); }
public static string Decrypt(string encryptedData, string pw, string iv) { try { IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); IBuffer ivBuffer = CryptographicBuffer.ConvertStringToBinary(iv, BinaryStringEncoding.Utf16LE); IBuffer cipherBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedData); // Derive key material for password size 32 bytes for AES256 algorithm KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); // using IV and 1000 iterations KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(ivBuffer, 1000); // create a key based on original key and derivation parmaters CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); // derive buffer to be used for encryption iv from derived password key IBuffer ivMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); // create symmetric key from derived password material CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); // decrypt data buffer using symmetric key and derived IV material IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, ivMaterial); string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer); return(result); } catch (System.Exception) { System.Diagnostics.Debug.WriteLine("Failed to decrypt file. Throwing exception up the chain."); throw; } }
public static string GenerateEntropy(string password, string salt, CharSets sets, uint keySize, Algorithms digest, int length, uint iterations) { string algorithm; switch (digest) { case Algorithms.Sha256: algorithm = KeyDerivationAlgorithmNames.Pbkdf2Sha256; break; case Algorithms.Sha384: algorithm = KeyDerivationAlgorithmNames.Pbkdf2Sha384; break; case Algorithms.Sha512: algorithm = KeyDerivationAlgorithmNames.Pbkdf2Sha512; break; default: throw new ArgumentOutOfRangeException(); } KeyDerivationAlgorithmProvider provider = KeyDerivationAlgorithmProvider.OpenAlgorithm(algorithm); // This is our secret password IBuffer buffSecret = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); // Use the provided salt IBuffer buffSalt = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8); // Create the derivation parameters. KeyDerivationParameters pbkdf2Params = KeyDerivationParameters.BuildForPbkdf2(buffSalt, iterations); // Create a key from the secret value. CryptographicKey keyOriginal = provider.CreateKey(buffSecret); // Derive a key based on the original key and the derivation parameters. IBuffer keyDerived = CryptographicEngine.DeriveKeyMaterial( keyOriginal, pbkdf2Params, keySize ); // Return the buffer as a hex string return(CryptographicBuffer.EncodeToHexString(keyDerived)); }
public void GenerateKey(string password, string salt, out Windows.Storage.Streams.IBuffer keyMaterial, out Windows.Storage.Streams.IBuffer iv) { IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8); KeyDerivationParameters keyParams = KeyDerivationParameters.BuildForSP800108(saltBuffer, GetNonce()); KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(Encryptor.Settings.KeyDerivationAlgorithm); IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); CryptographicKey keyOriginal = kdf.CreateKey(passwordBuffer); int keySize = 256; int ivSize = 128 / 8; uint totalData = (uint)(keySize + ivSize); IBuffer keyDerived = CryptographicEngine.DeriveKeyMaterial(keyOriginal, keyParams, totalData); byte[] keyMaterialBytes = keyDerived.ToArray(); keyMaterial = WindowsRuntimeBuffer.Create(keyMaterialBytes, 0, keySize, keySize); iv = WindowsRuntimeBuffer.Create(keyMaterialBytes, keySize, ivSize, ivSize); }
/// <summary> /// Шифрование текста /// </summary> /// <param name="SourceText">Исходный (открытый) текст</param> /// <param name="InputKey">Ключ шифрование</param> /// <param name="AlgorythmName">Имя алгоритма шифрования</param> /// <returns>Зашифрованный текст</returns> public string EncryptMode(string SourceText, string InputKey, string AlgorythmName, string IV, string KeySize) { SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(AlgorythmName); IBuffer KeyBuffer = CryptographicBuffer.ConvertStringToBinary(InputKey, BinaryStringEncoding.Utf16LE); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary("ll234hl@kljh5:Annc!6002mz", BinaryStringEncoding.Utf16LE); //CryptoKey = Algorithm.CreateSymmetricKey(KeyBuffer); //######################### KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(KeyBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, Convert.ToUInt32(KeySize) / 8); //string test = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, keyMaterial); CryptoKey = Algorithm.CreateSymmetricKey(keyMaterial); //############### // CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); //Надо присваивать IV пользовательское значение или генерированное значение IV if (AlgorythmName.Contains("CBC")) { IVBuffer = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf16LE); } // Set the data to encrypt. SourceTextBuffer = CryptographicBuffer.ConvertStringToBinary(SourceText, BinaryStringEncoding.Utf16LE); // Encrypt EncryptBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.Encrypt(CryptoKey, SourceTextBuffer, IVBuffer); //Convert to Base64 EncryptTextOutput = CryptographicBuffer.EncodeToBase64String(EncryptBuffer); string test = CryptographicBuffer.EncodeToBase64String(keyMaterial); //return test;// return(EncryptTextOutput); }
/// <summary> /// Generates an encryption key derived using a password, a random salt, and specified number of rounds of PBKDF2 /// /// TODO: pass in password via SecureString? /// </summary> /// <param name="password"></param> /// <param name="salt"></param> /// <returns></returns> public static IBuffer GetEncryptionKey(string password, string salt) { if (string.IsNullOrEmpty(password)) { throw new ArgumentException("Password is empty"); } if (salt == null || salt.Length == 0) { throw new ArgumentException("Salt is empty"); } KeyDerivationAlgorithmProvider pbkdf2 = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); IBuffer buffSecret = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); CryptographicKey key = pbkdf2.CreateKey(buffSecret); KeyDerivationParameters parameters = KeyDerivationParameters.BuildForPbkdf2(CryptographicBuffer.DecodeFromBase64String(salt), PBKDF2_ITERATIONS); return(CryptographicEngine.DeriveKeyMaterial(key, parameters, KEY_SIZE_BYTES)); }
private static void GenerateKeyMaterial(IBuffer passwordBuffer, IBuffer saltBuffer, uint iterationCount, out IBuffer keyMaterial, out IBuffer iv) { KeyDerivationParameters kdfParameters = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, iterationCount); // Get a KDF provider for PBKDF2, and store the source password in a Cryptographic Key KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256); CryptographicKey passwordSourceKey = kdf.CreateKey(passwordBuffer); // Generate key material from the source password, salt, and iteration count. Only call DeriveKeyMaterial once, // since calling it twice will generate the same data for the key and IV. int keySize = 256 / 8; int ivSize = 128 / 8; uint totalDataNeeded = (uint)(keySize + ivSize); IBuffer keyAndIv = CryptographicEngine.DeriveKeyMaterial(passwordSourceKey, kdfParameters, totalDataNeeded); // Split the derived bytes into a seperate key and IV byte[] keyMaterialBytes = keyAndIv.ToArray(); keyMaterial = WindowsRuntimeBuffer.Create(keyMaterialBytes, 0, keySize, keySize); iv = WindowsRuntimeBuffer.Create(keyMaterialBytes, keySize, ivSize, ivSize); }
/// <summary> /// Derives a cryptographically strong key from the specified password. /// </summary> /// <param name="password">The user-supplied password.</param> /// <param name="salt">The salt.</param> /// <param name="iterations">The rounds of computation to use in deriving a stronger key. The larger this is, the longer attacks will take.</param> /// <param name="keySizeInBytes">The desired key size in bytes.</param> /// <returns>The generated key.</returns> public override byte[] DeriveKeyFromPassword(string password, byte[] salt, int iterations, int keySizeInBytes) { Requires.NotNullOrEmpty(password, "password"); Requires.NotNull(salt, "salt"); Requires.Range(iterations > 0, "iterations"); Requires.Range(keySizeInBytes > 0, "keySizeInBytes"); IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); IBuffer saltBuffer = salt.ToBuffer(); KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, (uint)iterations); // create a key based on original key and derivation parameters CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(passwordBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, (uint)keySizeInBytes); return(keyMaterial.ToArray()); }
public void DeriveEncryptionKey(byte[] passphrase, byte[] salt, ref byte[] encryptionKey) { var tokenData = SettingsHelper.LoadSetting <TFTokenData>(Consts.SETTINGS_TOKEN_SECRET_KEY); IBuffer passphraseBuffer = CryptographicBuffer.CreateFromByteArray(passphrase); IBuffer hmacKeyBuffer = CryptographicBuffer.CreateFromByteArray(tokenData.SecretKey); MacAlgorithmProvider hmacProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1); CryptographicHash saltHMAC = hmacProvider.CreateHash(hmacKeyBuffer); IBuffer saltBuffer = saltHMAC.GetValueAndReset(); KeyDerivationAlgorithmProvider pbkdf2Provider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, (uint)NumberOfOterations); CryptographicKey pbkdf2Key = pbkdf2Provider.CreateKey(passphraseBuffer); IBuffer derivedKeyBuffer = CryptographicEngine.DeriveKeyMaterial(pbkdf2Key, pbkdf2Parms, (uint)encryptionKey.Length); byte[] derivedKeyBytes = derivedKeyBuffer.ToArray(); Array.Copy(derivedKeyBytes, encryptionKey, encryptionKey.Length); Array.Clear(derivedKeyBytes, 0, derivedKeyBytes.Length); }
public IBuffer SampleDeriveKeyMaterialPbkdf( String strAlgName, UInt32 targetKeySize, UInt32 iterationCount) { // Open the specified algorithm. KeyDerivationAlgorithmProvider objKdfProv = KeyDerivationAlgorithmProvider.OpenAlgorithm(strAlgName); // Demonstrate how to retrieve the algorithm name. String strAlgUsed = objKdfProv.AlgorithmName; // Create a buffer that contains the secret used during derivation. String strSecret = "MyPassword"; IBuffer buffSecret = CryptographicBuffer.ConvertStringToBinary(strSecret, BinaryStringEncoding.Utf8); // Create a random salt value. IBuffer buffSalt = CryptographicBuffer.GenerateRandom(32); // Create the derivation parameters. KeyDerivationParameters pbkdf2Params = KeyDerivationParameters.BuildForPbkdf2(buffSalt, iterationCount); // Create a key from the secret value. CryptographicKey keyOriginal = objKdfProv.CreateKey(buffSecret); // Derive a key based on the original key and the derivation parameters. IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial( keyOriginal, pbkdf2Params, targetKeySize); // Demonstrate checking the iteration count. UInt32 iterationCountOut = pbkdf2Params.IterationCount; // Demonstrate returning the derivation parameters to a buffer. IBuffer buffParams = pbkdf2Params.KdfGenericBinary; // return the KDF key material. return(keyMaterial); }
public static string Decrypt(string encryptedData) { //Chuyen password sang IBuffer theo dinh dang Utf8 IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); //Chuyen salt theo dinh dang Utf8 IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8); //Chuyen du lieu chuoi sang IBuffer de giai ma IBuffer cipherBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedData); KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 16); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); //Giai ma IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial); //Chuyen tu dinh dang IBuffer ve chuoi ban dau string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, resultBuffer); return(result); }
public static bool GetPBKDFDerivedKey(string password, byte[] salt, // length = 32 bytes (256 bits) out byte[] encryptionKeyOut) // length = 32 bytes (256 bits) { IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(salt); KeyDerivationParameters kdfParameters = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000); // 10000 iterations // Get a KDF provider for PBKDF2 and hash the source password to a Cryptographic Key using the SHA256 algorithm. // The generated key for the SHA256 algorithm is 256 bits (32 bytes) in length. KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256); IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); CryptographicKey passwordSourceKey = kdf.CreateKey(passwordBuffer); // Generate key material from the source password, salt, and iteration count const int keySize = 256 / 8; // 256 bits = 32 bytes IBuffer key = CryptographicEngine.DeriveKeyMaterial(passwordSourceKey, kdfParameters, keySize); // send the generated key back to the caller CryptographicBuffer.CopyToByteArray(key, out encryptionKeyOut); return(true); // success }
/// <summary> /// Дешифрования текст /// </summary> /// <param name="SourceText">Исходный (шифрованный) текст</param> /// <param name="InputKey">Ключ шифрования</param> /// <param name="AlgorytmName">Имя алгоритма дешифрования</param> /// /// <returns>Расшифрованный (открытый) текст</returns> public string DecrypMode(string SourceText, string InputKey, string AlgorytmName, string IV, string KeySize) { SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(AlgorytmName); IBuffer KeyBuffer = CryptographicBuffer.ConvertStringToBinary(InputKey, BinaryStringEncoding.Utf16LE); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary("ll234hl@kljh5:Annc!6002mz", BinaryStringEncoding.Utf16LE); //CryptoKey = Algorithm.CreateSymmetricKey(keymaterial); KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(KeyBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, Convert.ToUInt32(KeySize) / 8); // string test= CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, keyMaterial); CryptoKey = Algorithm.CreateSymmetricKey(keyMaterial); if (AlgorytmName.Contains("CBC")) { IVBuffer = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf16LE); } // Set the data to encrypt. SourceTextBuffer = CryptographicBuffer.DecodeFromBase64String(SourceText); // Decrypt DecryptBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.Decrypt(CryptoKey, SourceTextBuffer, IVBuffer); DecryptTextOutput = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, DecryptBuffer);//Надо думать над реализацией Base64 return(DecryptTextOutput); }
/// <inheritdoc /> public override void ForwardProcessDataStream(System.IO.Stream inStream, System.IO.Stream outStream, Dictionary <string, string> options, out long writtenBytes) { if (options == null) { throw new ArgumentNullException("options"); } else if (!options.ContainsKey(PasswordOption)) { throw new ArgumentException("Options must contain encryption key", "options"); } if (outStream == null) { throw new ArgumentNullException("outStream"); } #if NETFX_CORE inStream.Seek(0, 0); outStream.Seek(0, 0); IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(options[PasswordOption], BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(SALT); // Derive key material for password size 32 bytes for AES256 algorithm KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); // using salt and 1000 iterations KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); // create a key based on original key and derivation parmaters CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); // derive buffer to be used for encryption salt from derived password key IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); // display the buffers - because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); // create symmetric key from derived password key CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); using (MemoryStream ms = new MemoryStream()) { inStream.CopyTo(ms); // encrypt data buffer using symmetric key and derived salt material IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(ms), saltMaterial); resultBuffer.AsStream().CopyTo(outStream); writtenBytes = outStream.Position; } #else Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(options[PasswordOption], SALT); var key = pdb.GetBytes(32); pdb.Reset(); var iv = pdb.GetBytes(16); using (var transform = encrypter.CreateEncryptor(key, iv)) { using (MemoryStream internalStream = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(internalStream, transform, CryptoStreamMode.Write)) { StreamTools.Write(inStream, csEncrypt); inStream.Flush(); csEncrypt.FlushFinalBlock(); internalStream.Seek(0, 0); StreamTools.Write(internalStream, outStream); writtenBytes = outStream.Position; } } } #endif }