I have a client generated CSR file, from which I want to extract the Public Key. They provided KeyStore Explorer software to check it.
However I am unable to extract the public key from it using the tool. How can get the public key from CSR file using Java program using BC?
CSR is generated with RSA 2048, using SHA1 with RSA.
From the tool, I can see the ASN1 data of the Public key but not ASCII format. Atleast how do I use the ASN1 data to get the public key in ASCII format using BC
SEQUENCE
{
SEQUENCE
{
OBJECT IDENTIFIER=RSA encryption (1.2.840.113549.1.1.1)
NULL
}
BIT STRING= //BITS HERE
}
It depends on what you mean by "ASCII format". But generally you can do something like that:
// Read the CSR
FileReader fileReader = new FileReader("/path/to/your.csr");
PemReader pemReader = new PemReader(fileReader);
PKCS10CertificationRequest csr =
new PKCS10CertificationRequest(pemReader.readPemObject().getContent());
pemReader.close();
fileReader.close();
// Write the Public Key as a PEM-File
StringWriter output = new StringWriter();
PemWriter pemWriter = new PemWriter(output);
PemObject pkPemObject = new PemObject("PUBLIC KEY",
csr.getSubjectPublicKeyInfo().getEncoded());
pemWriter.writeObject(pkPemObject);
pemWriter.close();
System.out.println(output.getBuffer());
// Extract the Public Key as "RSAKeyParameters" so you can use for
// encryption/signing operations.
RSAKeyParameters pubkey =
(RSAKeyParameters)PublicKeyFactory.createKey(csr.getSubjectPublicKeyInfo());
This is what you'll get:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxlRixVjOXAmUQ2zORREO
VSQDQejyjWzT3bDznPltiPMwM3SOmPmZyrB8jF3iFvzdFge1QG2WdDj7PzmysXNL
/1xRa0efWv8nURx1eV86hvU6ThNqY3WPyYYXSjTcN74uhGSJo7d5zG6JSL4Cj+l4
RO+nh/5Pa8438ufS+9hXndKPFT2aub9roKysxWpsctpNoOIjfyxkLv9Z9sqxuggG
nwYkwYmoDjPAQp2gRpCp7Hw5F6jSkA33NR5S/aPdyvzKZDbuoRdAl2sTubL1TLG3
nC6tetGsmFRRkNiJjPSNtbXXtN6RB2eJL0epyaFFLksFBaL6nvYIgB1uqFroUY15
2QIDAQAB
-----END PUBLIC KEY-----
I have tested this with the latest version of the BC-provider. You need both the "provider" and the "PKIX/PKCS..." jar (otherwise you have to deal with deprecated API-calls).