/// <summary> /// Decrypts a string. /// </summary> /// <param name="cipherString">The encrypted string.</param> /// <param name="password">Password to create key with</param> /// <param name="salt">Salt to create key with</param> /// <param name="iv">IV</param> /// <param name="keySize">Can be 128, 192, or 256</param> /// <param name="iterationCount">The number of iterations to derive the key.</param> /// <returns>The decrypted string.</returns> public static string Decrypt(string cipherString, string password, string salt, string iv, Bytes.KeySize keySize, int iterationCount) { if (string.IsNullOrEmpty(cipherString)) { throw new ArgumentNullException(nameof(cipherString)); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } if (string.IsNullOrEmpty(salt)) { throw new ArgumentNullException(nameof(salt)); } if (string.IsNullOrEmpty(iv)) { throw new ArgumentNullException(nameof(iv)); } var keyBytes = Bytes.GenerateKey(password, salt, keySize, iterationCount); var ivBytes = Encoding.UTF8.GetBytes(iv); return(Decrypt(cipherString, keyBytes, ivBytes)); }
public void Encrypt_decrypt_using_different_key_sizes(Bytes.KeySize keySize) { const string password = "******"; const string salt = "saltsaltsalt"; var iv = string.Empty.PadLeft(32, '#'); const string original = "My secret text"; var encrypted = Strings.Encrypt(original, password, salt, iv, keySize, 1); var decrypted = Strings.Decrypt(encrypted, password, salt, iv, keySize, 1); Assert.AreEqual(original, decrypted); }
/// <summary> /// Encrypts a string. The password, salt and keySize are all used to generate a key see Bytes.GenerateKey(). /// The iv is converted into a byte array using Encoding.UTF8.GetBytes(iv). /// The other Encrypt() function is then called using the clearString, keyBytes and ivBytes. /// </summary> /// <param name="clearString">The plain text string.</param> /// <param name="password">Password to create key with</param> /// <param name="salt">Salt to create key with</param> /// <param name="iv">IV</param> /// <param name="keySize">Can be 128, 192, or 256</param> /// <param name="iterationCount">The number of iterations to derive the key.</param> /// <returns>The encrypted string.</returns> public static string Encrypt(string clearString, string password, string salt, string iv, Bytes.KeySize keySize, int iterationCount) { if (string.IsNullOrEmpty(clearString)) { throw new ArgumentNullException("clearString"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } if (string.IsNullOrEmpty(salt)) { throw new ArgumentNullException("salt"); } if (string.IsNullOrEmpty(iv)) { throw new ArgumentNullException("iv"); } byte[] keyBytes = Bytes.GenerateKey(password, salt, keySize, iterationCount); byte[] ivBytes = Encoding.UTF8.GetBytes(iv); return(Encrypt(clearString, keyBytes, ivBytes)); }