public string Encrypt(string plainText, string password) { RijndaelManaged myRijndael = new RijndaelManaged(); string keyPT = password; string saltString = GetRandomSalt().Substring(0, 24); byte[] salt = Encoding.ASCII.GetBytes(saltString); saltString = Convert.ToBase64String(salt); int myIterations = 1000; //Both encrypt and decrypt need to use the same number of iterations for the encryption/decryption to work. Default to 1,000 Rfc2898DeriveBytes derivedBytesKey = new Rfc2898DeriveBytes(keyPT, salt, myIterations); // Sets correct size (/8) myRijndael.Key = derivedBytesKey.GetBytes(myRijndael.KeySize / 8); myRijndael.IV = derivedBytesKey.GetBytes(myRijndael.BlockSize / 8); // Encrypt the string to an array of bytes. byte[] encryptedBytes = EncryptStringToBytesAES(plainText, myRijndael.Key, myRijndael.IV); string encryptedBase64 = Convert.ToBase64String(encryptedBytes); //***** Key/Salt saltString = HexConversion.TextToHex(saltString.Trim()); //***** Encrypted value string encrypted = HexConversion.TextToHex(encryptedBase64.Trim()); //***** Combine the encrypted text with the key/salt and return string encryptedString = encrypted + " " + saltString; return(encryptedString); }
public string GetRandomSalt() { RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); byte[] salt = new byte[32]; //256 bits random.GetBytes(salt); return(HexConversion.BytesToHex(salt)); }
public string Decrypt(string encryptedText, string password) { RijndaelManaged myRijndael = new RijndaelManaged(); string keyPT = password; encryptedText = HexConversion.HexToText(encryptedText); string salt = encryptedText.Substring(encryptedText.Length - 32); //Since the encryption is a random length, the trailing right 32 characters will always be the salt value string encrypted = encryptedText.Substring(0, (encryptedText.Length - 32)).Trim(); byte[] saltBytes = Convert.FromBase64String(salt); int myIterations = 1000; //Both encrypt and decrypt need to use the same number of iterations for the encryption/decryption to work. Default to 1,000 Rfc2898DeriveBytes derivedBytesKey = new Rfc2898DeriveBytes(keyPT, saltBytes, myIterations); // Sets correct size (/8) myRijndael.Key = derivedBytesKey.GetBytes(myRijndael.KeySize / 8); myRijndael.IV = derivedBytesKey.GetBytes(myRijndael.BlockSize / 8); byte[] decryptedBytes = new byte[encrypted.Length]; decryptedBytes = Convert.FromBase64String(encrypted); string decryptedString = DecryptStringFromBytesAES(decryptedBytes, myRijndael.Key, myRijndael.IV); return(decryptedString); }