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:org.ejbca.core.ejb.ca.sign.SignSessionTest.java

License:Open Source License

/**
 * tests bouncy PKCS10/*ww w.ja v a 2 s.c o  m*/
 * 
 * @throws Exception
 *             if en error occurs...
 */
public void test24TestBCPKCS10DSAWithRSACA() throws Exception {
    log.trace(">test24TestBCPKCS10DSAWithRSACA()");
    userAdminSession.setUserStatus(admin, "foo", UserDataConstants.STATUS_NEW);
    log.debug("Reset status of 'foo' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA1WithDSA",
            CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=foo"), dsakeys.getPublic(), new DERSet(),
            dsakeys.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 DSAPublicKey) {
        DSAPublicKey dsapk = (DSAPublicKey) pk;
        assertEquals(dsapk.getAlgorithm(), "DSA");
    } else {
        assertTrue("Public key is not DSA", false);
    }
    try {
        cert.verify(rsacacert.getPublicKey());
    } catch (Exception e) {
        assertTrue("Verify failed: " + e.getMessage(), false);
    }
    log.trace("<test24TestBCPKCS10DSAWithRSACA()");
}

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  2s  .  c om
 * 
 * @throws Exception
 *             if en error occurs...
 */
public void test26TestBCPKCS10DSAWithDSACA() throws Exception {
    log.trace(">test26TestBCPKCS10DSAWithDSACA()");
    userAdminSession.setUserStatus(admin, "foodsa", UserDataConstants.STATUS_NEW);
    log.debug("Reset status of 'foodsa' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA1WithDSA",
            CertTools.stringToBcX509Name("C=SE, O=AnaTom, CN=foodsa"), dsakeys.getPublic(), new DERSet(),
            dsakeys.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("foodsa");
    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 DSAPublicKey) {
        DSAPublicKey dsapk = (DSAPublicKey) pk;
        assertEquals(dsapk.getAlgorithm(), "DSA");
    } else {
        assertTrue("Public key is not DSA", false);
    }
    try {
        cert.verify(dsacacert.getPublicKey());
    } catch (Exception e) {
        assertTrue("Verify failed: " + e.getMessage(), false);
    }
    log.trace("<test26TestBCPKCS10DSAWithDSACA()");
}

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

License:Open Source License

public void test28TestDNOverride() throws Exception {
    // Create a good certificate profile (good enough), using QC statement
    certificateProfileSession.removeCertificateProfile(admin, "TESTDNOVERRIDE");
    EndUserCertificateProfile certprof = new EndUserCertificateProfile();
    // Default profile does not allow DN override
    certprof.setValidity(298);/*from   w  w  w .  j a  v a  2  s .c om*/
    certificateProfileSession.addCertificateProfile(admin, "TESTDNOVERRIDE", certprof);
    int cprofile = certificateProfileSession.getCertificateProfileId(admin, "TESTDNOVERRIDE");

    // Create a good end entity profile (good enough), allowing multiple UPN
    // names
    endEntityProfileSession.removeEndEntityProfile(admin, "TESTDNOVERRIDE");
    EndEntityProfile profile = new EndEntityProfile();
    profile.addField(DnComponents.COUNTRY);
    profile.addField(DnComponents.COMMONNAME);
    profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS));
    profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cprofile));
    endEntityProfileSession.addEndEntityProfile(admin, "TESTDNOVERRIDE", profile);
    int eeprofile = endEntityProfileSession.getEndEntityProfileId(admin, "TESTDNOVERRIDE");
    UserDataVO user = new UserDataVO("foo", "C=SE,CN=dnoverride", rsacaid, null, "foo@anatom.nu",
            SecConst.USER_ENDUSER, eeprofile, cprofile, SecConst.TOKEN_SOFT_PEM, 0, null);
    user.setPassword("foo123");
    user.setStatus(UserDataConstants.STATUS_NEW);
    // Change a user that we know...
    userAdminSession.changeUser(admin, user, false);

    // Create a P10 with strange order DN
    PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA1WithRSA",
            new X509Name("CN=foo,C=SE, Name=AnaTom, O=My org"), 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);

    // PKCS10RequestMessage p10 = new PKCS10RequestMessage(iep10);
    p10.setUsername("foo");
    p10.setPassword("foo123");
    IResponseMessage resp = signSession.createCertificate(admin, p10,
            org.ejbca.core.protocol.X509ResponseMessage.class, null);
    X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    assertEquals("CN=dnoverride,C=SE", cert.getSubjectDN().getName());

    // Change so that we allow override of validity time
    CertificateProfile prof = certificateProfileSession.getCertificateProfile(admin, cprofile);
    prof.setAllowDNOverride(true);
    certificateProfileSession.changeCertificateProfile(admin, "TESTDNOVERRIDE", prof);

    userAdminSession.changeUser(admin, user, false);
    resp = signSession.createCertificate(admin, p10, org.ejbca.core.protocol.X509ResponseMessage.class, null);
    cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    assertEquals("CN=foo,C=SE,Name=AnaTom,O=My org", cert.getSubjectDN().getName());

}

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Creates a proxy certificate from a certificate request
 * //  www . j a va2s.  c om
 * @param inCertReq
 *            Certificate request
 * @param inUserCert
 *            Issuer certificate
 * @param inUserKey
 *            Issuer privateKey
 * @param pwd
 *            Issuer password
 * @return chaine of certificate containing proxy in first place
 * @deprecated Use proxy generator from util-java
 */
