我正在尝试从文件中读取私钥。我在logcat中收到以下错误。返回的值为空。
java.security.spec.InvalidKeySpecException:java.lang.RuntimeException:error:0c0000af:ASN.1编码例程:OPENSSL_internal:TOO_LONG
我试着寻找已经发生但却找不到的情况。我想知道这个错误意味着什么以及如何解决它。
这是我的代码:
public static String decryptionWithFile(String encrypted,String privateFile2)throws Exception {
PrivateKey privateKey = getPrivateKey(privateFile2);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bts = Hex.decodeHex(encrypted.toCharArray());
bts = cipher.doFinal(bts);
bts = getFinalBytesOfDycryptedString(bts);
String decryptedMessage = new String(cipher.doFinal(encrypted.getBytes()));
return new String(bts,"UTF-8");
}
这是getPrivateKey();方法:
private static PrivateKey getPrivateKey(String privateFile2)throws Exception {
File f = new File(privateFile2);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec);
return privKey;
}
重要说明:我将.der文件添加到我的资源文件夹中,然后将其保存到内部存储中的文件中,以便访问我的功能所需的路径。你认为,在这个过程中,文件中发生了什么事吗? (它与公钥一起运行良好)
答案 0 :(得分:0)
问题证明是我猜想的。当我将.der文件写入内部存储时,它会以某种方式被改变,因此无法正常工作。
所以不是那样的。我直接使用从getAssets()。open(filename)返回的InputStream
来读取私钥。修好了。