Search in sources :

Example 1 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest in project airlift by airlift.

the class TestCertificationRequest method test.

@Test
public void test() throws Exception {
    // test only with state because BC encodes every other value using UTF8String instead of PrintableString used by the JDK
    String name = "C=country";
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(new ECGenParameterSpec("secp256r1"));
    KeyPair keyPair = generator.generateKeyPair();
    CertificationRequestInfo certificationRequestInfo = new CertificationRequestInfo(new X500Principal(name), keyPair.getPublic());
    SignatureAlgorithmIdentifier signatureAlgorithmIdentifier = findSignatureAlgorithmIdentifier("SHA256withECDSA");
    byte[] signature = certificationRequestInfo.sign(signatureAlgorithmIdentifier, keyPair.getPrivate());
    CertificationRequest certificationRequest = new CertificationRequest(certificationRequestInfo, signatureAlgorithmIdentifier, signature);
    assertEquals(certificationRequest.getCertificationRequestInfo(), certificationRequestInfo);
    assertEquals(certificationRequest.getSignatureAlgorithmIdentifier(), signatureAlgorithmIdentifier);
    assertEquals(base16().encode(certificationRequest.getSignature()), base16().encode(signature));
    assertEquals(certificationRequest, certificationRequest);
    assertEquals(certificationRequest.hashCode(), certificationRequest.hashCode());
    PKCS10CertificationRequest expectedCertificationRequest = new PKCS10CertificationRequest(new org.bouncycastle.asn1.pkcs.CertificationRequest(new org.bouncycastle.asn1.pkcs.CertificationRequestInfo(new X500Name(name), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()), new DERSet()), new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withECDSA"), new DERBitString(signature)));
    assertEquals(base16().encode(certificationRequest.getEncoded()), base16().encode(expectedCertificationRequest.getEncoded()));
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) DERBitString(org.bouncycastle.asn1.DERBitString) DERBitString(org.bouncycastle.asn1.DERBitString) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) DERSet(org.bouncycastle.asn1.DERSet) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) SignatureAlgorithmIdentifier.findSignatureAlgorithmIdentifier(io.airlift.security.csr.SignatureAlgorithmIdentifier.findSignatureAlgorithmIdentifier) X500Principal(javax.security.auth.x500.X500Principal) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Test(org.testng.annotations.Test)

Example 2 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class CsrEnrollCertCmd method execute0.

@Override
protected Object execute0() throws Exception {
    if (caName != null) {
        caName = caName.toLowerCase();
    }
    CertificationRequest csr = CertificationRequest.getInstance(IoUtil.read(csrFile));
    Date notBefore = StringUtil.isNotBlank(notBeforeS) ? DateUtil.parseUtcTimeyyyyMMddhhmmss(notBeforeS) : null;
    Date notAfter = StringUtil.isNotBlank(notAfterS) ? DateUtil.parseUtcTimeyyyyMMddhhmmss(notAfterS) : null;
    EnrollCertResult result;
    RequestResponseDebug debug = getRequestResponseDebug();
    try {
        result = caClient.requestCert(caName, csr, profile, notBefore, notAfter, debug);
    } finally {
        saveRequestResponse(debug);
    }
    X509Certificate cert = null;
    if (result != null) {
        String id = result.getAllIds().iterator().next();
        CertOrError certOrError = result.getCertOrError(id);
        cert = (X509Certificate) certOrError.getCertificate();
    }
    if (cert == null) {
        throw new CmdFailure("no certificate received from the server");
    }
    File certFile = new File(outputFile);
    saveVerbose("certificate saved to file", certFile, cert.getEncoded());
    return null;
}
Also used : RequestResponseDebug(org.xipki.common.RequestResponseDebug) CmdFailure(org.xipki.console.karaf.CmdFailure) EnrollCertResult(org.xipki.ca.client.api.EnrollCertResult) CertOrError(org.xipki.ca.client.api.CertOrError) File(java.io.File) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 3 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class CmpCaClient method requestCertViaCsr.

// method parseEnrollCertResult
public X509Certificate requestCertViaCsr(String certProfile, CertificationRequest csr) throws Exception {
    ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(PKIHeader.CMP_2000, requestorSubject, responderSubject);
    builder.setMessageTime(new Date());
    builder.setTransactionID(randomTransactionId());
    builder.setSenderNonce(randomSenderNonce());
    builder.addGeneralInfo(new InfoTypeAndValue(CMPObjectIdentifiers.it_implicitConfirm, DERNull.INSTANCE));
    builder.addGeneralInfo(new InfoTypeAndValue(CMPObjectIdentifiers.regInfo_utf8Pairs, new DERUTF8String("CERT-PROFILE?" + certProfile + "%")));
    builder.setBody(new PKIBody(PKIBody.TYPE_P10_CERT_REQ, csr));
    ProtectedPKIMessage request = builder.build(requestorSigner);
    PKIMessage response = transmit(request);
    return parseEnrollCertResult(response);
}
Also used : ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) GeneralPKIMessage(org.bouncycastle.cert.cmp.GeneralPKIMessage) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) PKIBody(org.bouncycastle.asn1.cmp.PKIBody) InfoTypeAndValue(org.bouncycastle.asn1.cmp.InfoTypeAndValue) ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) ProtectedPKIMessageBuilder(org.bouncycastle.cert.cmp.ProtectedPKIMessageBuilder) Date(java.util.Date)

Example 4 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class RestCaClientExample method main.

