AES256 encription Without RijndaelManaged in .Net core 1.1

1.3k Views Asked by At

I want to do AES256 Encryption in .net core 1.1. RijndaelManaged is not supporting with the .net core 1.1. So I'm using here AES aes = new AES.create()

This part of code create the random private key for the encryption

public string GenaratePassPharse()
    {
        RandomNumberGenerator rngCryptoServiceProvider = RandomNumberGenerator.Create();
        byte[] randomBytes = new byte[KEY_SIZE];
        rngCryptoServiceProvider.GetBytes(randomBytes);
        string plainPassPharse = Convert.ToBase64String(randomBytes);

        return plainPassPharse;
    }

and here the AES() encryption method. What I want to do is pass my generated key (which is return from above method)instead of the aesAlg.Key as an encryption key.

 static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;

        // Create an Aes object
        // with the specified key and IV.
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.BlockSize = 128;
            aesAlg.KeySize = 128;



            // Create an encryptor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }


        // Return the encrypted bytes from the memory stream.
        return encrypted;

    }

And any another way to use AES256 Encryption algorithms?

1

There are 1 best solutions below

0
xanatos On BEST ANSWER

The full code should be:

public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] key, byte[] iv = null)
{
    // Check arguments.
    if (plainText == null)
    {
        throw new ArgumentNullException("plainText");
    }

    if (key == null || key.Length == 0)
    {
        throw new ArgumentNullException("Key");
    }

    // Create an Aes object
    // with the specified key and IV.
    using (Aes aes = Aes.Create())
    {
        aes.Key = key;

        if (iv == null)
        {
            iv = new byte[aes.BlockSize / 8];

            using (RandomNumberGenerator rngCryptoServiceProvider = RandomNumberGenerator.Create())
            {
                rngCryptoServiceProvider.GetBytes(iv);
            }
        }

        // Note that we are setting IV, Mode, Padding
        aes.IV = iv;
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;

        // Create an encryptor to perform the stream transform.
        using (ICryptoTransform encryptor = aes.CreateEncryptor())
        using (MemoryStream ms = new MemoryStream())
        using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
        {
            // Prepend the IV
            cs.Write(iv, 0, iv.Length);

            // Here we are setting the Encoding
            using (StreamWriter sw = new StreamWriter(cs, Encoding.UTF8))
            {
                // Write all data to the stream.
                sw.Write(plainText);
            }

            byte[] encrypted = ms.ToArray();
            return encrypted;
        }
    }
}

public static string DecryptBytesToString_Aes(byte[] encrypted, byte[] key)
{
    // Check arguments.
    if (encrypted == null || encrypted.Length == 0)
    {
        throw new ArgumentNullException("plainText");
    }

    if (key == null || key.Length == 0)
    {
        throw new ArgumentNullException("Key");
    }

    // Create an Aes object
    // with the specified key and IV.
    using (Aes aes = Aes.Create())
    {
        aes.Key = key;

        using (MemoryStream ms = new MemoryStream(encrypted))
        {
            // Read the prepended IV
            var iv = new byte[aes.BlockSize / 8];
            ms.Read(iv, 0, iv.Length);

            // Note that we are setting IV, Mode, Padding
            aes.IV = iv;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            // Create an encryptor to perform the stream transform.
            using (ICryptoTransform decrytor = aes.CreateDecryptor())
            using (CryptoStream cs = new CryptoStream(ms, decrytor, CryptoStreamMode.Read))
            // Here we are setting the Encoding
            using (StreamReader sr = new StreamReader(cs, Encoding.UTF8))
            {
                // Read all data from the stream.
                string plainText = sr.ReadToEnd();
                return plainText;
            }
        }
    }
}

public static byte[] GenerateAesKey(int bits)
{
    using (RandomNumberGenerator rngCryptoServiceProvider = RandomNumberGenerator.Create())
    {
        byte[] key = new byte[bits / 8];
        rngCryptoServiceProvider.GetBytes(key);
        return key;
    }
}

public static void Main()
{
    var key = GenerateAesKey(256);
    var encrypted = EncryptStringToBytes_Aes("Hello", key);
    var decrypted = DecryptBytesToString_Aes(encrypted, key);
}

This code prepend a random IV to the encrypted stream, and the recovers it from the encrypted stream to decrypt the stream.

It is very important that when you speak of encryption you set everything that can be setted. There must be no questions open. The encryption Mode, the Padding, the Encoding the plaintext must be encoded. Everything!