Android Question encryptions file

FHEBERT

Member
Licensed User
Longtime User
Hello,
I would like to encrypt and decrypt text file.
I use this code :

B4X:
Sub btnMd5_Click

    'Code module
  
    Dim mode As Int=0
    Dim text As String="test de cryptage"
  
Get(text , mode )
Dim code As String=Get(text , mode )

mode=1
Get(code , mode )
Dim code1 As String=Get(text , mode )
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
  Dim iv(0) As Byte
  Dim sSecretKey As String = "ysatisfh"
    iv = Bconv.StringToBytes(sSecretKey,"ISO-8859-1")
  key = Bconv.StringToBytes(sSecretKey,"ISO-8859-1")

  Dim Kg As KeyGenerator
  Dim c As Cipher
  c.InitialisationVector = iv
  c.Initialize("DES/CBC/PKCS5Padding") ' 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, True)
      Return Bconv.HexFromBytes(data)
  Else If Mode = 1 Then
      data = Bconv.HexToBytes(Text)
      bytes = c.Decrypt(data, Kg.key, True)
      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

But I have a error when I decrypt : BadPaddingException: pad block corrupted.
I don't see the reason.

Thank for your help.
 

FHEBERT

Member
Licensed User
Longtime User
Why don't you use KeyValueStore or RandomAccessFile.WriteEncryptedObject?
Because I would like to be compatible with VB.net program.
See VB.net code here :

B4X:
 Sub EncryptFile(ByVal sInputFilename As String, _
                  ByVal sOutputFilename As String, _
                  ByVal sKey As String)
        Try

       
            Dim fsInput As New FileStream(sInputFilename, _
                                        FileMode.Open, FileAccess.Read)
            Dim fsEncrypted As New FileStream(sOutputFilename, _
                                        FileMode.Create, FileAccess.Write)

            Dim DES As New DESCryptoServiceProvider()

            'Définit la clé secrète pour l'algorithme DES.
            'Une clé de 64 bits et un vecteur d'initialisation sont requis pour ce fournisseur
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)

            'Définit le vecteur d'initialisation.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)

            'crée un crypteur DES à partir de cette instance
            Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
            'Crée un flux de cryptage qui transforme le flux de fichier à l'aide du cryptage DES
            Dim cryptostream As New CryptoStream(fsEncrypted, _
                                                desencrypt, _
                                                CryptoStreamMode.Write)

            'Lit le texte du fichier dans le tableau d'octets
            Dim bytearrayinput(fsInput.Length - 1) As Byte
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
            'écrit le fichier crypté à l'aide de DES
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
            cryptostream.Close()
            fsInput.Close()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        DecryptFile(access_file, access_file_open, sSecretKey)
    End Sub

    Sub DecryptFile(ByVal sInputFilename As String, _
        ByVal sOutputFilename As String, _
        ByVal sKey As String)

        Try


            Dim DES As New DESCryptoServiceProvider()
            'Une clé de 64 bits et un vecteur d'initialisation sont requis pour ce fournisseur.
            'Définit la clé secrète pour l'algorithme DES.
            DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
            'Définit le vecteur d'initialisation.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)

            'crée un flux de fichier pour lire le fichier crypté de retour
            Dim fsread As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
            'crée un décrypteur DES à partir de l'instance DES
            Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor()
            'crée un flux de cryptage, défini pour lire et effectuer une transformation
            'de décryptage DES sur les octets entrants
            Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
            'imprime le contenu du fichier décrypté
            Dim fsDecrypted As New StreamWriter(sOutputFilename)
            fsDecrypted.Write(New StreamReader(cryptostreamDecr).ReadToEnd)
            fsDecrypted.Flush()
            fsDecrypted.Close()
            fsread.Close()

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
This code works:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Log(Get(Get("test de cryptage", 0), 1))
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
  Dim iv(0) As Byte
  Dim sSecretKey As String = "ysatisfh"
  iv = Bconv.StringToBytes(sSecretKey,"ISO-8859-1")
  key = Bconv.StringToBytes(sSecretKey,"ISO-8859-1")

  Dim Kg As KeyGenerator
  Dim c As Cipher
  c.InitialisationVector = iv
  c.Initialize("DES/CBC/PKCS5Padding") ' 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, True)
  Return Bconv.HexFromBytes(data)
  Else
  data = Bconv.HexToBytes(Text)
  bytes = c.Decrypt(data, Kg.key, True)
  Return Bconv.StringFromBytes(bytes,"UTF8").Trim
  End If
