Example usage for org.bouncycastle.pkcs PKCS10CertificationRequest isSignatureValid

List of usage examples for org.bouncycastle.pkcs PKCS10CertificationRequest isSignatureValid

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs PKCS10CertificationRequest isSignatureValid.

Prototype

public boolean isSignatureValid(ContentVerifierProvider verifierProvider) throws PKCSException 

Source Link

Document

Validate the signature on the PKCS10 certification request in this holder.

Usage

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

License:Open Source License

@Test
public void testBCPKCS10ECDSAWithECDSAImplicitlyCACA() throws Exception {
    log.trace(">test17TestBCPKCS10ECDSAWithECDSAImplicitlyCACA()");
    final String ecDsaImplicitCaUserName = "fooecdsaimpca";
    CAInfo infoecdsaimplicitlyca = caSession.getCAInfo(internalAdmin, TEST_ECDSA_IMPLICIT_CA_NAME);
    int ecdsaimplicitlycacaid = infoecdsaimplicitlyca.getCAId();
    createEndEntity(ecDsaImplicitCaUserName, SecConst.EMPTY_ENDENTITYPROFILE,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, ecdsaimplicitlycacaid);
    try {/*from ww w.  j  a va2 s  . c  o m*/
        endEntityManagementSession.setUserStatus(internalAdmin, ecDsaImplicitCaUserName,
                EndEntityConstants.STATUS_NEW);
        log.debug("Reset status of 'foo' to NEW");
        // Create certificate request
        PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithECDSA",
                CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=" + ecDsaImplicitCaUserName),
                ecdsakeys.getPublic(), new DERSet(), ecdsakeys.getPrivate(), null);
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(req.toASN1Structure());
        dOut.close();
        PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
        ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(ecdsakeys.getPublic());
        boolean verify = req2.isSignatureValid(verifier);
        log.debug("Verify returned " + verify);
        assertTrue(verify);
        log.debug("CertificationRequest generated successfully.");
        byte[] bcp10 = bOut.toByteArray();
        PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
        p10.setUsername(ecDsaImplicitCaUserName);
        p10.setPassword("foo123");
        ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class,
                null);
        Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
        assertNotNull("Failed to create certificate", cert);
        log.debug("Cert=" + cert.toString());
        X509Certificate ecdsaimplicitlycacacert = (X509Certificate) caSession
                .getCAInfo(internalAdmin, TEST_ECDSA_IMPLICIT_CA_NAME).getCertificateChain().toArray()[0];
        try {
            cert.verify(ecdsaimplicitlycacacert.getPublicKey());
        } catch (Exception e) {
            assertTrue("Verify failed: " + e.getMessage(), false);
        }
    } finally {
        endEntityManagementSession.deleteUser(internalAdmin, ecDsaImplicitCaUserName);
    }
    log.trace("<test17TestBCPKCS10ECDSAWithECDSAImplicitlyCACA()");
}

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

License:Open Source License

/**
 * tests bouncy PKCS10//from   w  w w . j ava  2s .co  m
 * 
 */
@Test
public void testBCPKCS10RSAWithRSASha256WithMGF1CA() throws Exception {
    log.trace(">test19TestBCPKCS10RSAWithRSASha256WithMGF1CA()");
    endEntityManagementSession.setUserStatus(internalAdmin, RSA_MFG1_ENTITY_NAME,
            EndEntityConstants.STATUS_NEW);
    log.debug("Reset status of 'foorsamgf1ca' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest(
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA_AND_MGF1,
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=" + RSA_MFG1_ENTITY_NAME), rsakeys.getPublic(),
            new DERSet(), rsakeys.getPrivate(), null);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();
    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(rsakeys.getPublic());
    boolean verify = req2.isSignatureValid(verifier);
    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");
    ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null);
    X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pk;
        assertEquals(rsapk.getAlgorithm(), "RSA");
    } else {
        assertTrue("Public key is not RSA", false);
    }
    X509Certificate rsamgf1cacacert = (X509Certificate) caSession
            .getCAInfo(internalAdmin, TEST_SHA256_WITH_MFG1_CA_NAME).getCertificateChain().toArray()[0];
    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()");
}

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

