注意: String cert通过 REST API 作为 HashMap 发送,不确定这里出了什么问题。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)
1 回答
慕后森
TA贡献1802条经验 获得超5个赞
正如我在问题本身中提到的,我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());
添加回答
举报
0/150
提交
取消