End Sub
It first encrypts the text and then decrypts it.
 
Upvote 0

FHEBERT

Member
Licensed User
Longtime User
Thanks a lot,
I have saw my error.
In my original code I had :

kg.GenerateKey
key = kg.KeyToBytes

I have save file in Hexa format.
But I would like to write en read in ASCII format.

Here my code in Hexa format file

B4X:
Sub Decrypt_file

    Dim key(0) As Byte
    Dim iv(0) As Byte
    Dim sSecretKey As String = "ysatisfh"
    Dim filename_cx As String ="info_collecte_HM1_dec.txt"
   
       
    iv = Bconv.StringToBytes(sSecretKey,"ISO-8859-1")
    key = Bconv.StringToBytes(sSecretKey,"ISO-8859-1")
       
    ' use DES for variable length data using padding
    Dim kg As KeyGenerator
    Dim c As Cipher
    c.Initialize("DES/CBC/PKCS5Padding") ' replace "DES/" with "AES/" for Rijndael or "DESEDE/" for triple DES
   
   
   
    'Lecture du fichier
    Dim data_hexa As String
    Dim array_bin(0) As Byte
 
    Dim reader As TextReader
    reader.Initialize(File.OpenInput(File.DirDefaultExternal,filename_cx))
    data_hexa= reader.ReadAll
    reader.Close
    array_bin= Bconv.HexToBytes(data_hexa)
   
    ' CBC needs an initialisation vector
    c.InitialisationVector = iv
    kg.Initialize("DES") ' replace "DES" with "AES" for Rijndael or "DESEDE" for triple DES
    kg.KeyFromBytes(key)
   
    Dim data_decode(0) As Byte  =Bconv.StringToBytes(data_hexa,"ISO-8859-1")
   
    Dim writer As TextWriter
    writer.Initialize(File.OpenOutput(File.DirDefaultExternal,"info_collecte_HM2_dec.txt",False))
   
    For i=0 To data_decode.Length-1
        writer.WriteLine(data_decode(i))
    Next
    writer.Close
   
   
    data_decode = c.Decrypt(array_bin, kg.key, True)   
    Msgbox(Bconv.StringFromBytes(data_decode, "UTF8"), "Decrypted")
   

End Sub
Sub Encrypt_file

    Dim key(0) As Byte
    Dim data(0) As Byte
    Dim iv(0) As Byte
    Dim sSecretKey As String = "ysatisfh"
    Dim filename_cx As String ="info_collecte_HM1.txt"
   
    iv = Bconv.StringToBytes(sSecretKey,"ISO-8859-1")
    key = Bconv.StringToBytes(sSecretKey,"ISO-8859-1")
   
   
    ' use DES for variable length data using padding
    Dim kg As KeyGenerator
    Dim c As Cipher
    c.Initialize("DES/CBC/PKCS5Padding") ' replace "DES/" with "AES/" for Rijndael or "DESEDE/" for triple DES
   
   
       
    'Lecture du fichier
    Dim out As OutputStream
   
    out.InitializeToBytesArray(100)
    File.Copy2(File.OpenInput(File.DirDefaultExternal,filename_cx), out)
     
   
    ' CBC needs an initialisation vector
    c.InitialisationVector = iv
    kg.Initialize("DES") ' replace "DES" with "AES" for Rijndael or "DESEDE" for triple DES
    kg.KeyFromBytes(key)
   
   
    'Msgbox(Bconv.StringFromBytes(key,"ISO-8859-1"), "Key " & key.Length & " bytes")
   
   
    data = c.Encrypt(out.ToBytesArray, kg.key, True)
   
    Msgbox(Bconv.StringFromBytes(data,"ISO-8859-1"), "Encrypted is " & data.Length & " bytes")
       
    Dim writer As TextWriter
    writer.Initialize(File.OpenOutput(File.DirDefaultExternal,"info_collecte_HM1_dec.txt",False))
   
    writer.Write(Bconv.HexFromBytes(data))
    writer.Close
 
