这取决于“ASCII 格式”的含义。但通常你可以这样做:
// 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());
这就是你会得到的:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxlRixVjOXAmUQ2zORREO
VSQDQejyjWzT3bDznPltiPMwM3SOmPmZyrB8jF3iFvzdFge1QG2WdDj7PzmysXNL
/1xRa0efWv8nURx1eV86hvU6ThNqY3WPyYYXSjTcN74uhGSJo7d5zG6JSL4Cj+l4
RO+nh/5Pa8438ufS+9hXndKPFT2aub9roKysxWpsctpNoOIjfyxkLv9Z9sqxuggG
nwYkwYmoDjPAQp2gRpCp7Hw5F6jSkA33NR5S/aPdyvzKZDbuoRdAl2sTubL1TLG3
nC6tetGsmFRRkNiJjPSNtbXXtN6RB2eJL0epyaFFLksFBaL6nvYIgB1uqFroUY15
2QIDAQAB
-----END PUBLIC KEY-----
我已经用最新版本的 BC-provider 对此进行了测试。您需要“provider”和“PKIX/PKCS...”jar(否则您必须处理已弃用的 API 调用)。