[英](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: 我正在尝试通过pem文件在Android应用程序中创建PrivateKey实例,以解密一些数据,但是出现以下错误:
java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG
java.lang.RuntimeException:错误:0c0890ba:ASN.1编码例程: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? 有什么帮助吗?
Seems your key is not PKCS8 format. 似乎您的密钥不是PKCS8格式。 Java does not support loading keys in PKCS#1 format.
Java不支持以PKCS#1格式加载密钥。 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. 检查您的密钥是否为PKCS#8格式,并验证其以
-----BEGIN PRIVATE KEY-----
开头。如果以----BEGIN RSA PRIVATE KEY-----
开头,则需要对其进行转换到PKCS#8。 See Convert PEM traditional private key to PKCS8 private key 请参阅将PEM传统私钥转换为PKCS8私钥
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-----", "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.