License:Open Source License

/**
 * tests bouncy PKCS10//from   ww w.j  a  va  2 s .c o m
 * 
 */
@Test
public void testBCPKCS10() throws Exception {
    log.trace(">test03TestBCPKCS10()");
    endEntityManagementSession.setUserStatus(internalAdmin, RSA_USERNAME, EndEntityConstants.STATUS_NEW);
    log.debug("Reset status of 'foo' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=foo"), rsakeys.getPublic(), new DERSet(),
            rsakeys.getPrivate(), null);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();
    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(rsakeys.getPublic());
    boolean verify = req2.isSignatureValid(verifier);
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername(RSA_USERNAME);
    p10.setPassword("foo123");
    ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null);
    Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());
    // Verify error handling
    EndEntityInformation badUserData = new EndEntityInformation();
    int rsacaid = caSession.getCAInfo(internalAdmin, getTestCAName()).getCAId();
    badUserData.setCAId(rsacaid);
    p10 = new PKCS10RequestMessage(bcp10);
    try {
        signSession.createCertificate(internalAdmin, p10, 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.SignSessionWithRsaTest.java

License:Open Source License

@Test
public void testDNOverride() throws Exception {
    // Create a good certificate profile (good enough), using QC statement
    certificateProfileSession.removeCertificateProfile(internalAdmin, "TESTDNOVERRIDE");
    final CertificateProfile certprof = new CertificateProfile(
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    // Default profile does not allow DN override
    certprof.setValidity(298);//  ww w .ja v a  2 s  .c  o  m
    certificateProfileSession.addCertificateProfile(internalAdmin, "TESTDNOVERRIDE", certprof);
    int cprofile = certificateProfileSession.getCertificateProfileId("TESTDNOVERRIDE");
    // Create a good end entity profile (good enough), allowing multiple UPN
    // names
    endEntityProfileSession.removeEndEntityProfile(internalAdmin, "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(internalAdmin, "TESTDNOVERRIDE", profile);
    int eeprofile = endEntityProfileSession.getEndEntityProfileId("TESTDNOVERRIDE");
    int rsacaid = caSession.getCAInfo(internalAdmin, getTestCAName()).getCAId();
    final String dnOverrideEndEntityName = "DnOverride";
    createEndEntity(dnOverrideEndEntityName, eeprofile, cprofile, rsacaid);
    try {
        EndEntityInformation user = new EndEntityInformation(dnOverrideEndEntityName, "C=SE,CN=dnoverride",
                rsacaid, null, "foo@anatom.nu", new EndEntityType(EndEntityTypes.ENDUSER), eeprofile, cprofile,
                SecConst.TOKEN_SOFT_PEM, 0, null);
        user.setPassword("foo123");
        user.setStatus(EndEntityConstants.STATUS_NEW);
        // Change a user that we know...
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        // Create a P10 with strange order DN
        PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                new X500Name("CN=foo,C=SE,NAME=AnaTom,O=My org"), rsakeys.getPublic(), new DERSet(),
                rsakeys.getPrivate(), null);
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(req.toASN1Structure());
        dOut.close();
        PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
        ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(rsakeys.getPublic());
        boolean verify = req2.isSignatureValid(verifier);
        log.debug("Verify returned " + verify);
        assertTrue(verify);
        log.debug("CertificationRequest generated successfully.");
        byte[] bcp10 = bOut.toByteArray();
        PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
        p10.setUsername(dnOverrideEndEntityName);
        p10.setPassword("foo123");
        ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, 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(cprofile);
        prof.setAllowDNOverride(true);
        certificateProfileSession.changeCertificateProfile(internalAdmin, "TESTDNOVERRIDE", prof);
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        resp = signSession.createCertificate(internalAdmin, p10, 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());
    } finally {
        endEntityManagementSession.deleteUser(internalAdmin, dnOverrideEndEntityName);
    }
}

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

License:Open Source License

@Test
public void testBCPKCS10DSAWithRSACA() throws Exception {
    log.trace(">test24TestBCPKCS10DSAWithRSACA()");

    endEntityManagementSession.setUserStatus(internalAdmin, RSA_USERNAME, EndEntityConstants.STATUS_NEW);
    log.debug("Reset status of 'foo' to NEW");
    // Create certificate request
    KeyPair dsakeys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_DSA);
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithDSA",
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=foo"), dsakeys.getPublic(), new DERSet(),
            dsakeys.getPrivate(), null);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();//w  w  w  .ja  v a2 s.  c  om

    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(dsakeys.getPublic());
    boolean verify = req2.isSignatureValid(verifier);
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername(RSA_USERNAME);
    p10.setPassword("foo123");
    ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, 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 {
        fail("Public key is not DSA");
    }
    try {
        X509Certificate rsacacert = (X509Certificate) caSession.getCAInfo(internalAdmin, getTestCAName())
                .getCertificateChain().toArray()[0];
        cert.verify(rsacacert.getPublicKey());
    } catch (Exception e) {
        fail("Verify failed: " + e.getMessage());
    }
    log.trace("<test24TestBCPKCS10DSAWithRSACA()");
}

From source file:org.ejbca.ui.cli.ca.BaseCaAdminCommand.java

License:Open Source License

protected void makeCertRequest(String dn, KeyPair rsaKeys, String reqfile)
        throws NoSuchAlgorithmException, IOException, NoSuchProviderException, InvalidKeyException,
        SignatureException, OperatorCreationException, PKCSException {
    log.trace(">makeCertRequest: dn='" + dn + "', reqfile='" + reqfile + "'.");

    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithRSA",
            CertTools.stringToBcX500Name(dn), rsaKeys.getPublic(), new DERSet(), rsaKeys.getPrivate(), null);

    /*/*from   www. ja v  a 2 s . c  o m*/
     * We don't use these unnecessary attributes DERConstructedSequence kName
     * = new DERConstructedSequence(); DERConstructedSet kSeq = new
     * DERConstructedSet();
     * kName.addObject(PKCSObjectIdentifiers.pkcs_9_at_emailAddress);
     * kSeq.addObject(new DERIA5String("foo@bar.se"));
     * kName.addObject(kSeq); req.setAttributes(kName);
     */
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();

    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    ContentVerifierProvider contentVerifier = CertTools.genContentVerifierProvider(rsaKeys.getPublic());
    boolean verify = req2.isSignatureValid(contentVerifier); //req2.verify();
    log.info("Verify returned " + verify);

    if (verify == false) {
        log.info("Aborting!");
        return;
    }

    FileOutputStream os1 = new FileOutputStream(reqfile);
    os1.write("-----BEGIN CERTIFICATE REQUEST-----\n".getBytes());
    os1.write(Base64.encode(bOut.toByteArray()));
    os1.write("\n-----END CERTIFICATE REQUEST-----\n".getBytes());
    os1.close();
    log.info("CertificationRequest '" + reqfile + "' generated successfully.");
    log.trace("<makeCertRequest: dn='" + dn + "', reqfile='" + reqfile + "'.");
}