public static void main(String[] args) {
    // System.setProperty("javax.net.debug", "all");
    try {
        RestCaClient client = new RestCaClient(CA_URL, USER, PASSWORD);
        client.init();
        // retrieve CA certificate
        printCert("===== CA Certificate (REST) =====", client.getCaCert());
        // Enroll certificate - RSA
        MyKeypair kp = generateRsaKeypair();
        CertificationRequest csr = genCsr(kp, getSubject());
        X509Certificate cert = client.requestCert(CERT_PROFILE, csr);
        printCert("===== RSA (REST) =====", cert);
        // Enroll certificate - EC
        kp = generateEcKeypair();
        csr = genCsr(kp, getSubject());
        cert = client.requestCert(CERT_PROFILE, csr);
        printCert("===== EC (REST) =====", cert);
        // Enroll certificate - DSA
        kp = generateDsaKeypair();
        csr = genCsr(kp, getSubject());
        cert = client.requestCert(CERT_PROFILE, csr);
        printCert("===== DSA =====", cert);
        BigInteger serialNumber = cert.getSerialNumber();
        // Suspend certificate
        boolean flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.certificateHold));
        if (flag) {
            System.out.println("(REST) suspended certificate");
        } else {
            System.err.println("(REST) suspending certificate failed");
        }
        // Unsuspend certificate
        flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.removeFromCRL));
        if (flag) {
            System.out.println("(REST) unsuspended certificate");
        } else {
            System.err.println("(REST) unsuspending certificate failed");
        }
        // Revoke certificate
        flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.keyCompromise));
        if (flag) {
            System.out.println("(REST) revoked certificate");
        } else {
            System.err.println("(REST) revoking certificate failed");
        }
        client.shutdown();
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(-1);
    }
}
Also used : RestCaClient(org.xipki.litecaclient.RestCaClient) BigInteger(java.math.BigInteger) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) X509Certificate(java.security.cert.X509Certificate)

Example 5 with CertificationRequest

use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class ScepClientExample method main.

public static void main(String[] args) {
    try {
        X509Certificate caCert = ScepUtil.parseCert(ScepUtil.read(new FileInputStream(expandPath(CA_CERT_FILE))));
        CaIdentifier tmpCaId = new CaIdentifier(CA_URL, null);
        CaCertValidator caCertValidator = new PreprovisionedCaCertValidator(caCert);
        ScepClient client = new ScepClient(tmpCaId, caCertValidator);
        client.init();
        // Self-Signed Identity Certificate
        MyKeypair keypair = generateRsaKeypair();
        CertificationRequest csr = genCsr(keypair, getSubject(), challengePassword);
        // self-signed cert must use the same subject as in CSR
        X500Name subjectDn = csr.getCertificationRequestInfo().getSubject();
        X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn, BigInteger.valueOf(1), new Date(), new Date(System.currentTimeMillis() + 24 * 3600 * 1000), subjectDn, keypair.getPublic());
        ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keypair.getPrivate());
        X509Certificate selfSignedCert = ScepUtil.parseCert(certGenerator.build(signer).getEncoded());
        // Enroll certificate - RSA
        EnrolmentResponse resp = (EnrolmentResponse) client.scepEnrol(csr, keypair.getPrivate(), selfSignedCert);
        if (resp.isFailure()) {
            throw new Exception("server returned 'failure'");
        }
        if (resp.isPending()) {
            throw new Exception("server returned 'pending'");
        }
        X509Certificate cert = resp.getCertificates().get(0);
        printCert("SCEP (RSA, Self-Signed Identity Cert)", cert);
        // Use the CA signed identity certificate
        X509Certificate identityCert = cert;
        PrivateKey identityKey = keypair.getPrivate();
        keypair = generateRsaKeypair();
        csr = genCsr(keypair, getSubject(), challengePassword);
        // Enroll certificate - RSA
        resp = (EnrolmentResponse) client.scepEnrol(csr, identityKey, identityCert);
        if (resp.isFailure()) {
            throw new Exception("server returned 'failure'");
        }
        if (resp.isPending()) {
            throw new Exception("server returned 'pending'");
        }
        cert = resp.getCertificates().get(0);
        printCert("SCEP (RSA, CA issued identity Cert)", cert);
        client.destroy();
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(-1);
    }
}
Also used : PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CaIdentifier(org.xipki.scep.client.CaIdentifier) ContentSigner(org.bouncycastle.operator.ContentSigner) ScepClient(org.xipki.scep.client.ScepClient) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) Date(java.util.Date) CaCertValidator(org.xipki.scep.client.CaCertValidator) PreprovisionedCaCertValidator(org.xipki.scep.client.PreprovisionedCaCertValidator) PreprovisionedCaCertValidator(org.xipki.scep.client.PreprovisionedCaCertValidator) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) EnrolmentResponse(org.xipki.scep.client.EnrolmentResponse) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Aggregations

CertificationRequest (org.bouncycastle.asn1.pkcs.CertificationRequest)17 X509Certificate (java.security.cert.X509Certificate)14 X500Name (org.bouncycastle.asn1.x500.X500Name)12 Date (java.util.Date)10 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)7 CertificateException (java.security.cert.CertificateException)6 CertificationRequestInfo (org.bouncycastle.asn1.pkcs.CertificationRequestInfo)6 Extensions (org.bouncycastle.asn1.x509.Extensions)6 OperationException (org.xipki.ca.api.OperationException)6 IOException (java.io.IOException)5 BigInteger (java.math.BigInteger)5 File (java.io.File)4 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)4 PKCS10CertificationRequest (org.bouncycastle.pkcs.PKCS10CertificationRequest)4 EnrolmentResponse (org.xipki.scep.client.EnrolmentResponse)4 ScepClient (org.xipki.scep.client.ScepClient)4 InvalidKeyException (java.security.InvalidKeyException)3 PrivateKey (java.security.PrivateKey)3 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)3 Certificate (org.bouncycastle.asn1.x509.Certificate)3