Got java.security.InvalidKeyException: IOException: ObjectIdentifier() -- data 不是对象 ID (tag = -96)



注意:String cert作为 HashMap 通过 REST API 发送,不确定这里出了什么问题。

HashMap<String, Object> extraParams = //API brings this HashMap here.
String cert = (String) extraParams.get("certificate");
cert = cert.replaceAll("-----BEGIN CERTIFICATE-----", "").
replaceAll("-----END CERTIFICATE-----", "").replaceAll("r", "").replaceAll("n", "");
byte[] decodedBytes = Base64.decodeBase64(cert.getBytes("UTF-8"));
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pk = kf.generatePublic(publicKeySpec);

我来自原始服务器的证书字符串和我通过 API 收到的证书字符串是相同的,但仍然收到此错误,不知道为什么?

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: ObjectIdentifier() -- data isn't an object ID (tag = -96)

正如我在问题本身中提到的,我的String Cert已经穿越了REST HTTP,我怀疑UTF-8编码可能是一个问题。这就是我所缺少的。下面的代码对我来说就像魅力一样。部分复制自 https://stackoverflow.com/a/34549537/1665592

String cert = "...";
byte[] encodedCert = cert.getBytes("UTF-8");
byte[] decodedCert = Base64.decodeBase64(encodedCert);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
InputStream in = new ByteArrayInputStream(decodedCert);
X509Certificate certificate = (X509Certificate)certFactory.generateCertificate(in);
PublicKey publicKey = ((RSAPublicKey)certificate.getPublicKey());

最新更新