在java X 509中创建证书文件(.pem和.der文件)

时间:2016-08-18 17:19:22

标签: java x509certificate

我需要在java中创建私钥和公钥,这是我到目前为止所做的:

public class CertificateChainGeneration {

    public static void CertificateChainGeneration(){
        try{
            //Generate ROOT certificate
            CertAndKeyGen keyGen=new CertAndKeyGen("RSA","SHA1WithRSA",null);
            keyGen.generate(1024);
            PrivateKey privateKey=keyGen.getPrivateKey();

            X509Certificate myCertificate = keyGen.getSelfCertificate(new X500Name("CN=MYCERTIFICATE"), (long) 365 * 24 * 60 * 60);

            myCertificate   = createSignedCertificate(myCertificate,privateKey);
            FileOutputStream publicKeyOut = new FileOutputStream("PublicKey.pem");
            BASE64Encoder encoder = new BASE64Encoder();
            publicKeyOut.write(X509Factory.BEGIN_CERT.getBytes());
            publicKeyOut.write('\n');
            encoder.encodeBuffer(myCertificate.getEncoded(), publicKeyOut);
            publicKeyOut.write(X509Factory.END_CERT.getBytes());
            publicKeyOut.close();

            byte[] privateKeyBytes = privateKey.getEncoded();
            FileOutputStream privateKeyOut = new FileOutputStream("PrivateKey.der");
            privateKeyOut.write(privateKeyBytes);
            privateKeyOut.close(); 
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    private static X509Certificate createSignedCertificate(X509Certificate issuerCertificate,PrivateKey issuerPrivateKey){
        try{
            Principal issuer = issuerCertificate.getSubjectDN();
            String issuerSigAlg = issuerCertificate.getSigAlgName();

            byte[] inCertBytes = issuerCertificate.getTBSCertificate();
            X509CertInfo info = new X509CertInfo(inCertBytes);
            info.set(X509CertInfo.ISSUER, new CertificateIssuerName((X500Name) issuer));

                        CertificateExtensions exts=new CertificateExtensions();
                        BasicConstraintsExtension bce = new BasicConstraintsExtension(true, -1);
                        exts.set(BasicConstraintsExtension.NAME,new BasicConstraintsExtension(false, bce.getExtensionValue()));
                        info.set(X509CertInfo.EXTENSIONS, exts);

            X509CertImpl outCert = new X509CertImpl(info);
            outCert.sign(issuerPrivateKey, issuerSigAlg);

            return outCert;
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return null;
    }
}

PrivateKey.der文件不是有效证书,我不知道如何使其有效。有人可以帮忙吗?

如果可能的话,我宁愿避免使用de bouncycastle库。

0 个答案:

没有答案