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...
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 FunctionExample 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.
3The 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).