我正在尝试使用从PEM文件生成的字符串在android上生成ECPrivateKey,但出现错误:0D0680A8:asn1编码例程:ASN1_CHECK_TLEN:错误的标签错误。
我不想使用依赖关系(Bouncy Castle)来生成密钥。
我来自PEM的私钥
----- BEGIN EC私钥----- MHcCAQEEID5vukktXVvQhHpJRyBz4ngksjChNPbqBs4BE + d / pOq9oAoGCCqGSM49 AwEHoUQDQgAEsUYsxpVlCmRQEFZn + A + aES3 / KtmvBUNDSEZyfcKZUTqT / qPzwLM / g1O3X6YfNiDc5sIXxaQEahBpv0gjiWWnig == ----- END EC私钥-----
generatePrivateKeyfromPEM(){
//Getting the private key from PEM
String yPart = resultsPrivateKey.getData().substring(30, 198);
//Sanitising the private key
yPart = yPart.replaceAll("\n", "");
yPart = yPart.replaceAll(" ","");
ECPrivateKey sk;
try {
sk = getPrivateKey(yPart);
Log.i(LOG_TAG, "Private key is" + sk.toString());
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}}
private ECPrivateKey getPrivateKey(String base64PrivateKey) throws InvalidKeySpecException {
byte[] fromPEM = org.apache.commons.codec.binary.Base64.decodeBase64(base64PrivateKey.getBytes());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(fromPEM);
KeyFactory factory = null;
try {
factory = KeyFactory.getInstance("EC");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
PrivateKey privateKey = factory.generatePrivate(spec);
return (ECPrivateKey) privateKey;
}