Android Question Encryption problem

hugorinen

Member
Licensed 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

lemonisdead

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

hugorinen

Member
Licensed 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
 

hugorinen

Member
Licensed 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
 

hugorinen

Member
Licensed 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.
 
Top