3

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)
Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92
  • Why did you delete your previous question and then repost the same one? You need to understand that a certificate and public key are two different things. A certificate **contains** a public key, among other things. However, a certificate will not start with `-----BEGIN PUBLIC KEY-----`, so you code is confusing. – President James K. Polk Sep 18 '19 at 14:34
  • Thanks @JamesKPolk yep, I was initially confused between `certificate` and `PublicKey` – Swapnil Kotwal Sep 19 '19 at 11:13

1 Answers1

3

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());
Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92