0

编写代码生成数字证书

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

无法解码文件。它不是 PKCS #12 格式、已损坏或您输入的密码不正确。

但我不知道如何添加该密码以满足 PKCS #12 format. 怎么去呢?

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;

    }

证书生成成功并卡在这里。

你可以在这里看到完整的代码。

感谢您的任何提示。

4

1 回答 1

1

我查看了您的代码,我认为问题在于当浏览器需要 PKCS #12 格式时,您使用 certificate.getEncoded() 以原始二进制 DER 格式输出证书。我从未以编程方式完成此操作,我一直使用 keytool 或 openssl 在格式之间进行转换,所以我无能为力。

eta:这解释了如何在 java 中创建、签名和导出 PKCS12:http: //www.mayrhofer.eu.org/create-x509-certs-in-java(注意:这是一个旧帖子,需要 bouncycastle 和一点黑客攻击 :( - 现代版本的 bouncycastle 可能只是提供此功能)

于 2013-10-09T15:12:08.543 回答