1

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?

2
  • 1
    is your key in PKCS#8 format or in PKCS#1 format? it starts with ----BEGIN PRIVATE KEY----- or with ----BEGIN RSA PRIVATE KEY-----? In the second case you need to convert it to pcks8 Commented Feb 13, 2017 at 11:32
  • You're right pedrofb, put your comment as an answer if you want me to set it as the correct answer. Commented Feb 13, 2017 at 22:02

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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-----", "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.