Android Question How can I encrypt a String in a text file?

Sergio Castellari

Active Member
Licensed User
Hello people,

I have a "settings.txt" file, which I save / read with
File.WriteMap (TXTFileDir, TXTFileName, Map1) / map1 = File.ReadMap (TXTFileDir, TXTFileName)

This works correctly. The file path is File.DirInternal.

But I need a key of the map, it can be encrypted when recording it, and decrypt it when reading it.

Cheers,
Sergio
 

MicroDrie

Well-Known Member
Licensed User
Longtime User
With the search option you can find several encryption examples. If you want to encrypt and decrypt only one string type you can use B4XEncryption (B4A, B4J and B4I). An example is given. Be aware that it is a good security policy not to put passwords in the code.
 
Upvote 0

Sergio Castellari

Active Member
Licensed User
Hello @MicroDrie,

Thank you.
I had already seen B4x Encryption. But what I need was a simple encryption returned in the form of text to be able to identify it in a "file.txt".

I managed to do it in the following way:

B4X:
'***********************************************************
'* Cripto() Encripta/Desencripta un String simple          *
'*    Recibe: cTxt ---> Texto a Encriptar                  *
'*                 ---> TextoBase64 a desencriptar         *
'*            cTipo --> "E" Encriptar / "D" Desencriptar   *
'* Retorna: un String (compatible con archivos.txt)        *
'******************************************** 06-05-2020 ***
Public Sub Cripto(cTxt As String, cTipo As String) As String
    Dim c As B4XCipher
    Dim su As StringUtils
    Dim e() As Byte
    If cTipo = "E" Then
        Log("Texto a Encriptar: " & cTxt)
        e = c.Encrypt(cTxt.GetBytes("utf8"),"xpenfWv")
        Return su.EncodeBase64(e)
    Else If cTipo = "D" Then
        Log("Texto a Desencriptar: " & cTxt)
        e = su.DecodeBase64(cTxt)
        If e.Length = 0 Then Return ""
        e = c.Decrypt(e,"xpenfWv")
        Return BytesToString(e, 0, e.Length, "utf8")
    Else
        Return cTxt
    End If
End Sub
[/CÓDIGO]
 
Upvote 0

MicroDrie

Well-Known Member
Licensed User
Longtime User
Maybe this example: Use simple encryption for B4J, B4A and B4I (also in url) write the data to and read the data from a file. You can have maximum flexibility when you use the JSON format. Erel has made a online tool for the construction of the data. If you data is stored in a map, you can use a DButils routine or construct a comma separated file (CSV file). A CSV start always with the field header. Choices enough.
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
Upvote 0

Sergio Castellari

Active Member
Licensed User
Base 64 is the correct way to convert "random bytes" to string.

Another simple option is to use KVS (2) which supports encryption as well, though it will not create a text file (why does it matter?).

Thanks @Erel
I did not know it was KVS, another colleague also gave me the information. It is much more powerful.

Cheers
 
Upvote 0
Top