Java p12从现有密钥生成

时间:2018-06-11 13:10:47

标签: java cryptography rsa

我正在用Java编写一个使用Crt参数生成RSA密钥的程序。我能够在.pem文件中导出密钥,但我需要将其导出到pkcs12文件中。我怎么能用Java做到这一点?

1 个答案:

答案 0 :(得分:0)

Java通过KeyStore.getInstance("PKCS12")包含对PKCS#12密钥库的本机支持。但是,通常密钥库要求您提供匹配的私钥/ 证书对。仅提供公钥而不是证书是不够的。您必须创建证书,例如自签名证书才能使用PKCS#12密钥库提供商。

我尝试使用匿名类型创建自己的Certificate实例,但PKCS#12密钥库似乎只允许X.509证书(但它只会在您存储时告诉您密钥存储区,即它不是快速失败

以下是一些代码,用于创建自签名证书并存储私钥和生成的自签名证书:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Date;

import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.CertIOException;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.util.encoders.Hex;

public class StoreRSAKeyPairInPKCS12 {

    public static void main(String[] args) throws Exception {

        // --- generate a key pair (you did this already it seems)
        KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
        final KeyPair pair = rsaGen.generateKeyPair();

        // --- create the self signed cert
        Certificate cert = createSelfSigned(pair);

        // --- create a new pkcs12 key store in memory
        KeyStore pkcs12 = KeyStore.getInstance("PKCS12");
        pkcs12.load(null, null);

        // --- create entry in PKCS12
        pkcs12.setKeyEntry("privatekeyalias", pair.getPrivate(), "entrypassphrase".toCharArray(), new Certificate[] {cert});

        // --- store PKCS#12 as file
        try (FileOutputStream p12 = new FileOutputStream("mystore.p12")) {
            pkcs12.store(p12, "p12passphrase".toCharArray());
        }

        // --- read PKCS#12 as file
        KeyStore testp12 = KeyStore.getInstance("PKCS12");
        try (FileInputStream p12 = new FileInputStream("mystore.p12")) {
            testp12.load(p12, "p12passphrase".toCharArray());
        }

        // --- retrieve private key
        System.out.println(Hex.toHexString(testp12.getKey("privatekeyalias", "entrypassphrase".toCharArray()).getEncoded()));
    }

    private static X509Certificate createSelfSigned(KeyPair pair) throws OperatorCreationException, CertIOException, CertificateException {
        X500Name dnName = new X500Name("CN=publickeystorageonly");
        BigInteger certSerialNumber = BigInteger.ONE;

        Date startDate = new Date(); // now

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.add(Calendar.YEAR, 1);
        Date endDate = calendar.getTime();

        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").build(pair.getPrivate());
        JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, pair.getPublic());

        return new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));
    }

}

您至少需要来自Bouncy Castle的PKIX库(bcpkix-jdk15on.jar)以及可能是Bouncy Castle提供商的库。不需要安装Bouncy Castle提供程序