B4i Library iEncryption library

This library supports:
- Generating cryptographically secure random values.
- Hash calculations (message digest)
- Encryption and decryption

Cipher.Encrypt / Decrypt are simple methods that you should use to securely encrypt or decrypt data unless you need to work with other systems. Encrypt2 and Decrypt2 together with GenerateKey give you more options.

Encrypt / Decrypt methods are compatible with B4A and B4J B4XEncryption methods: https://www.b4x.com/android/forum/threads/b4xencryption.48177/#content

Note that if your device has a 64 bit CPU (like most devices) then you need to compile your app in 64 bit mode for this library to work properly: Tools - Builder Server - Server Settings.
In release mode both 64 bit and 32 bit binaries are always included.
 
Last edited:

nw11

Member
Licensed User
Longtime User
B4X:
Sub Get(Text As String, Mode As Int) As String

    If Text = Null OR Text = "" Then Return ""   
   
    Dim key(0) As Byte
    Dim AppK As String
    AppK = KID & KID2 ' my key
    key = AppK.GetBytes("ISO-8859-1")

    Dim data(0) As Byte       
    Dim bytes(0) As Byte       
    Dim Kg As KeyGenerator   
    Dim c As Cipher   
    c.Initialize("DES/ECB/NoPadding")

    Kg.Initialize("DES")
    Kg.KeyFromBytes(key)   
   
    key = Null
    If Mode = 0 Then   
        Text = padString(Text)
        data = Bconv.StringToBytes(Text, "ISO-8859-1")       
        data = c.Encrypt(data, Kg.key, False)       
        key = Null
        Return Bconv.HexFromBytes(data)   
    Else If Mode = 1 Then
        data = Bconv.HexToBytes(Text)       
        bytes = c.Decrypt(data, Kg.key, False)
        key = Null
        Dim AppStr As String
        AppStr = Bconv.StringFromBytes(bytes,"ISO-8859-1").Trim
        bytes = Null
        Return AppStr   
    End If

End Sub

Sub padString(source As String) As String
    Dim paddingChar As String, size, x, padLength As Int
    Dim appSource As String
    Dim k As Int
    For k = 0 To source.Length - 1
        Try
            If Asc(source.SubString2(k, k + 1)) < 256 Then
                appSource = appSource & source.SubString2(k, k + 1)
            Else
                appSource = appSource & " "
            End If
        Catch
            'Log("fine")
        End Try
    Next
    source = appSource
   
    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

Hi Erel, this is my b4a code for crypt/decrypt the message my App actually is using.

now i'm trying to convert all my app in ios.

i have tryed to convert with this code but unfortunally it doesn't work

B4X:
Dim key(0) AsByte
Dim appK AsString

appK = KID & KID2

key = appK.GetBytes("ISO-8859-1")

Dim data(0) AsByte
Dim bytes(0) AsByte

'Dim kg As KeyGenerator
Dim c AsCipher
Dim appK2() AsByte
appK2 = c.GenerateKey(key, "SHA-1", Null, 0)
'c.Initialize("DES/ECB/NoPadding") ' just "DES" actually performs "DES/ECB/PKCS5Padding".    

'kg.Initialize("DES")
'kg.KeyFromBytes(key) 
  
key = Null
If Mode = 0Then
Text = padString(Text)
data = Bconv.StringToBytes(Text, "ISO-8859-1")
'data = c.Encrypt(data, kg.key, False)
data = c.Encrypt2(data, appK2, "DES", Null, 0)
key = Null
ReturnBconv.HexFromBytes(data)
ElseIf Mode = 1Then
data = Bconv.HexToBytes(Text)
'bytes = c.Decrypt(data, kg.key, False)
bytes = c.Decrypt2(data, appK2, "DES", Null, 0)
key = Null
Dim AppStr AsString
AppStr = Bconv.StringFromBytes(bytes,"ISO-8859-1").Trim
bytes = Null
Return AppStr
End If

i don't know if the value "SHA-1" is correct and which values i have to use for then GenerateKey command parameters (IV .. options)

can you please help me ?

thank you in advance

best regards

Fabrizio

nb: sorry for my english
 

nw11

Member
Licensed User
Longtime User
You don't need to use GenerateKey as you are creating the key yourself.

The options parameter (last parameter) should be c.OPTION_ECBMode.

as always .. you are great :) .. now it works .. thank you very much.

Fabrizio
 

Rafael Perez Jurado

Member
Licensed User
Longtime User
Hi,
I have a this problem, I have a APP to android that Encrypt and Decrypt a text, the function are:
B4X:
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 = "M0rtadel0"
    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 = "M0rtadel0"
    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

