B4A Library Base64 and Encryption library

Discussion in 'Additional libraries, classes and official updates' started by agraham, Dec 10, 2010.

  1. agraham

    agraham Expert Licensed User

    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.

    Attached Files:

    Last edited by a moderator: Apr 11, 2016
    Zayn Arka, walt61, OliverA and 7 others like this.
  2. agraham

    agraham Expert Licensed 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.
  3. SteveBee

    SteveBee Member Licensed 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....

  4. AscySoft

    AscySoft Active Member Licensed User

    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.

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

    agraham Expert Licensed 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.
  6. AscySoft

    AscySoft Active Member Licensed User

    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)
    Dim Bconv As ByteConverter
    Dim key(0As Byte
    Dim data(0As Byte
    Dim iv(0As Byte
       iv = 
    ' use DES for variable length data using padding
       Dim kg As KeyGenerator
    Dim c As Cipher
    "AES/CBC/PKCS5Padding"' replace "DES/" with "AES/" for Rijndael or "DESEDE/" for triple DES
    ' CBC needs an initialisation vector
       c.InitialisationVector = iv
    "AES"' replace "DES" with "AES" for Rijndael or "DESEDE" for triple DES
       key = kg.KeyToBytes
    Msgbox(Bconv.HexFromBytes(key), "Key " & key.Length & " bytes")
       clear = 
    "Hello, World!"
       data = Bconv.StringToBytes(clear, 
       data = c.Encrypt(data, kg.Key, 
    Log("Encoding: " & Bconv.HexFromBytes(data))
    Msgbox(Bconv.HexFromBytes(data), "Encrypted is " & data.Length & " bytes")
       data = c.Decrypt(data, kg.Key, 
    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!
  7. agraham

    agraham Expert Licensed 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.
  8. AscySoft

    AscySoft Active Member Licensed User

    The link is not good...
    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?
  9. agraham

    agraham Expert Licensed User

    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.
  10. elbarto

    elbarto Member Licensed User


    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.


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

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

    agraham Expert Licensed 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.
  12. elbarto

    elbarto Member Licensed 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.
  13. elbarto

    elbarto Member Licensed 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! :)
  14. slowtime

    slowtime Active Member Licensed User


    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
  15. agraham

    agraham Expert Licensed User

    Thanks for asking. Yes, apart from Jpeg, SVG and PageTurnView which incorporate code released under other conditions.

    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.
  16. moster67

    moster67 Expert Licensed User


    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: Jan 23, 2012
  17. agraham

    agraham Expert Licensed 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.
  18. P373R

    P373R Member Licensed User

  19. peacemaker

    peacemaker Well-Known Member Licensed User

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

    Agraham ?
  20. peacemaker

    peacemaker Well-Known Member Licensed User

    Ready code module for cripting passwords

    '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(0As Byte
    Dim data(0As Byte   
    Dim bytes(0As Byte   

       key = 
    Array As Byte(324477158)   'change this for you

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

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

    For i = 0 To padLength - 1
       source = source & paddingChar
    Return source
    End Sub
    Maybe will be useful not only for me.
    Last edited: Mar 15, 2012
    mmieher, toby and patrick14384 like this.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice