使用BouncyCastle

时间:2016-08-30 07:16:12

标签: java bouncycastle ecdsa

我试图在Java中使用ECDSA和BouncyCastle库,我通过读取Java中的pkcs12文件获得的私钥与我在PEM文件中看到的不同(我使用openssl)。我不确定它们是否应该相同但似乎合乎逻辑。问题是如何在pkcs12文件中使用BC获取与使用openssl相同的私钥?

证书和密钥是用

生成的
openssl ecparam -name secp521r1 -genkey -param_enc explicit -out private-key.pem
openssl req -new -x509 -key private-key.pem -out server.pem -days 730              
openssl pkcs12 -export -clcerts -in server.pem -inkey private-key.pem -out ecdsaCertificate.p12

Java代码:

 Public static void readCertificateData()
      throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException,
      FileNotFoundException, IOException, UnrecoverableKeyException {

System.out.println("Get KeyStore");
KeyStore pkcs12Store = KeyStore.getInstance("pkcs12", "BC");
System.out.println("Read File");
pkcs12Store.load(new FileInputStream(CERT), PASSWORD.toCharArray());

Enumeration aliasEnum = pkcs12Store.aliases();
Key key = null;
Certificate cert = null;

while (aliasEnum.hasMoreElements()) {

      String keyName = (String) aliasEnum.nextElement();
      key = pkcs12Store.getKey(keyName, PASSWORD.toCharArray());
      ECPrivateKey ecKey = (ECPrivateKey) key;

      System.out.println("ecKey : \n" + ecKey.toString());
      System.out.println("privKeyToDER:\n" + privateKeyToDER((PrivateKey) key));
      cert = pkcs12Store.getCertificate(keyName);
      System.out.println("cert2 :\n" + Base64.toBase64String((cert.getEncoded())));

      StringToFile(DIR + "tempCert.pem", "-----BEGIN CERTIFICATE-----\n"
              + Base64.toBase64String((cert.getEncoded())) + "-----END CERTIFICATE-----\n");
      System.out.println("privKey Base64 : " + Base64.toBase64String(key.getEncoded()));
      cert = pkcs12Store.getCertificate(keyName);
}
}
public static String privateKeyToDER(PrivateKey key) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    JcaPEMWriter pemWriter = new JcaPEMWriter(new OutputStreamWriter(bos));

    pemWriter.writeObject(key);
    pemWriter.close();

    return new String(bos.toByteArray());
}

0 个答案:

没有答案