I have a requirement to decrypt a value that was encrypted in the database using EncryptByPassPhrase, but without access to the database.
How to get an encryption key from a passphrase?
I watched
T-SQL DecryptByPassPhrase Replication 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==";
TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
provider.Key = UTF8Encoding.UTF8.GetBytes(passphrase).Take(16).ToArray();
provider.KeySize = 128;
provider.Padding = PaddingMode.Zeros;
byte[] encryptedStringAsByteArray = Convert.FromBase64String(encryptedString);
encryptedStringAsByteArray = encryptedStringAsByteArray.Concat(new byte[] { byte.MinValue, byte.MinValue, byte.MinValue, byte.MinValue }).ToArray();
MemoryStream encryptedStringAsMemoryStream = new MemoryStream(encryptedStringAsByteArray);
CryptoStream cryptoStream = new CryptoStream(encryptedStringAsMemoryStream, provider.CreateDecryptor(), CryptoStreamMode.Read);
StreamReader cryptoStreamReader = new StreamReader(cryptoStream);
string decryptedString = cryptoStreamReader.ReadToEnd();
}
Kaido source
share