I have a requirement to decrypt a value that was encrypted on the database using EncryptByPassPhrase, but without accessing the database.
How do I get the encryption key from the passphrase?
I've looked at
Replicate T-SQL DecryptByPassPhrase in C#
and
C# Decrypt bytes from SQL Server EncryptByPassPhrase?
and my code is:
public static string AESDatabaseDecrypt(string encryptedString)
{
passphrase = "S0meFakePassPhrase01234!";
encryptedString = "AQAAAOmuc52dnbVwTqEx1kp+4WhI89LYKHh3jg=="; // temporarily hard coded
// setup encryption settings to match decryptbypassphrase
TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
provider.Key = UTF8Encoding.UTF8.GetBytes(passphrase).Take(16).ToArray(); // stuck on getting key from passphrase
provider.KeySize = 128;
provider.Padding = PaddingMode.Zeros;
// setup data to be decrypted
byte[] encryptedStringAsByteArray = Convert.FromBase64String(encryptedString);
// hack some extra bytes up to a multiple of 8
encryptedStringAsByteArray = encryptedStringAsByteArray.Concat(new byte[] { byte.MinValue, byte.MinValue, byte.MinValue, byte.MinValue }).ToArray(); // add 4 empty bytes to make 32 bytes
MemoryStream encryptedStringAsMemoryStream = new MemoryStream(encryptedStringAsByteArray);
// decrypt
CryptoStream cryptoStream = new CryptoStream(encryptedStringAsMemoryStream, provider.CreateDecryptor(), CryptoStreamMode.Read);
// return the result
StreamReader cryptoStreamReader = new StreamReader(cryptoStream);
string decryptedString = cryptoStreamReader.ReadToEnd();
}