Android Question Problem with Encrypt / Decrypt

Alex_197

Active Member
Licensed User
Hi all.

My app sends requests to the server and in this request some data is encrypted (for example device id, username, etc...)
It works fine since March 2020 and today one of my customer can't register with the server because string encrypted in my app on his LG X screen phone with Android 6.0.1 can't be decrypted on the server. It has never happened before. I tried all my phones with Android versions from 4 to 11 and all of them work fine with the same encrypt / decrypt procedures.

When I try to decrypt this string on the server (this is .NET 3.5) I'm getting the error Bad Data. I attached the error log from the server

and this is Decryption code on the server (VB.NET 3.5)
B4X:
Public Function Decrypt(encryptedData As String) As String

        Try
            Dim result As String = ""

            If encryptedData = "" Then
                Return "-1"
            End If

            If IsIOS.ToLower = "yes" Then
                result = IOSDecrypt(encryptedData)
                Return result
            End If

            Dim buffer As Byte() = Convert.FromBase64String(encryptedData)
            Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
            des.IV = New Byte() {211, 5, 233, 24, 55, 166, 7, 88}

            des.Key = ASCIIEncoding.UTF8.GetBytes("1234567890123456")
            'This line where the error happens
            result = Encoding.ASCII.GetString(des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length))
            des.Clear()
            Return result

        Catch ex As Exception
            Functions.SaveError(ex, "encryptedData=" & encryptedData)
            Return "-1"
        End Try

    End Function
and this is a code in my B4A app

B4X:
Sub Encrypt(dataToEncrypt As String ) As String

    Try
    
        Dim strPWD As String="1234567890123456"
        
        If dataToEncrypt.Trim.Length=0 Then
            Return dataToEncrypt
        End If
        
        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 = Array As Byte(211, 5, 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(strPWD,"ASCII"))
    
        data = bconv.StringToBytes(dataToEncrypt, "ASCII")
    
        data = c.Encrypt(data, kg.Key, True)

        Return B64.EncodeBtoS(data, 0, data.Length)
    Catch
        Log("Encrypt " & LastException)       
        Return "Error - Encryption failed."
    End Try
End Sub
If I try to decrypt the same string with my B4A Decrypt code

B4X:
Sub Decrypt(encryptedData As String ) As String

    Try
    
        Dim strPWD As String="1234567890123456"
        
        If encryptedData.Trim.Length=0 Then
            Return encryptedData
        End If

        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 = Array As Byte(211, 5, 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(strPWD,"ASCII"))
    
  
  
        data = B64.DecodeStoB(encryptedData)
        data = c.Decrypt(data, kg.Key, True)

        Return bconv.StringFromBytes(data, "ASCII")

    Catch
        Log("Decrypt " & LastException)        
        Return "Error - Decrption failed."
    End Try

End Sub
I got the error

B4X:
Error occurred on line: 81 (modCrypt)
javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
    at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
    at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER.doFinalInternal(OpenSSLCipher.java:602)
    at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:365)
    at javax.crypto.Cipher.doFinal(Cipher.java:2055)
    at anywheresoftware.b4a.agraham.encryption.CipherWrapper.doFinal(CipherWrapper.java:140)
    at anywheresoftware.b4a.agraham.encryption.CipherWrapper.Decrypt(CipherWrapper.java:150)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:732)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:348)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:197)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
    at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:80)
    at android.view.View.performClick(View.java:7288)
    at android.view.View.performClickInternal(View.java:7258)
    at android.view.View.access$4000(View.java:808)
    at android.view.View$PerformClick.run(View.java:28019)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7615)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Decrypt (Exception) java.lang.Exception:  javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
Thanks for your help.
 

Attachments

KMatle

Expert
Licensed User
Hard to say if it's just one device. Maybe the user never updated his/her phone or so. I found some sources on the www saying that there was/is a bug with Android 6 (which is quite old). What about going to AES-256 which is safer and probably solves your problem? (as AES is more often used).
 

