B4A Library Base64 and Encryption library

Here's a library that, for the moment, can perform Base64 encoding and decoding and symmetric algorithm encryption and decryption. Tested symmetric algorithms are DES, Triple DES and AES (Rijndael).

As the Java encryption rountines are all byte array oriented you will need my ByteConverter library to run the demo.

EDIT :- Version 1.1 posted. Asymmetric algorithms, Signing and MACs now implemented. See post#2 for details.
 

Attachments

  • Encryption1.1.zip
    25.4 KB · Views: 9,055
  • Encryption_java_source.zip
    27.2 KB · Views: 2,180
Last edited by a moderator:

agraham

Expert
Licensed User
Longtime User
Version 1.1 completes the simplified exposure of all the algorithms implemented by the standard Java Cryptography Architecture (JCA). The very basic key management provided is totally insecure and merely allows the saving and restoring of cryptographic keys as byte arrays.

I have not attempted any implementation of secure Key Management nor of Certificate handling. If you really know what you are doing but can't roll your own in Java then I would be happy to try see if I can implement your requirements but I am not going to attempt any generic solution in advance of a real need.
 

SteveBee

Member
Licensed User
Longtime User
Needed an MD5 hash in my code...

Found your Encryption library & dependency.. ran the demos to find out 'how to'... put the files in the Libraries sub-folder.. substituted my 'seed' for yours and there we are: your MD5 hash matches the one my ASP.NET function does.

All up, about half-an-hour from go to whoa....

:sign0098:
 

AscySoft

Active Member
Licensed User
Longtime User
Hi
I just need to encrypt/decrypt a text file.
My application must be able to encrypt under Android OS and another application must decrypt this file using NET framework(WINDOWS), and vice versa. So, which encoding is the best and compatible between this two systems?

I only ask this because you must know the answer and will save me of many hours of trying.

Thanks.
PS: if it's a lazy question then ignore it, but I'm new to encoding(also in windows)!
 

AscySoft

Active Member
Licensed User
Longtime User
The hash and encryption algorithms are standardised. Use whatever suits the level of security you need, Rijndael/AES with CBC is a good bet for a file.

Thanks for this, but I'm afraid I'm still a noob when coming to this..
So let's say I need to encrypt the text "Hello, World!" using ASE/CBC.
I also use initialization vector from 16bytes string say "@1B2c3D4f5F6g7H8"
To make this standard I would also need a PassPhrase from which a pseudo-random password will be derived. The derived password will be used to generate the encryption key. PassPhrase can be any string and it's value must be kept in secret.

Recap: we have a clear text = "Hello, World!"
Algorithm will be AES/CBC
iv = "@1B2c3D4f5F6g7H8".GetBytes("UTF8") 'Initialization vector
PassPhrase = "Pa$$word" 'must be secret, but here is for example

Now comes the big question: how do I use this to encrypt text?
I know to encrypt this but without the passPhrase like in this example(from your code)
B4X:
        Dim Bconv As ByteConverter
        Dim key(0) As Byte
   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = "@1B2c3D4f5F6g7H8".GetBytes("UTF8")
   ' use DES for variable length data using padding
   Dim kg As KeyGenerator
   Dim c As Cipher
   c.Initialize("AES/CBC/PKCS5Padding") ' replace "DES/" with "AES/" for Rijndael or "DESEDE/" for triple DES
   
   ' CBC needs an initialisation vector
   c.InitialisationVector = iv
   kg.Initialize("AES") ' replace "DES" with "AES" for Rijndael or "DESEDE" for triple DES
   kg.GenerateKey
   key = kg.KeyToBytes
   Msgbox(Bconv.HexFromBytes(key), "Key " & key.Length & " bytes")
   
   clear = "Hello, World!"
   data = Bconv.StringToBytes(clear, "UTF8")
   data = c.Encrypt(data, kg.Key, True)
   Log("Encoding: " & Bconv.HexFromBytes(data))
   Msgbox(Bconv.HexFromBytes(data), "Encrypted is " & data.Length & " bytes")
   data = c.Decrypt(data, kg.Key, True)
   Log("Decoding: " & Bconv.StringFromBytes(data, "UTF8"))
   Msgbox(Bconv.StringFromBytes(data, "UTF8"), "Decrypted")

But how can I generate key for encoding/decoding from PassPhrase?

Sorry if I misunderstand something, and BIG thanks in advance!
 

agraham

Expert
Licensed User
Longtime User
I ducked out of exposing any password based encryption functionality in the library, mainly because I know that I don't fully understand it. http://www.ietf.org/rfc/rfc2898.txt.

Unless you really need pasword based encryption I would recomment you use a key generated by Keygenerator.GenerateKey which is assured to be a random value.
 

AscySoft

Active Member
Licensed User
Longtime User
I ducked out of exposing any password based encryption functionality in the library, mainly because I know that I don't fully understand it. http://www.ietf.org/rfc/rfc2898.txt.
The link is not good...
Unless you really need password based encryption I would recommend you use a key generated by Keygenerator.GenerateKey which is assured to be a random value.
I see, but I wanna encode a file, send it to PC and the decode it there. Also encode a file on PC, retrieve it on Android and decode it.
If I would encode "by Keygenerator.GenerateKey", how am I suppose to decode it on PC because key is random? Sending the key means encryption was in vain.:BangHead:

So, how do I solve this problem?
 

agraham

Expert
Licensed User
Longtime User
how am I suppose to decode it on PC because key is random?
You only generate the key once, or whenever you want to change it. Then when you have it you can represent it as a hex string and use it just like you would a password which needs to be known at both ends.

