Android Code Snippet AES 128 Key generation

Instead of generating AES keys using just Agraham's Encryption library:

B4X:
Dim key As KeyGenerator
key.Initialize("AES")
key.GenerateKey

We can improve it, specify the length of the key (128, 192 or 256) and the Bouncy Castle provider using Javaobject and Reflection library:

B4X:
Dim key As KeyGenerator
Dim r As Reflector
Dim o As JavaObject = r.RunStaticMethod("javax.crypto.KeyGenerator", "getInstance", Array("AES", "BC"), Array As String("java.lang.String", "java.lang.String"))
o.RunMethod("init", Array As Object(128))
key.key = o.RunMethod("generateKey", Null)

Replace 128 by the desired length. This may be needed because different Android implementations may generate by default 128 or 192 bit keys.
 
Top