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);
任何幫助?
是PKCS#8格式還是PKCS#1格式的密鑰?它以'---- BEGIN PRIVATE KEY -----'或'---- BEGIN RSA PRIVATE KEY -----'開頭。在第二種情況下,您需要將其轉換爲pcks8 – pedrofb
如果您希望我將其設置爲正確的答案,那麼您的評論是正確的。 – svprdga