public byte[] x509MakeProxyCert(byte[] inCertReq, byte[] inUserCert, byte[] inUserKey, String pwd1)
        throws CertificateException, GeneralSecurityException, Exception {
    X509Certificate[] userCert = null;
    PrivateKey pvk = null;

    // Read certificate request
    InputStream inTCertReq = null;

    inTCertReq = new ByteArrayInputStream(
            GrDPX509Util.readPEM(new ByteArrayInputStream(inCertReq), GrDPConstants.CRH, GrDPConstants.CRF));

    if ((inUserCert != null) && (inUserKey != null)) {
        // Reading chain of certificates from input stream
        userCert = GrDPX509Util
                .loadCertificateChain(new BufferedInputStream(new ByteArrayInputStream(inUserCert)));

        if (userCert.length <= 0) {
            logger.error("Invalid user certificate. Number of certificates in chain : " + userCert.length);
            throw new GeneralSecurityException("Invalid user certificate.");
        }

        pvk = PrivateKeyReader.read(new BufferedInputStream(new ByteArrayInputStream(inUserKey)), pwd1);
    } else {
        logger.error("Error, CreateProxyFromCertReq :: UserCertificate and UserKey can not be null.");
        throw new CertificateException(
                "Error, CreateProxyFromCertReq :: UserCertificate and UserKey can not be null.");
    }

    // Loading chian of certificates
    X509Certificate[] cp = new X509Certificate[userCert.length + 1];

    ASN1InputStream derin = new ASN1InputStream(inTCertReq);
    DERObject reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((DERSequence) reqInfo);
    logger.debug("Number of Certificates in chain : " + Integer.toString(userCert.length));

    if (!certReq.verify()) {
        throw new GeneralSecurityException("Certificate request verification failed!");
    }

    // Generating proxy certificate
    cp[0] = createProxyCertificate(userCert[0], pvk, certReq.getPublicKey(), lifetime, proxyType, "proxy");

    for (int index = 1; index <= userCert.length; ++index)
        cp[index] = userCert[index - 1];

    certProxy = cp[0];

    return GrDPX509Util.certChainToByte(cp);
}

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Creates a proxy certificate from a certificate request and a proxy
 * certificate//from  w  w w  .  jav  a 2s .c o  m
 * 
 * @param inCertReq
 *            Certificate request
 * @param inProxy
 *            user proxy certificate 
 *            
 * @return chaine of certificate containing proxy in first place
 * @deprecated Use proxy generator from util-java
 */
public byte[] x509MakeProxyCert(byte[] inCertReq, byte[] inProxy) throws IOException, GeneralSecurityException {

    // Holds the cert chain loaded from the proxy file
    X509Certificate[] proxyCertChain = null;

    // Holds the priv key loaded from the proxy file
    PrivateKey proxyPrivKey = null;

    // Holds the final certificate chain of the proxy
    X509Certificate[] finalCertChain = null;

    // Load the proxy certificate chain
    proxyCertChain = GrDPX509Util
            .loadCertificateChain(new BufferedInputStream(new ByteArrayInputStream(inProxy)));

    // Check for null arguments
    if (inCertReq == null || inProxy == null) {
        throw new GeneralSecurityException(
                "Either the cert request or proxy cert were passed as null arguments." + " Cannot continue.");
    }

    // Check for a valid chain
    if (proxyCertChain.length <= 0) {
        throw new GeneralSecurityException(
                "Invalid number of certificates in proxy chain: " + proxyCertChain.length);
    }
    logger.debug("Number of certificates in proxy chain: " + proxyCertChain.length);

    // Reading private key form proxy file
    FileCertReader fileReader = new FileCertReader();
    KeyStore store = fileReader.readProxy(new BufferedInputStream(new ByteArrayInputStream(inProxy)),
            "keypair");
    proxyPrivKey = (PrivateKey) store.getKey("host", "keypair".toCharArray());

    // Load the certificate request
    InputStream inTCertReq = new ByteArrayInputStream(
            GrDPX509Util.readPEM(new ByteArrayInputStream(inCertReq), GrDPConstants.CRH, GrDPConstants.CRF));
    ASN1InputStream derin = new ASN1InputStream(inTCertReq);
    DERObject reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((DERSequence) reqInfo);

    // Verify cert request validity
    if (!certReq.verify()) {
        throw new GeneralSecurityException("Certificate request verification failed!");
    }

    // Generating proxy certificate
    finalCertChain = new X509Certificate[proxyCertChain.length + 1];
    finalCertChain[0] = createProxyCertificate(proxyCertChain[0], proxyPrivKey, certReq.getPublicKey(),
            lifetime, proxyType, "proxy");

    for (int i = 0; i < proxyCertChain.length; ++i) {
        finalCertChain[i + 1] = proxyCertChain[i];
    }

    // TODO: this should be removed at some point
    certProxy = finalCertChain[0];

    return GrDPX509Util.certChainToByte(finalCertChain);
}

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Creates a proxy certificate from a certificate request
 * //  w  w  w.  jav  a 2 s  .  c  o  m
 * @param inCertReq
 *            Certificate request
 * @param inUserCert
 *            Issuer certificate
 * @param inUserKey
 *            Issuer privateKey
 * @param pwd
 *            Issuer password
 * @return chaine of certificate containing proxy in first place
 * @deprecated Use proxy generator from util-java
 */