But I try to make a APP to IPhone that Decryp the same information, the function are:
B4X:
Sub Encrypt(dataToEncrypt As String,key As String) As String
    'Return dataToEncrypt
  
    Dim c As Cipher
    Dim bconv As ByteConverter
    Dim opzioni As Int
    Dim data(0) As Byte
    Dim data2(0) As Byte
    Dim iv(0) As Byte
    iv = Array As Byte(211, 22, 233, 24, 55, 166, 7, 88)
    Dim kgBytes() As Byte
    Dim output As String
  
    Dim pw() As Byte
    pw = bconv.StringToBytes(key, "UTF8")
     kgBytes = c.GenerateKey(pw, "SHA-1", iv, 1)
  
    'kgBytes = key.GetBytes("UTF8")
  
    data = bconv.StringToBytes(dataToEncrypt, "UTF8")   
    opzioni = Bit.Or(c.OPTION_ECBMode, c.OPTION_PKCS7Padding)
    data2 = c.Encrypt2(data, kgBytes, "3DES", iv, opzioni)  ' DESEDE/CBC/PKCS5Padding
  
    Dim s As StringUtils
    output = s.EncodeBase64(data2)
    Return output
End Sub
Sub Decrypt(encryptedData As String,key As String) As String
       Dim c As Cipher
    Dim bconv As ByteConverter
    Dim opzioni As Int
    Dim data(0) As Byte
    Dim data2(0) As Byte
    Dim iv(0) As Byte
    iv = Array As Byte(211, 22, 233, 24, 55, 166, 7, 88) 'not the original iV
    Dim kgBytes() As Byte
    Dim pw() As Byte
    'Dim p As String
    Dim output As String
    'pw = bconv.StringToBytes(key, "UTF8")
    pw = bconv.StringToBytes(key, "UTF8")
    Dim md As MessageDigest
    'pw=md.GetMessageDigest(pw,"MD5")
    'kgBytes = c.GenerateKey(pw,"SHA-1", iv, 1)
  
    kgBytes = md.GetMessageDigest(pw,"MD5")
       Dim s As StringUtils
    data=s.DecodeBase64(encryptedData)
    'data = bconv.StringToBytes(data, "UTF8")  
    opzioni = Bit.Or(c.OPTION_ECBMode, c.OPTION_PKCS7Padding)
    data2 = c.Decrypt2(data, kgBytes,"3DES", iv,opzioni)
    output = bconv.StringFromBytes(data2, "ASCII")
    Return output
   
Sub Button1_Click

'TextField1.Text = Decrypt("Hola", "M0rtadel0")

TextField1.Text = Decrypt("UXjIJMhkl20p49figYVSiiP2wbFn/XOy", "M0rtadel0")

End Sub

I hope you can give me a solution, thanks.
 

Rafael Perez Jurado

Member
Licensed User
Longtime User
Hi,
I downloaded B4XEncryption.zip but this content B4XEncryption.jar,B4XEncryption.xml and when I compile the project I have this error:

b4i_main.h:9:9: fatal error: 'B4XEncryption.h' file not found
#import "B4XEncryption.h"
^
1 error generated.

I don´t know why this file isn´t in to compress file. Do you have B4XEncryption.h?. Thanks.
 

Rafael Perez Jurado

Member
Licensed User
Longtime User
I copy the files to the folder libraries and I mark in the panel Libraries Manager B4XEncription. What do you want I do?. Sorry for the inconvenience. Thanks
 

Rafael Perez Jurado

Member
Licensed User
Longtime User
Ok, Sorry'm still asleep. What algoritm use this method, because I have a project in VB.net and this use 3DES. Thanks
B4X:
Private des As New TripleDESCryptoServiceProvider 'Algorithmo TripleDES
    Private hashmd5 As New MD5CryptoServiceProvider 'objeto md5
    Private myKey As String = "M0rtadel0" 'Clave secreta(puede alterarse)

    'Funcion para el Encriptado de Cadenas de Texto
    Public Function Encriptar(ByVal texto As String) As String

        If Trim(texto) = "" Then
            Encriptar = ""
        Else
            des.Key = hashmd5.ComputeHash((New UnicodeEncoding).GetBytes(myKey))
            des.Mode = CipherMode.ECB
            Dim encrypt As ICryptoTransform = des.CreateEncryptor()
            Dim buff() As Byte = UnicodeEncoding.ASCII.GetBytes(texto)
            Encriptar = Convert.ToBase64String(encrypt.TransformFinalBlock(buff, 0, buff.Length))
        End If
        Return Encriptar
    End Function


    'Funcion para el Desencriptado de Cadenas de Texto
    Public Function Desencriptar(ByVal texto As String) As String
        If Trim(texto) = "" Then
            Desencriptar = ""
        Else
            des.Key = hashmd5.ComputeHash((New UnicodeEncoding).GetBytes(myKey))
            des.Mode = CipherMode.ECB
            Dim desencrypta As ICryptoTransform = des.CreateDecryptor()
            Dim buff() As Byte = Convert.FromBase64String(texto)
            Desencriptar = UnicodeEncoding.ASCII.GetString(desencrypta.TransformFinalBlock(buff, 0, buff.Length))
        End If
        Return Desencriptar
    End Function
 

