Android Question RSA Encryption allways the same output

Alexander Stolte

Expert
Licensed User
Longtime User
Hey,

why is this code working on B4J, but not on B4A?

B4X:
Private Sub EncryptRSAWithPublicKey(Text As String,PublicKey As String) As String
  
    Dim su As StringUtils
    Dim pubkey() As Byte = su.DecodeBase64(PublicKey)
    Dim Enc As Cipher
    Enc.Initialize("RSA")
    Dim kpg As KeyPairGenerator
    kpg.Initialize("RSA", 1024)
    kpg.PublicKeyFromBytes(pubkey)
    Dim bytes() As Byte = Text.GetBytes("UTF8")

    Return su.EncodeBase64(Enc.Encrypt(bytes,kpg.PublicKey,False))
  
End Sub

on B4A the output is allways the same, on B4J the right key is generated and i can decrypt it, but on B4A not.
 
Last edited:

b4x-de

Active Member
Licensed User
Longtime User
As far as I understand it seems the private key is in PKCS#1, therefore you initialize the Cipher with "RSA/ECB/PKCS1Padding" in your Post#2. But the KeyPairGenerator expects the private key to be in PKCS#8 when calling kpg.PrivateKeyFromBytes(privkey).
 
Upvote 0
Top