Upvote 0

FHEBERT

Member
Licensed User
Longtime User
Do you think that encryption cipher wrapper is compatible with DESCryptoServiceProvider of vb.net.
Because the encryption is different for the same intialization. See the result :

android:–ñBޜ V”Bé£@ÃVc>½á—t‰ó&érw%# ˜Û1XxDߚ’Õ®…)
VB.net:–ñBÞœ V”Bé£@ÃVc>½á—t‰ó&érw%# ˜Û1XxDßš’Õ®…)

Thank a lot
 
Upvote 0

masskyy

Member
Hello Erel,

I'm trying to implemente your code but with some modifications:

1.- I'll use AES encryption.

2.- When the string has been encripted, I need to save the string in a text file. After that, I read this file and decrypt the string. But in this last step, ? get the follow error:

last block incompleted in decryption.

The code is as follow.
B4X:
      Dim Bconv As ByteConverter
      Dim key(0) As Byte
      Dim data(0) As Byte
      Dim bytes(0) As Byte
      Dim iv(0) As Byte
      Dim sSecretKey As String = "password"


      Dim Kg As KeyGenerator
      Dim c As Cipher
      Dim md As MessageDigest
      c.InitialisationVector = iv
      c.Initialize("AES")
      Kg.Initialize("AES")
      Kg.KeyFromBytes(md.GetMessageDigest(sSecretKey.GetBytes("UTF8"), "MD5"))


      Dim Text As String= "hola"
      data = Bconv.StringToBytes(Text, "UTF8")
      data = c.Encrypt(data, Kg.key, True)
     
      Log(Bconv.StringFromBytes(data, "UTF8"))
     
      File.WriteString(File.DirDefaultExternal, "String.txt", Bconv.StringFromBytes(data,"UTF8"))



      data = Bconv.StringToBytes(File.ReadString(File.DirDefaultExternal,"String.txt"),"UTF8")
      Log(Bconv.StringFromBytes(data, "UTF8"))
      bytes = c.Decrypt(data, Kg.key, False)
     
      Log(Bconv.StringFromBytes(bytes,"UTF8").Trim)
 
Upvote 0

masskyy

Member
Thank you Erel,

I got encrypt the list, but some strings are truncated. For example, before the encryption, the list is:

(ArrayList) [3fff 01, 3001 02]

And after read the text file and desencrypted this, the array list is as follow:

(ArrayList) [3fff, 3001]

The code:
B4X:
    'Genero una lista
    Dim List1 As List
    List1.Initialize
    List1.Add("3fff 01")
    List1.Add("3001 02")
    Log(List1)
   
    Dim byte_temp() As Byte
    Dim cadena As String
    Dim List2 As List
    List2.Initialize
   
    byte_temp=su.DecodeBase64(List1.Get(0))
    data = c.Encrypt(byte_temp, Kg.key, False)
    cadena= su.EncodeBase64(data)
    List2.Add(cadena)
    byte_temp=su.DecodeBase64(List1.Get(1))
    data = c.Encrypt(byte_temp, Kg.key, False)
    cadena= su.EncodeBase64(data)
    List2.Add(cadena)
    File.WriteList(File.DirDefaultExternal, "String.txt", List2)
   
    Log(List2)
   

   
    Dim List3 As List=File.ReadList(File.DirDefaultExternal, "String.txt")
    Dim List4 As List
    List4.Initialize
    Log(List3)
   
    For i=0 To List3.Size-1
        byte_temp=su.DecodeBase64(List3.Get(i))
        data = c.Decrypt(byte_temp, Kg.key, False)
        cadena= su.EncodeBase64(data)
        List4.Add(cadena)
    Next
   
    Log(List4)
 
Upvote 0
Top