Rafael Perez Jurado

Member
Licensed User
Longtime User
I use in android for encrypt:
B4X:
Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Main")
    Dim con() As Byte
    con=Encrypt("Hola")
    Dim s As StringUtils
    EditText1.Text = s.EncodeBase64(con)
  
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub Encrypt(dataToEncrypt As String) As Byte()

    Dim cifro As B4XCipher
    Dim B64 As Base64
    Dim ByteArray() As Byte
    ByteArray=cifro.Encrypt(dataToEncrypt.GetBytes("UTF8"), "M0rtadel0")

    Return ByteArray

End Sub

This is the result from android encript "2xR3EfwX/lGKX2NssR5f2RgN9nye/gsgulXd7T/5ZLb3ebflgqhiog=="

And Use in iPhone for decrypt:
B4X:
Sub Decrypt(encryptedData As String,key As String) As String

' Return output

Dim cifro As Cipher

Dim ByteArray() As Byte

Dim result() As Byte



Dim s As StringUtils

result=s.DecodeBase64(encryptedData)

ByteArray=cifro.Decrypt(result,"M0rtadel0")



Return BytesToString(ByteArray, 0, ByteArray.Length, "UTF8")

End Sub

Private Sub Page1_Resize(Width As Int, Height As Int)



End Sub

Private Sub Application_Background



End Sub

Sub Button1_Click

TextField1.Text = Decrypt("2xR3EfwX/lGKX2NssR5f2RgN9nye/gsgulXd7T/5ZLb3ebflgqhiog==", "M0rtadel0")

End Sub

The result is blank.... why?
 

iCAB

Well-Known Member
Licensed User
Longtime User
Hi All

I have this code that I am using with b4A, I need the equivalent for b4i as I am communicating with a .Net Backend system that has a matching algorithm
B4X:
Sub AES_Encrypt(szInputToEncrypt As String, szKey As String, szIV As String) As String
  
    Dim baInputdata() As Byte
    Dim baEncryptedData(0) As Byte
    Dim szEncryptedData As String
  
    Dim baIV(ENC_KEY_LENGTH) As Byte
    Dim baKey(ENC_KEY_LENGTH) As Byte


    ENC_ConvertHexStringTo16ByteArray(szKey, baKey)
    ENC_ConvertHexStringTo16ByteArray(szIV, baIV)
  
    baInputdata = szInputToEncrypt.GetBytes("UTF8")
  
    Dim kg As KeyGenerator ,c As Cipher
    c.Initialize("AES/CBC/PKCS5Padding")

    ' CBC needs an initialisation vector
    c.InitialisationVector = baIV
    kg.Initialize("AES")
    kg.KeyFromBytes(baKey) 'Key

    baEncryptedData = c.Encrypt(baInputdata, kg.key, True)
    szEncryptedData = GeneralLib.StringUtils1.EncodeBase64(baEncryptedData)
  
    'ENC_MyMessagesLog(szEncryptedData)
  
    Return szEncryptedData

End Sub


B4X:
Sub AES_Decrypt(szInputToDecrypt As String, szKey As String, szIV As String) As String
    Dim baInputdata() As Byte
    Dim baDecryptedData(0) As Byte
    Dim szDeccryptedData As String

      Dim baIV(ENC_KEY_LENGTH) As Byte
    Dim baKey(ENC_KEY_LENGTH) As Byte

    ENC_ConvertHexStringTo16ByteArray(szKey, baKey)
    ENC_ConvertHexStringTo16ByteArray(szIV, baIV)

    baInputdata = GeneralLib.StringUtils1.DecodeBase64(szInputToDecrypt)
  
  
    Dim kg As KeyGenerator ,c As Cipher
    c.Initialize("AES/CBC/PKCS5Padding")

    ' CBC needs an initialisation vector
    c.InitialisationVector = baIV
    kg.Initialize("AES")
    kg.KeyFromBytes(baKey) 'Key

    baDecryptedData = c.Decrypt(baInputdata, kg.key, True)
    szDeccryptedData = GeneralLib.ByteConv.StringFromBytes(baDecryptedData, "UTF8")
  
    Return szDeccryptedData
  
End Sub


Please advise
 
Top