AES Key and IV generate with 16 character length

I am searching for how to generate AES key and IV in vb.net.
As above link, there is the declaration for AesIV and AesKey.
But I don't want to use hard code for AesIV and AesKey.

Private Const AesIV As String = "!QAZ2WSX#EDC4RFV"
Private Const AesKey As String = "5TGB&YHN7UJM(IK<" 

What I want to do is I want to generate random key and IV automatically exactly the same 16character like above example.
Please help me somebody. Thanks...

1

2 Answers

Use the RNGCryptoServiceProvider to generate cryptographically strong sequences.

Imports System.Security.Cryptography
Public Function GenerateKey(ByVal Length As Integer) As Byte() Dim ReturnArray(Length - 1) As Byte Using RNG As New RNGCryptoServiceProvider RNG.GetBytes(ReturnArray) End Using Return ReturnArray
End Function

Example usage:

AES.Key = GenerateKey(16)
AES.IV = GenerateKey(16)

NOTE: You must use the exact same key and IV to decrypt the data again, so you must be able to get it back somehow.

3

The Aes class has inbuilt capabilities to do this. aes.GenerateKey() replaces the current key with a new random one (of size aes.KeySize). aes.GenerateIV() replaces the current IV with a new random one (of the block size, which is always 16 bytes for AES).

Note that a default instance of the Aes class already has a randomly generated key and a randomly generated IV.

(And this answer actually applies to any SymmetricAlgorithm type in .NET).

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like