也可以把证书写到ByteArrayOutputStream里,因为它有toByteArray方法,可以直接生成字节流保存证书
// This method writes a certificate to a file. If binary is false, the
// certificate is base64 encoded.
public static void export(java.security.cert.Certificate cert, File file, boolean binary) {
try {
// Get the encoded form which is suitable for exporting
byte[] buf = cert.getEncoded();
FileOutputStream os = new FileOutputStream(file);
if (binary) {
// Write in binary form
os.write(buf);
} else {
// Write in text form
Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
wr.write("-----BEGIN CERTIFICATE-----/n");
wr.write(new sun.misc.BASE64Encoder().encode(buf));
wr.write("/n-----END CERTIFICATE-----/n");
wr.flush();
}
os.close();
} catch (CertificateEncodingException e) {
} catch (IOException e) {
}
}
If the certificate is in the key store, it can exported using keytool
:
// Export in binary > keytool -storepass my-keystore-password -alias myalias -export -file outfilename.cer // Export in text format > keytool -storepass my-keystore-password -alias myalias -export -rfc -file outfilename.cerHere's an example of the text form of an exported certificate:
-----BEGIN CERTIFICATE----- MIIC6TCCAqcCBDxgu/IwCwYHKoZIzjgEAwUAMFoxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTES MBAGA1UEBxMJUGFsbyBBbHRvMQowCAYDVQQKEwFJMQswCQYDVQQLEwJNZTERMA8GA1UEAxMIUGF0 IENoYW4wHhcNMDIwMjA2MDUxNTMwWhcNMDIwNTA3MDUxNTMwWjBaMQswCQYDVQQGEwJVUzELMAkG A1UECBMCQ0ExEjAQBgNVBAcTCVBhbG8gQWx0bzEKMAgGA1UEChMBSTELMAkGA1UECxMCTWUxETAP BgNVBAMTCFBhdCBDaGFuMIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2 EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f6AR7 ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUA l2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdR WVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx +2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAPyx9uQ1PKBYO/2G RPzbW4y6pphNRmObJQWbjY/ERuCQwLRrpREh9sgMnptZjRzLVpWdzxNa9bFMFXAYMgoTUIgAZ9yN WPjp/JiFfzdIq3CY0CEey42M3mbD3pWsF9x4SSsJTpDobX/pm5XgtkhZXBZYtBk813Xv2LxyZ3OI W1JnMAsGByqGSM44BAMFAAMvADAsAhQ5wayd5cpEo/vHmF7G5gVQ9cMKKAIUMfk2ZYxNdhe6oNmH nR0AhnEHILE= -----END CERTIFICATE-----
// This method reads a certificate to a file. The certificate can be either // binary or base64 encoded. public static java.security.cert.Certificate importCertificate(File file) { try { FileInputStream is = new FileInputStream(file); CertificateFactory cf = CertificateFactory.getInstance("X.509"); java.security.cert.Certificate cert = cf.generateCertificate(is); return cert; } catch (CertificateException e) { } catch (IOException e) { } return null; } A certificate can be imported into a keystore usingkeytool
:> keytool -storepass my-keystore-password -alias myalias -import -file infilename.cer