Example usage for org.bouncycastle.jce PKCS10CertificationRequest verify

List of usage examples for org.bouncycastle.jce PKCS10CertificationRequest verify

Introduction

In this page you can find the example usage for org.bouncycastle.jce PKCS10CertificationRequest verify.

Prototype

public boolean verify()
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException 

Source Link

Document

verify the request using the BC provider.

Usage

From source file:be.fedict.eid.pkira.crypto.csr.CSRParserImpl.java

License:Open Source License

private CSRInfo extractCSRInfo(PKCS10CertificationRequest certificationRequest) throws CryptoException {
    try {/*from   www  . j ava 2s .  c  om*/
        if (!certificationRequest.verify()) {
            throw new CryptoException("CSR signature is not correct.");
        }
    } catch (Exception e) {
        throw new CryptoException("Cannot verify CSR signature: " + e.getMessage(), e);
    }

    return new CSRInfo(certificationRequest);
}

From source file:com.jlocksmith.util.CertificateUtil.java

License:Open Source License

/**
 * Generate PKCS10 CSR/*  w w  w . j a  v  a2 s . c o m*/
 * 
 * @param cert X590 Certificate
 * @param privateKey Private Key
 * @param path File Path
 * 
 * @return String
 * @throws Exception
 */
public static void generatePKCS10CSR(X509Certificate cert, PrivateKey privateKey, String path)
        throws Exception {
    X509Name subject = new X509Name(cert.getSubjectDN().toString());

    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(cert.getSigAlgName(), subject,
            cert.getPublicKey(), null, privateKey);

    // Verify CSR
    csr.verify();

    // Get Base 64 encoding of CSR
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DEROutputStream dos = new DEROutputStream(baos);
    dos.writeObject(csr.getDERObject());
    String sTmp = new String(Base64.encode(baos.toByteArray()));

    // CSR Header
    String csrText = BEGIN_CERT_REQUEST + "\n";

    // Wrap lines
    for (int iCnt = 0; iCnt < sTmp.length(); iCnt += CERT_REQ_LINE_LENGTH) {
        int iLineLength;

        if ((iCnt + CERT_REQ_LINE_LENGTH) > sTmp.length()) {
            iLineLength = sTmp.length() - iCnt;
        } else {
            iLineLength = CERT_REQ_LINE_LENGTH;
        }

        csrText += sTmp.substring(iCnt, iCnt + iLineLength) + "\n";
    }

    // CSR Footer
    csrText += END_CERT_REQUEST + "\n";

    // Write it out to file
    FileWriter fw = null;

    try {
        fw = new FileWriter(path);
        fw.write(csrText);
    } catch (Exception err) {
        throw err;
    } finally {
        if (fw != null) {
            try {
                fw.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:de.mendelson.util.security.csr.CSRUtil.java

/**
 * Generates a PKCS10 CertificationRequest. The passed private key must not be trusted
 *//*from www  .  j a  va  2 s. c  om*/
public PKCS10CertificationRequest generateCSR(PrivateKey key, X509Certificate cert) throws Exception {
    X509Name subject = new X509Name(cert.getSubjectDN().toString());
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(cert.getSigAlgName(), subject,
            cert.getPublicKey(), null, key);
    boolean verified = csr.verify();
    if (!verified) {
        throw new Exception(this.rb.getResourceString("verification.failed"));
    }
    return (csr);
}

From source file:me.it_result.ca.bouncycastle.BouncyCA.java

License:Open Source License

@Override
public synchronized X509Certificate signCertificate(byte[] csrBytes) throws CAException {
    ensureInitialized();/*from  ww w.  ja  v  a 2s  .  co  m*/
    try {
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(csrBytes);
        if (!csr.verify())
            throw new CAException("CSR verification failed!");
        X509Name sn = csr.getCertificationRequestInfo().getSubject();
        PublicKey publicKey = csr.getPublicKey();
        KeyStore keyStore = loadKeystore();
        PrivateKey caPrivateKey = (PrivateKey) keyStore.getKey(CA_ALIAS, keystorePassword.toCharArray());
        PublicKey caPublicKey = keyStore.getCertificate(CA_ALIAS).getPublicKey();
        BigInteger serialNumber = nextSerialNumber();
        assembleCertificate(publicKey, caPublicKey, sn.toString(), issuer, serialNumber, false, validityDays);
        ASN1Set csrAttributes = csr.getCertificationRequestInfo().getAttributes();
        Profile profile = selectProfile(csrAttributes);
        profile.generateCertificateExtensions(csrAttributes, certGen);
        X509Certificate cert = certGen.generate(caPrivateKey);
        String alias = Utils.generateAlias(sn);
        keyStore.setCertificateEntry(alias, cert);
        saveKeystore(keyStore);
        incrementSerialNumber(serialNumber);
        return cert;
    } catch (Exception e) {
        throw new CAException(e);
    } finally {
        certGen.reset();
    }
}

From source file:org.cagrid.gaards.pki.BouncyCastleCertProcessingFactory.java

License:Open Source License

/**
 * Creates a proxy certificate from the certificate request. (Signs a
 * certificate request creating a new certificate)
 * /*ww  w.  jav  a2 s. co m*/
 * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int,
 *      int, X509ExtensionSet, String) createProxyCertificate
 * @param certRequestInputStream
 *            the input stream to read the certificate request from.
 * @param cert
 *            the issuer certificate
 * @param privateKey
 *            the private key to sign the new certificate with.
 * @param lifetime
 *            lifetime of the new certificate in seconds. If 0 (or less
 *            then) the new certificate will have the same lifetime as the
 *            issuing certificate.
 * @param delegationMode
 *            the type of proxy credential to create
 * @param extSet
 *            a set of X.509 extensions to be included in the new proxy
 *            certificate. Can be null. If delegation mode is
 *            {@link GSIConstants#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.GSI_3_RESTRICTED_PROXY} then
 *            {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension 
 *            ProxyCertInfoExtension} must be present in the extension set.
 * @param cnValue
 *            the value of the CN component of the subject of the new
 *            certificate. If null, the defaults will be used depending on
 *            the proxy certificate type created.
 * @return <code>X509Certificate</code> the new proxy certificate
 * @exception IOException
 *                if error reading the certificate request
 * @exception GeneralSecurityException
 *                if a security error occurs.
 */
public X509Certificate createCertificate(String provider, InputStream certRequestInputStream,
        X509Certificate cert, PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet,
        String cnValue, String signatureAlgorithm) throws IOException, GeneralSecurityException {

    DERInputStream derin = new DERInputStream(certRequestInputStream);
    DERObject reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo);

    boolean rs = certReq.verify();

    if (!rs) {
        throw new GeneralSecurityException("Certificate request verification failed!");
    }

    return createProxyCertificate(provider, cert, privateKey, certReq.getPublicKey(), lifetime, delegationMode,
            extSet, cnValue, signatureAlgorithm);
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionTest.java

License:Open Source License

/**
 * tests bouncy PKCS10/*from w  w w . j  av  a2  s  . c o  m*/
 * 
 * @throws Exception
 *             if en error occurs...
 */
public void test03TestBCPKCS10() throws Exception {
    log.trace(">test03TestBCPKCS10()");
    userAdminSession.setUserStatus(admin, "foo", UserDataConstants.STATUS_NEW);
    log.debug("Reset status of 'foo' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA1WithRSA",
            CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=foo"), rsakeys.getPublic(), new DERSet(),
            rsakeys.getPrivate());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req);
    dOut.close();

    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    boolean verify = req2.verify();
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername("foo");
    p10.setPassword("foo123");
    IResponseMessage resp = signSession.createCertificate(admin, p10,
            org.ejbca.core.protocol.X509ResponseMessage.class, null);
    Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());

    // Verify error handling
    UserDataVO badUserData = new UserDataVO();
    badUserData.setCAId(rsacaid);
    p10 = new PKCS10RequestMessage(bcp10);
    try {
        signSession.createCertificate(admin, p10, org.ejbca.core.protocol.X509ResponseMessage.class,
                badUserData);
        assertFalse("Was able to create certificate when it should have failed.", true);
    } catch (SignRequestException e) {
        log.info("Expected exception caught (no password supplied): " + e.getMessage());
    }
    log.trace("<test03TestBCPKCS10()");
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionTest.java

License:Open Source License

/**
 * tests bouncy PKCS10//from  w w w  . j  a va 2 s.c  om
 * 
 * @throws Exception
 *             if en error occurs...
 */
public void test13TestBCPKCS10ECDSAWithRSACA() throws Exception {
    log.trace(">test13TestBCPKCS10ECDSAWithRSACA()");
    userAdminSession.setUserStatus(admin, "foo", UserDataConstants.STATUS_NEW);
    log.debug("Reset status of 'foo' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA256WithECDSA",
            CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=foo"), ecdsakeys.getPublic(), new DERSet(),
            ecdsakeys.getPrivate());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req);
    dOut.close();

    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    boolean verify = req2.verify();
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername("foo");
    p10.setPassword("foo123");
    IResponseMessage resp = signSession.createCertificate(admin, p10,
            org.ejbca.core.protocol.X509ResponseMessage.class, null);
    Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof JCEECPublicKey) {
        JCEECPublicKey ecpk = (JCEECPublicKey) pk;
        assertEquals(ecpk.getAlgorithm(), "EC");
        org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
        assertNotNull("ImplicitlyCA must have null spec", spec);
    } else {
        assertTrue("Public key is not EC", false);
    }
    try {
        cert.verify(rsacacert.getPublicKey());
    } catch (Exception e) {
        assertTrue("Verify failed: " + e.getMessage(), false);
    }
    log.trace("<test13TestBCPKCS10ECDSAWithRSACA()");
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionTest.java

License:Open Source License

/**
 * tests bouncy PKCS10/* w ww .jav  a  2 s.  c  o m*/
 * 
 * @throws Exception
 *             if en error occurs...
 */
public void test15TestBCPKCS10ECDSAWithECDSACA() throws Exception {
    log.trace(">test15TestBCPKCS10ECDSAWithECDSACA()");
    userAdminSession.setUserStatus(admin, "fooecdsa", UserDataConstants.STATUS_NEW);
    log.debug("Reset status of 'foo' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA256WithECDSA",
            CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=fooecdsa"), ecdsakeys.getPublic(), new DERSet(),
            ecdsakeys.getPrivate());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req);
    dOut.close();

    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    boolean verify = req2.verify();
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername("fooecdsa");
    p10.setPassword("foo123");
    IResponseMessage resp = signSession.createCertificate(admin, p10,
            org.ejbca.core.protocol.X509ResponseMessage.class, null);
    Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof JCEECPublicKey) {
        JCEECPublicKey ecpk = (JCEECPublicKey) pk;
        assertEquals(ecpk.getAlgorithm(), "EC");
        org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
        assertNotNull("ImplicitlyCA must have null spec", spec);
    } else {
        assertTrue("Public key is not EC", false);
    }
    try {
        cert.verify(ecdsacacert.getPublicKey());
    } catch (Exception e) {
        assertTrue("Verify failed: " + e.getMessage(), false);
    }
    log.trace("<test15TestBCPKCS10ECDSAWithECDSACA()");
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionTest.java

License:Open Source License

/**
 * tests bouncy PKCS10/*ww  w. j a va2 s  . c  om*/
 * 
 * @throws Exception
 *             if en error occurs...
 */
public void test17TestBCPKCS10ECDSAWithECDSAImplicitlyCACA() throws Exception {
    log.trace(">test17TestBCPKCS10ECDSAWithECDSAImplicitlyCACA()");
    userAdminSession.setUserStatus(admin, "fooecdsaimpca", UserDataConstants.STATUS_NEW);
    log.debug("Reset status of 'foo' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA256WithECDSA",
            CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=fooecdsaimpca"), ecdsakeys.getPublic(),
            new DERSet(), ecdsakeys.getPrivate());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req);
    dOut.close();

    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    boolean verify = req2.verify();
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername("fooecdsaimpca");
    p10.setPassword("foo123");
    IResponseMessage resp = signSession.createCertificate(admin, p10,
            org.ejbca.core.protocol.X509ResponseMessage.class, null);
    Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof JCEECPublicKey) {
        JCEECPublicKey ecpk = (JCEECPublicKey) pk;
        assertEquals(ecpk.getAlgorithm(), "EC");
        org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters();
        assertNotNull("ImplicitlyCA must have null spec", spec);
    } else {
        assertTrue("Public key is not EC", false);
    }
    try {
        cert.verify(ecdsaimplicitlycacacert.getPublicKey());
    } catch (Exception e) {
        assertTrue("Verify failed: " + e.getMessage(), false);
    }
    log.trace("<test17TestBCPKCS10ECDSAWithECDSAImplicitlyCACA()");
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionTest.java

