Android Question Different BYTE() result from 2 Instances of B4XCIPHER

Gianni Sassanelli

Active Member
Licensed User
Longtime User
Hi
as subject i get two different result if i call form more time the some function for encrypt my string
Is this correct?
I expected to always have the same byte array

If this is the correct behavior, how can I always get the same byte array?
thank's

the example is following

EXAMPLE:
    Dim EncryptedData() As Byte

    Dim c As B4XCipher
    Dim myString, myPassword As String

    Log("Start test ==============")
    myString       = "abc"
    myPassword = "1234"
    Log("1° test >>")
    EncryptedData = c.Encrypt(myString.GetBytes("utf8"), myPassword)
    Log("First Time    byte Length: " & EncryptedData.Length)
    For N = 0 To EncryptedData.Length-1
         Log(EncryptedData(N))
    Next
    EncryptedData = c.Encrypt(myString.GetBytes("utf8"), myPassword)   ' note the some string and password
    Log("Second Time    byte Length: " & EncryptedData.Length)
    For N = 0 To EncryptedData.Length-1
            Log(EncryptedData(N))
    Next   

    EncryptedData = c.Encrypt(myString.GetBytes("utf8"), myPassword)   ' note the some string and password
    Log("third Time    byte Length: " & EncryptedData.Length)
    For N = 0 To EncryptedData.Length-1
            Log(EncryptedData(N))
    Next
 

OliverA

Expert
Licensed User
Longtime User
If this is the correct behavior, how can I always get the same byte array?
B4XCipher uses a different "salt" when encrypting data. The encrypted data is prefixed with this salt to allow the decryption algorithm to work properly. This is by design. If you want something that encrypts without a salt, then one method would be to use @agraham's encryption library and do your own encryption. I would not recommend that though, since there are reasons for using a salt in encryption.

Links:
@agraham's encryption library: https://www.b4x.com/android/forum/threads/base64-and-encryption-library.6839/
An article about encryption and the use of salt: https://auth0.com/blog/adding-salt-to-hashing-a-better-way-to-store-passwords/
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
Initialisation Vectors in the Cipher object in the Encryption library serve the same purpose as a salt except you can define your own whereas B4XCipher chooses its own random one and prepends it to the result of the encryption. By using different IVs you ensure that the same string when encrypted twice does not produce the same result which is a good security measure.
 
Upvote 0

Gianni Sassanelli

Active Member
Licensed User
Longtime User
OK thank's for your explanation Agrahm and OliverA.

I would need to be able to encrypt a string to save some passwords.

The problem is that if the hash of the encrypted string always changes I can never compare a user entered password with one just saved in the db.
Could you advise me how to do it?
 
Upvote 0
Top