Encrypt/Decrypt Fail detection

Rusty

Well-Known Member
Licensed User
Longtime User
I am encrypting and decrypting data within my Android app.

When an Encrypted data element is Decrypted with the wrong password, is there a way to detect that the decryption failed?

Thanks,
Rusty
 

Rusty

Well-Known Member
Licensed User
Longtime User
Grazie per il tuo suggerimento.
Sto usando la libreria e la creazione di ByteConverter in memoria di crittografia / decrittografia.
Quando sto cercando di rilevare il tasto sbagliato viene utilizzata per decifrare una stringa.
...my attempt at Italian :)
...in English:
Thank you for your suggestion.
I am using the ByteConverter library and creating in memory encryption/decryption.
I'm trying to detect when the wrong key is used to decrypt a string.
Rusty
 
Upvote 0

Rusty

Well-Known Member
Licensed User
Longtime User
I have a Try Catch block and when an incorrect key is used, it does not "fire"
B4X:
Sub Decrypt(encryptedData As String, KeyNo As Int ) 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 
    iv = KeysIV
        
    Try
        c.Initialize("DESEDE/CBC/NoPadding")                '"DESEDE/CBC/PKCS5Padding")     ' 
        c.InitialisationVector = iv
        kg.Initialize("DESEDE")     
        kg.KeyFromBytes(Keys.Get(KeyNo))            
        data = B64.DecodeStoB(encryptedData)
        data = c.Decrypt(data, kg.Key, True)
    Catch                                                    'decrypt failed
        Return encryptedData
    End Try
Return Bconv.StringFromBytes(data, "UTF8")
End Sub
the catch doesn't happen when i use the wrong key.
Any ideas?
thanks,
Rusty
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
There is no way to tell if a wrong key (or a wrong initialisation vector) is used unless you can establish that the result is not as expected. You would need a known value at a known position in the data to check, or the original message could include a hash of that message which you could check after decryption.
 
Last edited:
Upvote 0

Rusty

Well-Known Member
Licensed User
Longtime User
Ok, that's why the catch doesn't "catch" the lack of decryption success.
What I've done is to re-encrypt the result from the decryption and handle the failure to successfully encrypt the data in a try catch. (unless it is successfully encrypted/decrypted)
If the original string (that failed decryption) does not match the re-encrypted and decrypted string, then the original decryption has failed.
A lot of overhead, but my strings are very short so it doesn't inordinately slow things down.
I suppose the idea of embedding a hash into the encrypted string to allow testing is a good idea and will experiment with this.
Not very elegant, but at least I can detect when an encrypted string was encrypted with a different key.

Thanks Agraham (and Erel)
 
Upvote 0
Top