Erel

Administrator
Staff member
Licensed User
If I try to decrypt the same string with my B4A Decrypt code
Are you able to reproduce it by encrypting a string in B4A and decrypting the result?

This code works:
B4X:
Private Sub Button1_Click
    Dim s As String = Encrypt("djsf lksdj flksd fjlksdf jlksdfj ksdlkf sjdlkfj skldfj slkdfj slkdf jslkdf jlksdf jklsdf")
    Log(s)
    Log(Decrypt(s))
End Sub
 

Alex_197

Active Member
Licensed User
Are you able to reproduce it by encrypting a string in B4A and decrypting the result?

This code works:
B4X:
Private Sub Button1_Click
    Dim s As String = Encrypt("djsf lksdj flksd fjlksdf jlksdfj ksdlkf sjdlkfj skldfj slkdfj slkdf jslkdf jlksdf jklsdf")
    Log(s)
    Log(Decrypt(s))
End Sub
Erel, thanks for the reply. But I don't know the original strings that were encrypted. I added some diagnostic that will return original and encrypted strings back to my email. Will see it later today.
 

Alex_197

Active Member
Licensed User
Hard to say if it's just one device. Maybe the user never updated his/her phone or so. I found some sources on the www saying that there was/is a bug with Android 6 (which is quite old). What about going to AES-256 which is safer and probably solves your problem? (as AES is more often used).
Can you show me some examples in B4A and .Net?
 

Alex_197

Active Member
Licensed User
Finally I received a list of the strings that were encrypted but failed to be decrypted.

B4X:
ProviderID    10102284
DeviceID    e2ae0c46-c5fc-4ad7-b0bb-6285a180ee80
FacilityCode    222493
SecProviderID    8OSuwpk5y352e9Su9me9TQ%3D%3D
SecDeviceID    fRkrkr2Vz40wVdfNQTZ6OiZxb5zg6MR27dqaDKUin1tdAoY9rHmNGA%3D%3D
SecFacilityCode    g9ZNkG0maRA%3D
If I try to decrypt them - it failed with the same error Bad Data.

Ok, now let's try to encrypt the original strings, for example Facility Code 222493.

Original string - 222493
Encrypted and encoded string - kg%2fN9KUctiE%3d


So now I out if any ideas how it was encrypted into g9ZNkG0maRA%3D.

What user says that this prepaid phone. Could it be reason?

Thanks.
 

Alex_197

Active Member
Licensed User
Are you able to reproduce it by encrypting a string in B4A and decrypting the result?

This code works:
B4X:
Private Sub Button1_Click
    Dim s As String = Encrypt("djsf lksdj flksd fjlksdf jlksdfj ksdlkf sjdlkfj skldfj slkdfj slkdf jslkdf jlksdf jklsdf")
    Log(s)
    Log(Decrypt(s))
End Sub
Yes I did and it's encrypted into different string that can be successfully decrypted.

Your example also works without problem wit my code.

That's why I don't understand how it was encrypted with the same code that can't be decrypted with the same code and encryption keys.

I attached a small project with the same code and keys as on my original project that runs on user's phone now.
 

Attachments

OliverA

Expert
Licensed User
Corruption of data? Bit flipping? Is that the only phone?
 

OliverA

Expert
Licensed User
Just for this case, encrypt, checksum and sent the checksum with the data
 

OliverA

Expert
Licensed User
Just for fun (first try), let's try these for encrypt/decrypt:
B4X:
Sub Encrypt(dataToEncrypt As String ) As String

    Try
    
    
        Dim su As StringUtils
        
        If dataToEncrypt.Trim.Length=0 Then
            Return dataToEncrypt
        End If
        
        Dim kg As KeyGenerator
        Dim c As Cipher
        'Dim B64 As Base64
        'Dim bconv As ByteConverter

        Dim data() As Byte
        Dim iv() As Byte = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES

      
        c.Initialize("DESEDE/CBC/PKCS5Padding")
        c.InitialisationVector = iv
        kg.Initialize("DESEDE")
   
    
        kg.KeyFromBytes(strPWD.GetBytes("ASCII"))
    
        data = dataToEncrypt.GetBytes("ASCII")
    
        data = c.Encrypt(data, kg.Key, True)

        Return su.EncodeBase64(data)
    Catch
        Log("Encrypt " & LastException)        
        Return "Error - Encryption failed."
    End Try
