AES sample

bluedude

Well-Known Member
Licensed User
Longtime User
I want to do AES encryption (there is no support for https it seems) for transmitting data safely from my backend web services to the android client.

I'm using an AES encryption class on the backend and I want to use AES too on the client.

Has anyone done something with the new encryption library how to use it?
 

bluedude

Well-Known Member
Licensed User
Longtime User
Encryption

Looked over the samples but they all use a dynamic generated key. I need something to exchange between my server and mobile client (as probably everyone needs in the end).

A lot of mobile apps. are very unsecure and I´m looking for a way to make the data exchange a little more secure.

From your samples, they tend to be very technical sometimes, I cannot get it done. I basically want to set my own key string both in the client and on the server.

Can you help.
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
The demo shows roundtripping a symmetric key using KeyGenerator.KeyToBytes and KeyGenerator.KeyFromBytes. You could use a hash function to generate a key from a secret string or you could export a key generated by KeyGenerator and (probably) encode it as a hex string for storage using my ByteConverter library. For use you would then convert it back to a byte array and import it with KeyFromBytes.

How you keep that secret key secure and available only in clear to your client and server apps is up to you but just saving it as a file at both client and server is not a good idea unless you are only concerned with eavesdropping of the data in transit. Ideally you would use a public key to encode a randomly generated symmetric session key and send it to the other party that would decode it with their private key. There are in fact standard protocols like SSL that do this but I'm only providing the tools, building the system is up to you.
 
Upvote 0

critalsoft

Member
Licensed User
Longtime User
Something like:
- Load the key which is stored in a file with KeyGenerator.KeyFromBytes.
- Then decrypt the data with Cipher.Decrypt.

Erel.

:sign0085: Can you please share the demo of the same. I want to encrypt and decrypt data by using my custom password. Eg encrypt("some data", mypassword) I am unable to do it. Thanks in advance.
 
Upvote 0

critalsoft

Member
Licensed User
Longtime User
Erel,

I am getting error in the following line:

data = c.Encrypt("some data".GetBytes("UTF8"), kg.Key, False)
java.security.InvalidKeyException: Key length not 128/192/256 bits
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Sorry. My previous code was wrong.
The key length must be of a specific size.
One way you can do it is to first calculate a MD5 hash of the string:
B4X:
Sub Activity_Create(FirstTime As Boolean)
Dim kg As KeyGenerator
kg.Initialize("AES")
Dim md As MessageDigest
Dim p As String
p = "mypassword"
kg.KeyFromBytes(md.GetMessageDigest(p.GetBytes("UTF8"), "MD5"))
Dim c As Cipher
c.Initialize("AES")
Dim data() As Byte
data = c.Encrypt("some data".GetBytes("UTF8"), kg.Key, False)
data = c.Decrypt(data, kg.Key, False)
Msgbox(BytesToString(data, 0, data.Length, "UTF8"), "")
End Sub
 
Upvote 0

AscySoft

Active Member
Licensed User
Longtime User
If I take your code and I slightly modify it, adding initialization vector(IV) and some logs... see below

B4X:
Sub Activity_Create(FirstTime As Boolean)
Dim kg As KeyGenerator
kg.Initialize("AES")
Dim md As MessageDigest
Dim p As String
p = "mypassword"
kg.KeyFromBytes(md.GetMessageDigest(p.GetBytes("UTF8"), "MD5"))
Dim c As Cipher
c.Initialize("AES")
[B][COLOR="Red"]c.InitialisationVector ="@1B2c364e5F6g7H8".GetBytes("UTF8")[/COLOR][/B]
Dim data() As Byte
data = c.Encrypt("some data".GetBytes("UTF8"), kg.Key, [B][COLOR="Red"]True[/COLOR][/B])
[B][COLOR="Red"]Log("CRIPTAT CharsFromBytes: " & Bconv.CharsFromBytes(data))
Log("CRIPTAT HexFromBytes: " & Bconv.HexFromBytes(data))[/COLOR][/B]
data = c.Decrypt(data, kg.Key, [B][COLOR="Red"]True[/COLOR][/B])
Msgbox(BytesToString(data, 0, data.Length, "UTF8"), "")
End Sub

well... the results of this modiffication surprisingly is the same as your previous code, without IV!
Why? I am doing something wrong maybe or is a bug on Encryption class?:sign0148:
 
Last edited:
Upvote 0

agraham

Expert
Licensed User
Longtime User
I'm not really familiar with all the transformations that are possible but it is likely that "AES" defines a single block transformation that does not use an IV. To use this library in any but a non-trivial way you need some familiarity with the Java Cryptography Architecture, links to which are in the help.

As I pointed out before any bugs in the library are highly unlikely as it is a very thin wrapper over the Android implementation of the Java Cryptography Architecture.
 
Upvote 0

AscySoft

Active Member
Licensed User
Longtime User
I finally did it! Took me a while to realize what's going on :BangHead:
The previous AES encryption example was a simple AES/Rijndael encryption, non CBC!
So, on .net framework(or other environment) you need to set Rijndael.mode to ECB!!!
Otherwise inter Op. encoding will not match!
:sign0060:

Just one question remain: how do I transform previous AES/ECB encoding into AES/CBC one(for even stronger security)?
 
Upvote 0

andrewmp

Member
Licensed User
Longtime User
decoding strings

I've been playing with the code by Erel