The reason I don't know much about password based encryption is that all the security work I did involved using directly generated random encrypted secret keys and our key management systems were based around that. No human ever saw any of our secret keys, they were generated in three parts by our key loaders and transported and entered separately into the encryption kit by three trusted employees.
 

elbarto

Member
Licensed User
Longtime User
Sha-256

Hello together,

can it be, that there is a problem in the library with SHA-256? I get different results in Java and in B4A.

Java:

B4X:
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] input = digest.digest(bytes);

B4A:

B4X:
Dim Result1() As Byte
Dim Encrypt1 As MessageDigest
Result1 = Encrypt1.GetMessageDigest(ByteConverter1.StringToBytes(StringResult1, "UTF8"), "SHA-256")
 

agraham

Expert
Licensed User
Longtime User
You don't seem to be comparing like with like. One is a a byte array, the other is a UTF-8 String converted to bytes, you may have an encoding problem. You need to perform both with the same known byte array contents as a check. I doubt if there is a problem as the library is a very thin wrapper over the Java so if you do the same things you should get the same result.
 

elbarto

Member
Licensed User
Longtime User
Maybe it is a problem with special characters? In the screenshot you can see the String as it goes in and then as it comes out.
b1cd6534582949f78d81c10261e41396.jpg
 

elbarto

Member
Licensed User
Longtime User
... my error. Now I did everything with the ByteConverter (ArrayCopy instead of adding Strings and converting the result to Byte) and it works. Thank you! :)
 

slowtime

Active Member
Licensed User
Longtime User
Hi,

I'd like use your libraries (Byte converter, Dialogs,Encryption) in a commercial application.

Are all released under cc 3 ?

How I must attribute the use of libraries to you ?

Thank you.


ps: very useful libraries
 

agraham

Expert
Licensed User
Longtime User
Are all released under cc 3 ?
Thanks for asking. Yes, apart from Jpeg, SVG and PageTurnView which incorporate code released under other conditions.

How I must attribute the use of libraries to you ?
If you have an "About" menu item then just add

"This application uses one or more libraries written by Andrew Graham."

or something similar if you don't like that exact wording.
 

moster67

Expert
Licensed User
Longtime User
Agraham,

I am looking for a way to encrypt some png-images (icons to be used in my app). The reason is that they will be stored on the SD-card and logically this means that said png-files can be easily copied to another location. The person furnishing the icons wants them protected somehow.

I think the best solution is to encrypt said images (will be encrypted by the creator and available as a separate download) and then while loading them, have them decrypted. I am a complete noob what regards encryption (and even more as to understanding it in depth). Articles I found using Google, suggested to use CipherInputStream and CipherOutputStream for this purpose. And to my surprise (although I shouldn't be), I noted that you had already written a library which I probably can use. Thanks!

However, before downloading the example-project and trying to understand how to implement it, I am wondering if the decryption-process is very time-consuming and memory-hungry. I am asking since my app will populate a listview (or a scrollview) with perhaps 30-40 png-images (10-15 kb each). Doing this without any decryption involved is real quick but would decrypting slow it down much?

Many thanks in advance for any useful information I may get.
 
Last edited:

agraham

Expert
Licensed User
Longtime User
Encryption is not memory hungry but does have a performance overhead. You will have to try it to see how it impacts your application -if you only do it once it's probably OK and if you are downloading the images that will probably take longer than doing the decryption.
 

peacemaker

Expert
Licensed User
Longtime User
Seems, for encription the padding up to 8 or 16 bytes is required before using .Encrypt.

TextToBeEcripted = padString(TextToBeEcripted)
data = Bconv.StringToBytes(TextToBeEcripted, "UTF8")
data = c.Encrypt(data, Kg.key, False)

Sub padString(source As String) As String
Dim paddingChar As String, size, x, padLength As Int
paddingChar = " "
size = 16
x = source.Length Mod size
padLength = size - x

For i = 0 To padLength - 1
source = source & paddingChar
Next
Return source
End Sub

Agraham ?
http://stackoverflow.com/questions/6547214/java-decrypt-error-data-not-block-size-aligned
 

peacemaker

Expert
Licensed User
Longtime User
Ready code module for cripting passwords

B4X:
'Code module
'Subs in this code module will be accessible from all modules.
Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.
   Dim Bconv As ByteConverter
End Sub

Sub Get(Text As String, Mode As Int) As String   'mode= 0/1 = encode/decode
   If Text = Null OR Text = "" Then Return ""
   Dim key(0) As Byte
   Dim data(0) As Byte   
   Dim bytes(0) As Byte   

   key = Array As Byte(3, 2, 4, 4, 7, 7, 15, 8)   'change this for you

   Dim Kg As KeyGenerator
   Dim c As Cipher
   c.Initialize("DES/ECB/NoPadding") ' just "DES" actually performs "DES/ECB/PKCS5Padding". 
   Kg.Initialize("DES")
   Kg.KeyFromBytes(key)
   If Mode = 0 Then   
      Text = padString(Text)
      data = Bconv.StringToBytes(Text, "UTF8")
      data = c.Encrypt(data, Kg.key, False)
      Return Bconv.HexFromBytes(data)
   Else If Mode = 1 Then
      data = Bconv.HexToBytes(Text)
      bytes = c.Decrypt(data, Kg.key, False)
      Return Bconv.StringFromBytes(bytes,"UTF8").Trim
   End If
End Sub

Sub padString(source As String) As String
Dim paddingChar As String, size, x, padLength As Int
paddingChar = " "
size = 16
x = source.Length Mod size
padLength = size - x

For i = 0 To padLength - 1
   source = source & paddingChar
Next
Return source
End Sub

Maybe will be useful not only for me.
 
Last edited:
Top