From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java

License:Open Source License

@Override
public void generateCertReq(String alias, String sDN, boolean explicitEccParameters) throws Exception {
    PublicKey publicKey = getCertificate(alias).getPublicKey();
    final PrivateKey privateKey = getPrivateKey(alias);
    if (log.isDebugEnabled()) {
        log.debug("alias: " + alias + " SHA1 of public key: "
                + CertTools.getFingerprintAsString(publicKey.getEncoded()));
    }/*from www .j av a2 s . com*/
    String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(publicKey).iterator().next();
    if (sigAlg == null) {
        sigAlg = "SHA1WithRSA";
    }
    if (sigAlg.contains("ECDSA") && explicitEccParameters) {
        log.info("Using explicit parameter encoding for ECC key.");
        publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
    } else {
        log.info("Using named curve parameter encoding for ECC key.");
    }
    X500Name sDNName = sDN != null ? new X500Name(sDN) : new X500Name("CN=" + alias);
    final PKCS10CertificationRequest certReq = CertTools.genPKCS10CertificationRequest(sigAlg, sDNName,
            publicKey, new DERSet(), privateKey, this.keyStore.getProvider().getName());
    ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(publicKey);
    if (!certReq.isSignatureValid(verifier)) {
        String msg = intres.getLocalizedMessage("token.errorcertreqverify", alias);
        throw new Exception(msg);
    }
    String filename = alias + ".pem";
    final Writer writer = new FileWriter(filename);
    writer.write(CertTools.BEGIN_CERTIFICATE_REQUEST + "\n");
    writer.write(new String(Base64.encode(certReq.getEncoded())));
    writer.write("\n" + CertTools.END_CERTIFICATE_REQUEST + "\n");
    writer.close();
    log.info("Wrote csr to file: " + filename);
}

