C # equivalent DecryptByPassPhrase

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=="; // 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();
}
+4
source share
1 answer

Well, I mean, the first thing that strikes me is that you are not actually returning a value from your method. Try adding return decryptedString;to the end and see what you get.

0
source

Source: https://habr.com/ru/post/1540243/


All Articles