1

I have generated a RSA key with PHP (openssl). It workes fine. I used this PHP script to create the keys:

$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
 );
$keys = openssl_pkey_new($config);
$privateKey = openssl_pkey_get_private($keys);
$details = openssl_pkey_get_details($privateKey);
$publicKey = $details['key'];
openssl_pkey_export_to_file($privateKey, 'private.pem');
file_put_contents('public.der', $publicKey);

Now I would like to load the keys (public.der and private.pem) by Android/Java. But I do not know how because of the format of the RSA key. I think the public.der can be in the assets folder (in Android).

I will not store the public key which belongs to the private key on the same device.

Edit: The content of the public.der file:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAog/07W7tF/7/tugWy5Fe
cyGMnwbvqYbyPVBJ8/08nZS79sZfROAuxrGz4CJMosCJp9MZdDiwKuLNaQ9Pbayz
mOq6sQ2XpGFDhqrVJJaw3R+oq8dWgtnyZcRs9MvUYVOOltqXV/NVv+X+JECqx8Pz
WiEim6mQtIbcjQ78hZhiC3kZeRIa17YVM/Yagu4tGne/F6gQaMvA+ZSWJIj5mvU1
UOuuCsCsTF5HQbrgWTH7P+ZB3andvPDnih9eNeeplxcVwk1KKdtkn7l1a8t7YYVW
eJtmtfd+sgjeCRDSqh1DNtDTanHOILunGBPZ85bN9dLZ3v5YJeQX4LL5R2jqy3ti
owIDAQAB
-----END PUBLIC KEY-----
JavaForAndroid
  • 1,111
  • 2
  • 20
  • 42

1 Answers1

2

Question "load RSA public Key From File" has a detailed answer to the question how to load DER-encoded keys into Java application.

And question "Getting RSA private key from PEM BASE64 Encoded private key file" describes loading PEM-encoded public key into Java application.

Community
  • 1
  • 1
divanov
  • 6,173
  • 3
  • 32
  • 51
  • I have already tried this, but I got this error while reading the public key:java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag. Can you help me? If I add BC as parameter I also get an error: java.security.spec.InvalidKeySpecException: java.io.IOException: cannot recognise object in stream – JavaForAndroid Feb 16 '14 at 20:14
  • And what is content of `public.der`? – divanov Feb 16 '14 at 20:23
  • I added the content of the public.der file to the first post. – JavaForAndroid Feb 16 '14 at 20:38
  • This is PEM format. See an answer update. – divanov Feb 16 '14 at 20:53
  • Great answer. Thank you. This code worked well: String temp = new String(keyBytes); String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", ""); publicKeyPEM = privKeyPEM.replace("-----END PUBLIC KEY-----", ""); Base64 b64 = new Base64(); byte [] decoded = b64.decode(publicKeyPEM); – JavaForAndroid Feb 16 '14 at 21:14