Android Question Encryption problem

hugorinen

Member
Licensed User
Longtime User
Hi,

I want to encrypt a string with a certificate *.cer (valid, tested on other platforms). I also tried with a .der file, but it didn't work.

Reading the public key :

B4X:
PUBLIC_KEY = File.ReadString(File.DirAssets,"mycertificate.cer").GetBytes("UTF8")

Encrypting :

B4X:
Sub CryptWithPublicKey(input As String) As String
    Dim cipher_ As Cipher
    Dim key_ As KeyPairGenerator
    Dim msg(0) As Byte
    Dim Bconv As ByteConverter

    key_.Initialize("RSA",128)

    key_.PublicKeyFromBytes(Main.PUBLIC_KEY) ' Here's the exception
     
    cipher_.Initialize("RSA")
 
    msg = cipher_.Encrypt(input.GetBytes("UTF8"),key_,False)
 
    Return Bconv.StringFromBytes(msg,"UTF8")
End Sub

The exception is :
java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag

I can't find why,

Thanks
 

Attachments

  • Capture.PNG
    Capture.PNG
    62.9 KB · Views: 163

lemonisdead

Well-Known Member
Licensed User
Longtime User
Off topic : could you change your avatar ? Without a second check we could think it's a Erel post. Thanks
 
Upvote 0

hugorinen

Member
Licensed User
Longtime User
@lemonisdead : yep sorry done !

@Klaus Matle : still not working, i'm testing it in Java right now with code :

B4X:
InputStream instream = new FileInputStream(filePath);   // Opening the certificate
byte[] encodedKey = new byte[instream.available()];
instream.read(encodedKey);                              // Getting bytes from it
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pkPublic = kf.generatePublic(publicKeySpec);  // Finally get our Public Key
 
Upvote 0

hugorinen

Member
Licensed User
Longtime User
Thanks but

B4X:
Dim PUBLIC_KEY(0) As Byte

And then :

B4X:
PUBLIC_KEY =  ReadFile(File.DirAssets,"publickey.der") '  or CER or PEM

B4X:
Dim key_ As KeyPairGenerator

key_.Initialize("RSA",128)

key_.PublicKeyFromBytes(Main.PUBLIC_KEY)

Return the same exception :

B4X:
java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
 
Upvote 0

hugorinen

Member
Licensed User
Longtime User
Finally I think I found the answer. The key was in wrong format. Right is DER but the one which I tested before wasn't working, and with another DER file it works. The code I post just before is right.
 
Upvote 0
Top