public X509Certificate[] createProxyFromCertReq(InputStream inCertReq, BufferedInputStream inUserCert,
        InputStream inUserKey, String pwd1) throws GeneralSecurityException, IOException, Exception {

    X509Certificate[] userCert = null;
    PrivateKey userPrivKey = null;
    PKCS10CertificationRequest certRequest = null;
    X509Certificate[] proxyCert = null;

    // Load the user certificate
    userCert = GrDPX509Util.loadCertificateChain(inUserCert);
    logger.debug("User Certificate - number of certificates in chain: " + userCert.length);

    // Load the private key
    userPrivKey = PrivateKeyReader.read(new BufferedInputStream(inUserKey), pwd1);

    // Load the certificate request
    ASN1InputStream derin = new ASN1InputStream(
            new ByteArrayInputStream(GrDPX509Util.readPEM(inCertReq, GrDPConstants.CRH, GrDPConstants.CRF)));
    DERObject reqInfo = derin.readObject();
    certRequest = new PKCS10CertificationRequest((DERSequence) reqInfo);

    // Initialize the proxy certificate chain
    proxyCert = new X509Certificate[userCert.length + 1];

    // Verify integrity of certificate request
    if (!certRequest.verify()) {
        throw new GeneralSecurityException("Certificate request verification failed.");
    }

    // Create the proxy certificate
    proxyCert[0] = createProxyCertificate(userCert[0], userPrivKey, certRequest.getPublicKey(), lifetime,
            proxyType, "proxy");

    // Complete the proxy certificate chain
    for (int index = 1; index <= userCert.length; ++index)
        proxyCert[index] = userCert[index - 1];

    certProxy = proxyCert[0];

    return proxyCert;
}

From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java

License:Apache License

/**
 * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new
 * certificate)//  ww  w  .  ja v  a 2s .  c  om
 *
 * @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 org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_4_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.
 * @deprecated
 */
public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
        PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet, String cnValue)
        throws IOException, GeneralSecurityException {

    ASN1InputStream derin = new ASN1InputStream(certRequestInputStream);
    ASN1Primitive reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo);

    boolean rs = certReq.verify();

    if (!rs) {
        String err = i18n.getMessage("certReqVerification");
        throw new GeneralSecurityException(err);
    }

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

From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java

License:Apache License

/**
 * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new
 * certificate)//from  w  w  w. jav  a 2 s  .  c  o 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 certType
 *            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 org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_4_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(InputStream certRequestInputStream, X509Certificate cert,
        PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet,
        String cnValue) throws IOException, GeneralSecurityException {

    ASN1InputStream derin = new ASN1InputStream(certRequestInputStream);
    ASN1Primitive reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo);

    boolean rs = certReq.verify();

    if (!rs) {
        String err = i18n.getMessage("certReqVerification");
        throw new GeneralSecurityException(err);
    }

    return createProxyCertificate(cert, privateKey, certReq.getPublicKey(), lifetime, certType, extSet,
            cnValue);
}

From source file:org.votingsystem.signature.util.CertUtils.java

License:Open Source License

/**
 * Generate V3 Certificate from CSR/* w  w  w.  j a va 2  s  .c o  m*/
 */
public static X509Certificate signCSR(PKCS10CertificationRequest csr, String organizationalUnit,
        PrivateKey caKey, X509Certificate caCert, Date dateBegin, Date dateFinish,
        DERTaggedObject... certExtensions) throws Exception {
    String strSubjectDN = csr.getCertificationRequestInfo().getSubject().toString();
    if (!csr.verify() || strSubjectDN == null)
        throw new Exception("ERROR VERIFYING CSR");
    if (organizationalUnit != null)
        strSubjectDN = organizationalUnit + "," + strSubjectDN;
    X509Certificate issuedCert = generateV3EndEntityCertFromCsr(csr, caKey, caCert, dateBegin, dateFinish,
            strSubjectDN, certExtensions);
    return issuedCert;
}