java - 数字证书私钥添加密码:Failed to decode the file :Not in PKCS #12 format,

标签 java encryption cryptography digital-signature digital-certificate

编写代码生成数字证书

在浏览器中安装时出现错误

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;

    }

证书生成成功并卡在此处。

You can see full code here.

感谢您的任何提示。

最佳答案

我查看了您的代码,我认为问题是当浏览器需要 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/

相关文章:

javascript - C# 解密Javascript中加密的数据

与自定义密码套件的 Java HTTPS 连接

java - javax.crypto.spec.SecretKeySpec 线程安全吗?

Java 可选参数化接口(interface)

java - 与 PriorityQueue 连续。比较时如何对对象+1?

php - 将 php mcrypt_encrypt 和 decrypt 转换为 mysql 函数

encryption - PKCS#11。在硬件中执行加密/解密的可能性

c++ - 用于密码学的 Botan vs OpenSSL vs Crypto++

java - 如何在Windows 7上双击运行.jar文件

java - 如何使用 JSP 将表单数据解析到客户端 Java 类