From source file:org.xipki.commons.security.SecurityFactoryImpl.java

License:Open Source License

@Override
public boolean verifyPopo(final PKCS10CertificationRequest csr, final AlgorithmValidator algoValidator) {
    if (algoValidator != null) {
        AlgorithmIdentifier algId = csr.getSignatureAlgorithm();
        if (!algoValidator.isAlgorithmPermitted(algId)) {
            String algoName;/*from   w  w w.j  a v  a 2 s  . c  o m*/
            try {
                algoName = AlgorithmUtil.getSignatureAlgoName(algId);
            } catch (NoSuchAlgorithmException ex) {
                algoName = algId.getAlgorithm().getId();
            }

            LOG.error("POPO signature algorithm {} not permitted", algoName);
            return false;
        }
    }

    try {
        SubjectPublicKeyInfo pkInfo = csr.getSubjectPublicKeyInfo();
        PublicKey pk = KeyUtil.generatePublicKey(pkInfo);
        ContentVerifierProvider cvp = getContentVerifierProvider(pk);
        return csr.isSignatureValid(cvp);
    } catch (InvalidKeyException | PKCSException | NoSuchAlgorithmException | InvalidKeySpecException ex) {
        LogUtil.error(LOG, ex, "could not validate POPO of CSR");
        return false;
    }
}

From source file:org.xipki.pki.scep.serveremulator.CaEmulator.java

License:Open Source License

private boolean verifyPopo(final CertificationRequest csr) {
    ParamUtil.requireNonNull("csr", csr);
    try {/* w  w w  .  j  a  va  2 s .com*/
        PKCS10CertificationRequest p10Req = new PKCS10CertificationRequest(csr);
        SubjectPublicKeyInfo pkInfo = p10Req.getSubjectPublicKeyInfo();
        PublicKey pk = KeyUtil.generatePublicKey(pkInfo);

        ContentVerifierProvider cvp = getContentVerifierProvider(pk);
        return p10Req.isSignatureValid(cvp);
    } catch (InvalidKeyException | PKCSException | NoSuchAlgorithmException | InvalidKeySpecException ex) {
        LogUtil.error(LOG, ex, "could not validate POPO of CSR");
        return false;
    }
}

From source file:org.xipki.security.SignerUtil.java

License:Open Source License

public static boolean verifyPOP(final PKCS10CertificationRequest p10Request) {
    try {//from  w w w  .  ja v  a  2s  . c o m
        SubjectPublicKeyInfo pkInfo = p10Request.getSubjectPublicKeyInfo();
        PublicKey pk = KeyUtil.generatePublicKey(pkInfo);

        ContentVerifierProvider cvp = KeyUtil.getContentVerifierProvider(pk);
        return p10Request.isSignatureValid(cvp);
    } catch (OperatorCreationException | InvalidKeyException | PKCSException | NoSuchAlgorithmException
            | InvalidKeySpecException e) {
        return false;
    }
}