svprdga
svprdga

Reputation: 2549

(Android / Java) Create a RSA private key instance

I am trying to create a PrivateKey instance in an Android app from a pem file to decrypt some data but I am getting the following error:

java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG

The code:

// Read private key.
InputStream is = context.getResources().openRawResource(R.raw.private_key);
br = new BufferedReader(new InputStreamReader(is));
List<String> lines = new ArrayList<String>();
line = null;
while ((line = br.readLine()) != null)
    lines.add(line);

// Removes the first and last lines of the file (comments).
if (lines.size() > 1 && lines.get(0).startsWith("-----") &&
        lines.get(lines.size()-1).startsWith("-----")) {
    lines.remove(0);
    lines.remove(lines.size()-1);
}

// Concats the remaining lines to a single String.
StringBuilder sb = new StringBuilder();
for (String aLine: lines)
    sb.append(aLine);
String keyString = sb.toString();

// Converts the String to a PublicKey instance
byte[] keyBytes = Base64.decode(keyString, Base64.DEFAULT);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
mKey = keyFactory.generatePrivate(spec);

Any help?

Upvotes: 1

Views: 1941

Answers (2)

m-tech
m-tech

Reputation: 338

use this lines:

    if (privateKeyString.contains("-----BEGIN PRIVATE KEY-----") || privateKeyString.contains("-----END PRIVATE KEY-----"))
        privateKeyString = privateKeyString.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "");


    if (privateKeyString.contains("-----BEGIN RSA PRIVATE KEY-----") || privateKeyString.contains("-----END RSA PRIVATE KEY-----"))
        privateKeyString = privateKeyString.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", "");

Upvotes: 0

pedrofb
pedrofb

Reputation: 39291

Seems your key is not PKCS8 format. Java does not support loading keys in PKCS#1 format. Check your key is in PKCS#8 format verifying that it starts with -----BEGIN PRIVATE KEY----- If it starts with ----BEGIN RSA PRIVATE KEY----- then you need to convert it to PKCS#8. See Convert PEM traditional private key to PKCS8 private key

Upvotes: 2

Related Questions