License:Open Source License

/**
 * tests bouncy PKCS10/*from ww  w .java2  s  .  c  o m*/
 * 
 * @throws Exception
 *             if en error occurs...
 */
public void test19TestBCPKCS10RSAWithRSASha256WithMGF1CA() throws Exception {
    log.trace(">test19TestBCPKCS10RSAWithRSASha256WithMGF1CA()");
    userAdminSession.setUserStatus(admin, "foorsamgf1ca", UserDataConstants.STATUS_NEW);
    log.debug("Reset status of 'foorsamgf1ca' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = new PKCS10CertificationRequest(
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA_AND_MGF1,
            CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=foorsamgf1ca"), rsakeys.getPublic(), new DERSet(),
            rsakeys.getPrivate());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req);
    dOut.close();

    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    boolean verify = req2.verify();
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername("foorsamgf1ca");
    p10.setPassword("foo123");
    IResponseMessage resp = signSession.createCertificate(admin, p10,
            org.ejbca.core.protocol.X509ResponseMessage.class, null);
    X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
    // X509Certificate cert =
    // CertTools.getCertfromByteArray(retcert.getEncoded());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());
    // FileOutputStream fos = new FileOutputStream("/tmp/testcert1.crt");
    // fos.write(cert.getEncoded());
    // fos.close();
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pk;
        assertEquals(rsapk.getAlgorithm(), "RSA");
    } else {
        assertTrue("Public key is not RSA", false);
    }
    try {
        cert.verify(rsamgf1cacacert.getPublicKey());
    } catch (Exception e) {
        assertTrue("Verify failed: " + e.getMessage(), false);
    }
    // 1.2.840.113549.1.1.10 is SHA256WithRSAAndMGF1
    assertEquals("1.2.840.113549.1.1.10", cert.getSigAlgOID());
    assertEquals("1.2.840.113549.1.1.10", cert.getSigAlgName());
    assertEquals("1.2.840.113549.1.1.10", rsamgf1cacacert.getSigAlgOID());
    assertEquals("1.2.840.113549.1.1.10", rsamgf1cacacert.getSigAlgName());

    log.trace("<test19TestBCPKCS10RSAWithRSASha256WithMGF1CA()");
}