-1

I want to extract CN from Kafka keystore.jks. This issue How to extract CN from X509Certificate in Java? can help you to extract CN from X509certificate, but it doesn't say how to extract from JKS and I spent a lot of time to get the right solution for my own question. I assume that my solution can help somebody to get the right answer faster. You should read keystore then convert to the X509 and take advantage of cryptacular lib (CertUtil.subjectCN). My code in Scala demonstrates this below.

moneretin
  • 31
  • 3
  • Does this answer your question? [How to extract CN from X509Certificate in Java?](https://stackoverflow.com/questions/2914521/how-to-extract-cn-from-x509certificate-in-java) – Joe Dec 02 '21 at 09:05
  • @Joe In this question is extracting CN from X509certificate and I spent a lot of time to get the right solution for my own question:( – moneretin Dec 02 '21 at 10:39
  • 1
    Are you saying this is a duplicate, but you wanted to post your own solution (then just explain your scenario in that question with your code solution)? Or are you saying that your scenario is different, but just happens to have a solution which solves both issues (ok)? – ouflak Dec 02 '21 at 11:47
  • @ouflak, okay, I got it. I edit my post – moneretin Dec 02 '21 at 18:12

1 Answers1

1

That's my Scala code for extracting CN from JKS cert:

import org.cryptacular.util.CertUtil
import java.io.FileInputStream
import java.security.KeyStore
import java.security.cert.X509Certificate
....

  val keystore = KeyStore.getInstance("JKS")
  val keystoreLocation = new FileInputStream("your_path_to_the_certificate")
  keystore.load(keystoreLocation, "your_password".toCharArray)
  val aliases = keystore.aliases()

  while (aliases.hasMoreElements) {
    val alias = aliases.nextElement
    logger.info("alias name: " + alias)
    val certificate = keystore.getCertificate(alias).asInstanceOf[X509Certificate]
    val CN = CertUtil.subjectCN(certificate)
    logger.info("Common Name: " + CN)
  }
moneretin
  • 31
  • 3
  • 1
    Can you [edit] your answer to explain what you change and why this works now ? – Elikill58 Dec 02 '21 at 09:55
  • @Elikill58, I didn't change anything. I just wrote code to solve my problem and I noticed that my problem is not on the list of stack overflow. I decided that maybe this question with my solution does help someone – moneretin Dec 02 '21 at 10:47