If I decode and encode the data byte array to and from strings with ByteConverter like this it works:

Dim bt As ByteConverter
Dim r as string
data = c.Encrypt("some data".GetBytes("UTF8"), kg.Key, False)

r=bt.StringFromBytes(data,"ISO-8859-1")
data=bt.StringToBytes(r,"ISO-8859-1")

data = c.Decrypt(data, kg.Key, False)

If I use any other decoding it does not work - does anyone have an idea why? Are the Encrypt/Decrypt functions tied to the device default string encodings?

I need to convert data array to a string to save in a db which is why I am testing with ByteConverter
 
Upvote 0

straybullet

Member
Licensed User
Longtime User
When I use the a string password to generate a key it works fine, but if the string password is different it errors out complaining about main_decrypt javx.crypt BadPaddingException: pad block corrupted


Is there a way to catch this error, of course if the password/padding is bad I want to know, but not error out the app.

Notice I left the letter o out of one of the password prompts to test if a user is using invalid password (key), then you get the error, put the letter o in and it works great



B4X:
Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.

End Sub

Sub Globals
   'These global variables will be redeclared each time the activity is created.
   'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
Dim incsms As String
Dim outsms As String

outsms = Encrypt("hello how are you doing on such a fine day I hope you are enjoying the sun.")
incsms = Decrypt (outsms)

ToastMessageShow(outsms,True)
ToastMessageShow(incsms,True)

End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub


Sub Encrypt(dataToEncrypt As String ) As String 

    Dim kg As KeyGenerator
    Dim c As Cipher
    Dim B64 As Base64
    Dim Bconv As ByteConverter

    Dim data(0) As Byte
    Dim iv(0) As Byte
   
   Dim p As String
   Dim md As MessageDigest
   
   
   
    iv = Array As Byte(211, 22, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
        
    c.Initialize("DESEDE/CBC/PKCS5Padding")     
    c.InitialisationVector = iv
    kg.Initialize("DESEDE") 
    
    'kg.KeyFromBytes(Bconv.StringToBytes("1234567890123456","ASCII"))
    p = "passwrd"
    kg.KeyFromBytes(md.GetMessageDigest(p.GetBytes("UTF8"), "MD5"))
   
    data = Bconv.StringToBytes(dataToEncrypt, "ASCII")        
    data = c.Encrypt(data, kg.Key, True)                

    Return B64.EncodeBtoS(data, 0, data.Length)
    
End Sub 

Sub Decrypt(encryptedData As String ) As String 

    Dim kg As KeyGenerator
    Dim c As Cipher
    Dim B64 As Base64
    Dim Bconv As ByteConverter
    Dim data(0) As Byte
    Dim iv(0) As Byte
   
   Dim p As String
   Dim md As MessageDigest
   
    iv = Array As Byte(211, 22, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
        
    c.Initialize("DESEDE/CBC/PKCS5Padding")     
    c.InitialisationVector = iv
    kg.Initialize("DESEDE")     
    'kg.KeyFromBytes(Bconv.StringToBytes("1234567890123456","ASCII"))
    p = "password"
    kg.KeyFromBytes(md.GetMessageDigest(p.GetBytes("UTF8"), "MD5"))
    
    data = B64.DecodeStoB(encryptedData)
    data = c.Decrypt(data, kg.Key, True)    

    Return Bconv.StringFromBytes(data, "ASCII")

End Sub
 
Upvote 0

straybullet

Member
Licensed User
Longtime User
Thanks, stuck the try, catch, end try in the decrypt sub, seems to have caught the error

Exceptions are the way modern languages like C++, C# and Java report errors. Use a Try .. Catch .. End Try block and check LastException.Message for the reason if necessary.
 
Last edited:
Upvote 0

agraham

Expert
Licensed User
Longtime User
It works like this - from the Exception help in Core.xml
B4X:
You can access the last thrown exception by calling LastException.
For example:
Try
   Dim in As InputStream
   in = File.OpenInput(File.DirInternal, "SomeMissingFile.txt")
   '...
Catch
   Log(LastException.Message)
End Try
If in.IsInitialized Then in.Close
 
Upvote 0

canalrun

Well-Known Member
Licensed User
Longtime User
Hello,
I am adding on to this thread because the earlier discussion is very closely related.

I have a Web server using PHP 5. On Android devices I am using B4A. I need to transfer string data between the two. HTTPS is not available and I would like some amount, even a small amount, of data security.

Both PHP and B4A via the encryption library support AES – perfect solution, but there are many different configuration options and details to work out. My initial attempts don't seem to work.

Would anybody like to share some sample code, or a detailed description, of transferring encrypted data between a Web server using PHP and Android using B4A? I would like to use a short string, maybe 16 characters, known on both devices (PHP and B4A) to serve as the encryption key.

Thanks much,
Barry.
 
Upvote 0

DeerBear

Member
Licensed User
Longtime User
A lot of mobile apps. are very unsecure and I´m looking for a way to make the data exchange a little more secure.
From your samples, they tend to be very technical sometimes, I cannot get it done. I basically want to set my own key string both in the client and on the server.
Can you help.

We can't help making your app more secure.
You can't help either.
It's - mostly - not up to you. Or me. Or anybody.

When you're on the net and want to transmit data SECURELY,
then you REALLY want a certificate AND https.

No other way around it I'm afraid.

Regards,

A
 
Upvote 0
Top