End Sub
B4X:
Sub Decrypt(encryptedData As String ) As String

    Try
    
        
        
        If encryptedData.Trim.Length=0 Then
            Return encryptedData
        End If

        Dim kg As KeyGenerator
        Dim c As Cipher
        Dim su As StringUtils

        Dim data() As Byte
        Dim iv() As Byte = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
      
        c.Initialize("DESEDE/CBC/PKCS5Padding")
        c.InitialisationVector = iv
        kg.Initialize("DESEDE")
    
    
        kg.KeyFromBytes(strPWD.GetBytes("ASCII"))
    
   
   
        data = su.DecodeBase64(encryptedData)
        data = c.Decrypt(data, kg.Key, True)

        Return BytesToString(data, 0, data.Length, "ASCII")

    Catch
        Log("Decrypt " & LastException)        
        Return "Error - Decrption failed."
    End Try

End Sub
 

Alex_197

Active Member
Licensed User
Just for fun (first try), let's try these for encrypt/decrypt:
B4X:
Sub Encrypt(dataToEncrypt As String ) As String

    Try
   
   
        Dim su As StringUtils
       
        If dataToEncrypt.Trim.Length=0 Then
            Return dataToEncrypt
        End If
       
        Dim kg As KeyGenerator
        Dim c As Cipher
        'Dim B64 As Base64
        'Dim bconv As ByteConverter

        Dim data() As Byte
        Dim iv() As Byte = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES

     
        c.Initialize("DESEDE/CBC/PKCS5Padding")
        c.InitialisationVector = iv
        kg.Initialize("DESEDE")
  
   
        kg.KeyFromBytes(strPWD.GetBytes("ASCII"))
   
        data = dataToEncrypt.GetBytes("ASCII")
   
        data = c.Encrypt(data, kg.Key, True)

        Return su.EncodeBase64(data)
    Catch
        Log("Encrypt " & LastException)       
        Return "Error - Encryption failed."
    End Try
End Sub
B4X:
Sub Decrypt(encryptedData As String ) As String

    Try
   
       
       
        If encryptedData.Trim.Length=0 Then
            Return encryptedData
        End If

        Dim kg As KeyGenerator
        Dim c As Cipher
        Dim su As StringUtils

        Dim data() As Byte
        Dim iv() As Byte = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
     
        c.Initialize("DESEDE/CBC/PKCS5Padding")
        c.InitialisationVector = iv
        kg.Initialize("DESEDE")
   
   
        kg.KeyFromBytes(strPWD.GetBytes("ASCII"))
   
  
  
        data = su.DecodeBase64(encryptedData)
        data = c.Decrypt(data, kg.Key, True)

        Return BytesToString(data, 0, data.Length, "ASCII")

    Catch
        Log("Decrypt " & LastException)       
        Return "Error - Decrption failed."
    End Try

End Sub
Doesn't work - I attached a small project. Your code in modCrypt Encrypt2 / Decrypt2
 

Attachments

OliverA

Expert
Licensed User
Doesn't work
It's my fault. I've not made myself clear. Use the code I posted on the other phone to generate the encrypted strings. I'm taking ByteConverter out of the picture. StringUtils can handle the Base64 encode/decode and build in B4X features can handle string to byte array and byte array to string conversions. ByteConverter has some Endian properties and I want to make sure they are not the culprit (most likely not, but one less library is one less library to debug). If this still generates an incorrect encrypted string, then I'll post some code to CRC each individual step to hopefully determine where the breakdown occurs.
 
Top