2017-02-13 18 views
1

我试图从PEM文件在一个Android应用程序创建一个专用密钥实例来解密的一些数据,但我收到以下错误:(安卓/ JAVA)创建一个RSA私钥例如

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

的代码:

// 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); 

任何帮助?

+1

是PKCS#8格式还是PKCS#1格式的密钥?它以'---- BEGIN PRIVATE KEY -----'或'---- BEGIN RSA PRIVATE KEY -----'开头。在第二种情况下,您需要将其转换为pcks8 – pedrofb

+0

如果您希望我将其设置为正确的答案,那么您的评论是正确的。 – svprdga

回答

2

看起来你的钥匙不是PKCS8格式。 Java不支持以PKCS#1格式加载密钥。检查您的密钥是否采用PKCS#8格式,验证它是否以-----BEGIN PRIVATE KEY-----开头如果以----BEGIN RSA PRIVATE KEY-----开头,则需要将其转换为PKCS#8。请参阅Convert PEM traditional private key to PKCS8 private key