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 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)); }
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); }
/** * 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 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); }
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 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); }
/// <summary> /// password-based key derivation functionality, PBKDF2, by using a pseudo-random number generator based on HMACSHA1. /// </summary> /// <param name="password">The password used to derive the key.</param> /// <param name="salt">The key salt used to derive the key.</param> /// <param name="iterations">The number of iterations for the operation.</param> /// <returns>The generated pseudo-random key.</returns> public static byte[] Rfc2898DeriveBytes(this string password, byte[] salt, uint iterations, uint cb) { var alg = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); var cryptoKey = alg.CreateKey(XmppEncoding.Utf8.GetBytes(password).AsBuffer()); var keyParams = KeyDerivationParameters.BuildForPbkdf2(salt.AsBuffer(), iterations); return(CryptographicEngine.DeriveKeyMaterial(cryptoKey, keyParams, cb).ToArray()); }
/// <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"; }
private async Task <byte[]> DecryptDataV2(byte[] encryptedData, string pw, string salt) { //var semaphore = GetSemaphore("default"); //await semaphore.WaitAsync(); try { var pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); var saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); var cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptedData); // Derive key material for password size 32 bytes for AES256 algorithm var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); // using salt and 1000 iterations var pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); // create a key based on original key and derivation parmaters var keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); var keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); var derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); // derive buffer to be used for encryption salt from derived password key var saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); // display the keys – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately //var keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); //var saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); var symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); // create symmetric key from derived password material var symmKey = symProvider.CreateSymmetricKey(keyMaterial); //GC.Collect(); // encrypt data buffer using symmetric key and derived salt material var resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial); //GC.Collect(); var result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer); //GC.Collect(); var byteArray2 = Convert.FromBase64String(result); if (byteArray2?.Length > 1000000) { GC.Collect(); } return(byteArray2); } catch (Exception ex) { return(null); } finally { //semaphore.Release(); } }
private static Tuple <IBuffer, IBuffer> DeriveKeyAndSalt(string key, string salt, uint iterationCount) { var keyBuffer = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); var saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8); var pbkdf2Sha512 = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512); var derivedKeyBuffer = CryptographicEngine.DeriveKeyMaterial(pbkdf2Sha512.CreateKey(keyBuffer), KeyDerivationParameters.BuildForPbkdf2(saltBuffer, iterationCount), keySize); var derivedSaltBuffer = CryptographicEngine.DeriveKeyMaterial(pbkdf2Sha512.CreateKey(derivedKeyBuffer), KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 8), keySize); return(new Tuple <IBuffer, IBuffer>(derivedKeyBuffer, derivedSaltBuffer)); }
private const int KeyLength = 32; // 32 bytes public byte[] DeriveKey(byte[] password, byte[] salt, uint rounds) { var buffSalt = salt.AsBuffer(); var buffPassword = password.AsBuffer(); var provider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256); var pbkdf2Params = KeyDerivationParameters.BuildForPbkdf2(buffSalt, rounds); var keyOriginal = provider.CreateKey(buffPassword); var keyDerived = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Params, KeyLength); return(keyDerived.ToArray()); }
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); }
/// <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 static IBuffer GeneratePBKDF2( string password, IBuffer salt, UInt32 targetSize, UInt32 iterationCount) { var keyParams = KeyDerivationParameters.BuildForPbkdf2(salt, iterationCount); var provider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); var key = provider.CreateKey(passwordBuffer); return(CryptographicEngine.DeriveKeyMaterial(key, keyParams, targetSize)); }
//static readonly string DefaultAlgorithm = SymmetricAlgorithmNames.AesEcbPkcs7; public static CryptographicKey CreateKey(String strPassword, byte[] strSalt, UInt32 iterationCount = 10000, String AlgorithmName = null) { //declares var strAlgName = AlgorithmName != null ? AlgorithmName : DefaultAlgorithm; var keygenAlgorithmName = KeyDerivationAlgorithmNames.Pbkdf2Sha512; uint keySize = 64; //must match algo //sanity checks if (strSalt == null) { strSalt = new byte[keySize]; } if (strSalt.Length != keySize) { Array.Resize(ref strSalt, (int)keySize); } // Open the specified algorithm. var objKdfProv = KeyDerivationAlgorithmProvider.OpenAlgorithm(keygenAlgorithmName); // Create a buffer that contains the secret used during derivation. var buffSecret = CryptographicBuffer.ConvertStringToBinary(strPassword, BinaryStringEncoding.Utf8); // Create a random salt value. var buffSalt = CryptographicBuffer.CreateFromByteArray(strSalt); // Create the derivation parameters. var pbkdf2Params = KeyDerivationParameters.BuildForPbkdf2(buffSalt, iterationCount); // Create a key from the secret value. var keyOriginal = objKdfProv.CreateKey(buffSecret); // Derive a key based on the original key and the derivation parameters. var keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Params, keySize); // Demonstrate checking the iteration count. var iterationCountOut = pbkdf2Params.IterationCount; // Create a key by using the KDF parameters. var objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); var key = objAlg.CreateSymmetricKey(keyMaterial); //return key return(key); }
/// <summary> /// Génère les clés de chiffrement AES nécéssaire au chiffrement ou au déchiffrement /// </summary> /// <param name="password">le mot de passe</param> /// <param name="salt">la complexification du mot de passe</param> /// <param name="iterationCount">le nombre de passage</param> /// <param name="keyMaterial">le buffer du mot de passe de sorti</param> /// <param name="iv">le buffer du vecteur de sorti</param> private static void GenerateKeyMaterial(string password, string salt, uint iterationCount, out IBuffer keyMaterial, out IBuffer iv) { var pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); var saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); var pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, iterationCount); var keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); var derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); iv = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); }
public override void Encrypt(Stream input, Stream output, string password, int bufferSize) { input.Position = 0; #if NETFX_CORE // Generate an IV and write it to the output. var iv = CryptographicBuffer.GenerateRandom(ivSize); output.Write(iv.ToArray(), 0, ivSize); var pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(iv, pwIterations); // Create a key based on original key and derivation parmaters CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, keySize); var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); var key = provider.CreateSymmetricKey(keyMaterial); // Get the input stream as an IBuffer. IBuffer msg; using (var ms = new MemoryStream()) { input.CopyTo(ms); msg = ms.ToArray().AsBuffer(); } var buffEncrypt = CryptographicEngine.Encrypt(key, msg, iv); output.Write(buffEncrypt.ToArray(), 0, (int)buffEncrypt.Length); output.Dispose(); #else using (var alg = Aes.Create()) { alg.Mode = CipherMode.CBC; alg.Padding = PaddingMode.PKCS7; alg.GenerateIV(); var key = new Rfc2898DeriveBytes(password, alg.IV, pwIterations); alg.Key = key.GetBytes(keySize); // Write the IV to the output stream. output.Write(alg.IV, 0, ivSize); using (var encryptor = alg.CreateEncryptor()) using (var cs = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) CopyStream(input, cs, bufferSize); } #endif }
private byte[] DecryptDataV2(byte[] encryptedData, string pw, string salt) { try { var pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); var saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); var cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptedData); // Derive key material for password size 32 bytes for AES256 algorithm var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); // using salt and 1000 iterations var pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); // create a key based on original key and derivation parmaters var keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); var keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); var derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); // derive buffer to be used for encryption salt from derived password key var saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); // display the keys – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately //var keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); //var saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); var symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); var symmKey = symProvider.CreateSymmetricKey(keyMaterial); var resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial); var result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer); var byteArray2 = Convert.FromBase64String(result); return(byteArray2); } catch (Exception ex) { _loggingService.WriteLine <App>(ex.Message, LogLevel.Error, ex); return(new byte[0]); } }
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); }
public override void Decrypt(Stream input, Stream output, string password, int bufferSize) { #if NETFX_CORE var thisIV = new byte[ivSize]; input.Read(thisIV, 0, ivSize); var iv = thisIV.AsBuffer(); var pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(iv, pwIterations); // Create a key based on original key and derivation parameters. CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, keySize); var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); var key = provider.CreateSymmetricKey(keyMaterial); // Get the input stream as an IBuffer. IBuffer msg; using (var ms = new MemoryStream()) { input.CopyTo(ms); msg = ms.ToArray().AsBuffer(); } var buffDecrypt = CryptographicEngine.Decrypt(key, msg, iv); output.Write(buffDecrypt.ToArray(), 0, (int)buffDecrypt.Length); #else using (var alg = Aes.Create()) { var thisIV = new byte[ivSize]; input.Read(thisIV, 0, ivSize); alg.IV = thisIV; var key = new Rfc2898DeriveBytes(password, alg.IV, pwIterations); alg.Key = key.GetBytes(keySize); using (var decryptor = alg.CreateDecryptor()) using (var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read)) CopyStream(cryptoStream, output, bufferSize); } #endif output.Position = 0; }
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); }
private KeyMaterial(SecureString password, byte[] salt, int iterations) { if (iterations < 1000) { throw new SecurityException("The KDF iterations should not be lower than 1000"); } if (password == null) { throw new ArgumentNullException(nameof(password)); } if (salt == null) { throw new ArgumentNullException(nameof(salt)); } // Possibly security critical #if WINDOWS_UWP var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password.GetString(), BinaryStringEncoding.Utf8); var saltBuffer = CryptographicBuffer.CreateFromByteArray(salt); var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); var pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, (uint)iterations); var keyOriginal = keyDerivationProvider.CreateKey(passwordBuffer); var keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); var derivedPasswordKey = keyDerivationProvider.CreateKey(passwordBuffer); this.key = keyMaterial.ToArray().ZipAsBytes(); this.initialisationVector = keyMaterial.ToArray().GetBytes(16).ZipAsBytes(); #else using (Rfc2898DeriveBytes keyMaterial = new Rfc2898DeriveBytes(password.GetString(), salt, iterations)) { this.key = keyMaterial.GetBytes(32).ZipAsBytes(); keyMaterial.Reset(); this.initialisationVector = keyMaterial.GetBytes(16).ZipAsBytes(); } #endif this.salt = salt.ZipAsBytes(); // Let us pin our variables so that the GC is not moving them around creating a lot of copies this.saltHandle = GCHandle.Alloc(this.salt, GCHandleType.Pinned); this.initialisationVectorHandle = GCHandle.Alloc(this.initialisationVector, GCHandleType.Pinned); this.keyHandle = GCHandle.Alloc(this.key, GCHandleType.Pinned); }
/// <summary> /// Turns string password into a hash for use in AES /// TODO remove magic numbers /// </summary> /// <param name="password"></param> public async Task CreateAesKey(string password) { var hashProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512); var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); var salt = await GetSalt(); //var salt = await GenerateAndSaveSalt(); var keyCreationParameters = KeyDerivationParameters.BuildForPbkdf2(salt, 1000); var originalKey = hashProvider.CreateKey(passwordBuffer); var hashedKeyMaterial = CryptographicEngine.DeriveKeyMaterial(originalKey, keyCreationParameters, 32); var aesProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesGcm); var key = aesProvider.CreateSymmetricKey(hashedKeyMaterial); aesKey = key; }
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); }
private IBuffer PBKDF2(IBuffer buffSecret, IBuffer buffSalt) { var algorithm = KeyDerivationAlgorithmNames.Pbkdf2Sha256; var iterationCountIn = 100000u; var targetSize = 32u; var provider = KeyDerivationAlgorithmProvider.OpenAlgorithm(algorithm); var pbkdf2Params = KeyDerivationParameters.BuildForPbkdf2(buffSalt, iterationCountIn); var keyOriginal = provider.CreateKey(buffSecret); var keyDerived = CryptographicEngine.DeriveKeyMaterial( keyOriginal, pbkdf2Params, targetSize ); return(keyDerived); }
/// <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); }