编写代码生成数字证书
在浏览器中安装时出现错误
Failed to decode the file. Either it is not in PKCS #12 format, has been corrupted, or the password you entered was incorrect.
但我不知道如何添加该密码以满足 PKCS #12 格式
。该如何搭配呢?
public KeyPair generateKeyPair() {
KeyPair pair = null;
try {
String password = "1234";
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = Utils.createFixedRandom();
keyGen.initialize(1024, random);
pair = keyGen.generateKeyPair();
PrivateKey privkey1 = pair.getPrivate();
PublicKey pubKey1 = pair.getPublic();
byte[] privateKeyBytes = pair.getPrivate().getEncoded();
byte[] encryptedPrivateKeyBytes = passwordEncrypt(
password.toCharArray(), privateKeyBytes);
//Problem might be here
Signature dsa = Signature.getInstance("SHA1withRSA");
dsa.initSign(privkey1);
Cipher cipher = Cipher
.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey1, random);
byte[] input = new byte[] { (byte) 0xbe, (byte) 0xef };
System.out.println("input : " + Utils.toHex(input));
byte[] cipherText = cipher.doFinal(input);
System.out.println("cipher: " + Utils.toHex(cipherText));
cipher.init(Cipher.DECRYPT_MODE, privkey1);
byte[] plainText = cipher.doFinal(cipherText);
System.out.println("plain : " + Utils.toHex(plainText));
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
}
return pair;
}
证书生成成功并卡在此处。
感谢您的任何提示。
最佳答案
我查看了您的代码,我认为问题是当浏览器需要 PKCS #12 格式时,您使用certificate.getEncoded() 以原始二进制 DER 格式输出证书。我从未以编程方式完成过此操作,我总是使用 keytool 或 openssl 在格式之间进行转换,因此我无法提供更多帮助。
eta:这解释了如何在 java 中创建、签名和导出 PKCS12:http://www.mayrhofer.eu.org/create-x509-certs-in-java (注意:这是一篇旧文章,需要 bouncycaSTLe 和一些黑客技术:( - 现代版本的 bouncycaSTLe 可能只提供此功能)
关于java - 数字证书私钥添加密码:Failed to decode the file :Not in PKCS #12 format,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19275109/