简体   繁体   中英

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

Note: String cert is sent over REST API as a HashMap, Not sure what is wrong here.

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);

My Certificate String from originated Server and what I received over API is same but still getting this error not sure why?

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

As I mentioned in the question itself that my String Cert have traveled over REST HTTP , I was suspecting that UTF-8 encoding might be an issue. That's what I was missing. Below code worked like charm for me. partially copied from 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM