我要将RSA中的私钥转换为字符串中的Key,但由于某种原因,它会输出系统错误。
static private Key privatekey;
try{
byte[] keyprivBytes = Base64.decode(KeypriString,0);
PKCS8EncodedKeySpec specpriv = new PKCS8EncodedKeySpec(keyprivBytes);
KeyFactory keyFactorypriv = KeyFactory.getInstance("RSA");
privatekey = keyFactorypriv.generatePrivate(specpriv); <--(here is where the logcat says the code is broken)
}catch(UnsupportedEncodingException | InvalidKeySpecException | NoSuchAlgorithmException e){
e.printStackTrace();
}
其中keypriString
是我的私钥所在的String
。
logcat的:
11-12 11:11:20.066 15141-15141/<pakage name> W/System.err: java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
11-12 11:11:20.066 15141-15141/<pakage name> W/System.err: at com.android.org.conscrypt.OpenSSLKey.getPrivateKey(OpenSSLKey.java:180)
11-12 11:11:20.076 15141-15141/<pakage name> W/System.err: at com.android.org.conscrypt.OpenSSLRSAKeyFactory.engineGeneratePrivate(OpenSSLRSAKeyFactory.java:64)
11-12 11:11:20.076 15141-15141/<pakage name> W/System.err: at java.security.KeyFactory.generatePrivate(KeyFactory.java:187)
11-12 11:11:20.076 15141-15141/<pakage name> W/System.err: at <pakage name>.Crypto.<init>(Crypto.java:62)
有人可以告诉我这个问题吗?
答案 0 :(得分:1)
1:逐步验证编码然后解码,并跟踪每一步到输出:你会看到它崩溃的地方
2:可能的错误:Base64.decode给出null,因为这不是一个好的base64字符串
3:或者你在PKCS和X509之间混淆了吗?
你应该看到 Converting Strings to encryption keys and vice versa java , 这个: Java asymmetric encryption: preferred way to store public/private keys , 这个: Create PrivateKey and PublicKey from a String base64 encoding with DER format