Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aspnet core encrypting and decrypting a string

I am trying to decrypt a string using some pretty standard algorithm.

public static string DecryptString(string cipherText)
{
    string keyString = string.Empty;

    // Check whether the environment variable exists.
    keyString = Environment.GetEnvironmentVariable("EncryptKey");

    if (keyString == null)
    {
        keyString = "E546C8DF278CD5931069B522E695D4F2";
    }

    var fullCipher = Convert.FromBase64String(cipherText);
    using (var aesAlg = Aes.Create())
    {
        byte[] iv = new byte[aesAlg.BlockSize / 8];
        var cipher = new byte[16];

        Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
        Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
        var key = Encoding.UTF8.GetBytes(keyString);

        string result;
        using (var decryptor = aesAlg.CreateDecryptor(key, iv))
        using (var msDecrypt = new MemoryStream(cipher))
        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        using (var srDecrypt = new StreamReader(csDecrypt))
        {
            result = srDecrypt.ReadToEnd();
        }
        return result;
    }
}

I keep getting the error :

System.Security.Cryptography.CryptographicException: Specified padding mode is not valid for this algorithm.

I have tried multiple ways like this

var iv = new byte[16];
var cipher = new byte[16];

Or

var iv = aesAlg.IV;

I still get an error at this point. What am I doing wrong ?

like image 941
w2olves Avatar asked May 01 '17 22:05

w2olves


People also ask

How do I encrypt and decrypt a string in SQL Server?

Now with the help of certificate and master key create SYMMETRIC KEY. Create symmetric key SK1 with algorithm = AES_256 encryption by certificate C1. Once all these KEYs are created in the database, we can use those for encrypting and decrypting data. Below is the script to encrypt the data in the column.


1 Answers

Two changes are required

var cipher = new byte[fullCipher.Length - iv.Length];

and

Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, fullCipher.Length - iv.Length);
like image 129
Clayton Harbich Avatar answered Oct 02 '22 18:10

Clayton Harbich