Java - sign certificate programmatically without BC

旧街凉风 提交于 2019-12-07 18:35:30

问题


I am struggling with code that allows me to generate and sign certificates from java code without using keytool. Additionally due to dependency problems and incompatibilities i am unable to use bouncycastle libraries.

So far I found working code to generate CSR with given parameters, and it seems to work (at least the openssl tools verify that it is indeed a valid CSR) the code I found is here:

http://www.journaldev.com/223/generating-a-certificate-signing-request-using-java-api

It works with a simple modification due to the X500Signer class missing from jdk7.

How can I sign this CSR with my own CA (I have the CA key and cert in text files generated by openssl)


回答1:


I have searched for a way to do this also, but I didn't find any examples, so I ended up looking in the keytool source instead. (Can be found here: http://www.docjar.com/html/api/sun/security/tools/KeyTool.java.html)

Here comes an example of how signing can be done:

private static final String SIGNATURE_ALGORITHM = "SHA1WITHRSA";
private static final long VALIDITY_DAYS = 14L;


public static byte[] sign(PKCS10 csr, X509CertImpl signerCert, PrivateKey signerPrivKey) throws CertificateException, IOException, InvalidKeyException, SignatureException {

    /*
     * The code below is partly taken from the KeyTool class in OpenJDK7.
     */

    X509CertInfo signerCertInfo = (X509CertInfo) signerCert.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name issuer = (X500Name) signerCertInfo.get(X509CertInfo.SUBJECT + "." + CertificateSubjectName.DN_NAME);

    /*
     * Set the certificate's validity:
     * From now and for VALIDITY_DAYS days 
     */
    Date firstDate = new Date();
    Date lastDate = new Date();
    lastDate.setTime(firstDate.getTime() + VALIDITY_DAYS * 1000L * 24L * 60L * 60L);
    CertificateValidity interval = new CertificateValidity(firstDate, lastDate);

    /*
     * Initialize the signature object
     */
    Signature signature;
    try {
        signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    signature.initSign(signerPrivKey);

    /*
     * Add the certificate information to a container object
     */
    X509CertInfo certInfo = new X509CertInfo();
    certInfo.set(X509CertInfo.VALIDITY, interval);
    certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new Random().nextInt() & 0x7fffffff));
    certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    try {
        certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get(SIGNATURE_ALGORITHM)));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    certInfo.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuer));
    certInfo.set(X509CertInfo.KEY, new CertificateX509Key(csr.getSubjectPublicKeyInfo()));
    certInfo.set(X509CertInfo.SUBJECT, new CertificateSubjectName(csr.getSubjectName()));

    /*
     * Add x509v3 extensions to the container
     */
    CertificateExtensions extensions = new CertificateExtensions();

    // Example extension.
    // See KeyTool source for more.
    boolean[] keyUsagePolicies = new boolean[9];
    keyUsagePolicies[0] = true; // Digital Signature
    keyUsagePolicies[2] = true; // Key encipherment
    KeyUsageExtension kue = new KeyUsageExtension(keyUsagePolicies);
    byte[] keyUsageValue = new DerValue(DerValue.tag_OctetString, kue.getExtensionValue()).toByteArray();
    extensions.set(KeyUsageExtension.NAME, new Extension(
            kue.getExtensionId(),
            true, // Critical
            keyUsageValue));


    /*
     * Create the certificate and sign it
     */
    X509CertImpl cert = new X509CertImpl(certInfo);
    try {
        cert.sign(signerPrivKey, SIGNATURE_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (NoSuchProviderException e) {
        throw new RuntimeException(e);
    }

    /*
     * Return the signed certificate as PEM-encoded bytes
     */
    ByteOutputStream bos = new ByteOutputStream();
    PrintStream out = new PrintStream(bos);
    BASE64Encoder encoder = new BASE64Encoder();
    out.println(X509Factory.BEGIN_CERT);
    encoder.encodeBuffer(cert.getEncoded(), out);
    out.println(X509Factory.END_CERT);
    out.flush();
    return bos.getBytes();
}



回答2:


In java 8, PKCS10 class is missing. so, instead of passing PKCS10 csr, pass PublicKey key & X500Name name
Replace csr.getSubjectPublicKeyInfo & csr.getSubjectName at line 47/48 with key and name



来源:https://stackoverflow.com/questions/12334468/java-sign-certificate-programmatically-without-bc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!