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?

svprdga
  • 2,171
  • 1
  • 28
  • 51
  • 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 – pedrofb Feb 13 '17 at 11:32
  • You're right pedrofb, put your comment as an answer if you want me to set it as the correct answer. – svprdga Feb 13 '17 at 22:02

2 Answers2

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

Community
  • 1
  • 1
pedrofb
  • 37,271
  • 5
  • 94
  • 142
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-----", "");
m-tech
  • 338
  • 2
  • 14