3

I am searching for how to generate AES key and IV in vb.net.
http://programmers-en.high-way.info/vb/aes.html
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...

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
Kingston
  • 549
  • 1
  • 8
  • 21
  • If you look at [MSDN](https://msdn.microsoft.com/en-us/library/system.security.cryptography.aescryptoserviceprovider(v=vs.110).aspx) you'll see there is a `GenerateIV()` method built in to the provider. Ditto for the Key. You need to retain the Key in order to Decrypt. – Ňɏssa Pøngjǣrdenlarp Mar 03 '17 at 14:36

2 Answers2

4

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.

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
  • Thanks for your answer @Visual Vincent. I will try as you said. – Kingston Mar 03 '17 at 08:41
  • 2
    Note: do **not** directly treat the result as a string as you do in your question, or you may loose key / IV information and therefore your encrypted plaintext. – Maarten Bodewes Mar 03 '17 at 12:35
  • 2
    Note: The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption. It's important to generate a fresh random IV when the key stays the same for multiple encryptions. – Artjom B. Mar 03 '17 at 17:26
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).

bartonjs
  • 30,352
  • 2
  • 71
  • 111