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:beta01.CertSigningRequest.java

private void genaretKeyPairDsa() throws Exception {
    String signatureAlg = "SHA1withDSA";
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA", "BC");
    kpg.initialize(2048);//from   www .j a  v a 2  s  . co m
    KeyPair kp = kpg.genKeyPair();

    X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    x500NameBuilder.addRDN(BCStyle.C, "ID");
    x500NameBuilder.addRDN(BCStyle.CN, "Pizaini");
    //x500NameBuilder.addRDN(BCStyle.O, "Institut Pertanian Bogor");

    X500Name subject = x500NameBuilder.build();

    PKCS10CertificationRequestBuilder requestBuilder = new JcaPKCS10CertificationRequestBuilder(subject,
            kp.getPublic());
    try {
        PKCS10CertificationRequest request = requestBuilder
                .build(new JcaContentSignerBuilder(signatureAlg).setProvider("BC").build(kp.getPrivate()));

        //verify signature
        if (request.isSignatureValid(
                new JcaContentVerifierProviderBuilder().setProvider("BC").build(kp.getPublic()))) {
            System.out.println(signatureAlg + ": PKCS#10 request verified.");
            //CSR Output
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //PemWriter pemWrtb = new PemWriter(new OutputStreamWriter(baos));
            JcaPEMWriter jcaPem = new JcaPEMWriter(new OutputStreamWriter(baos));
            jcaPem.writeObject(request);
            jcaPem.close();
            try {
                File file = new File("D:\\CSR_" + kpg.getAlgorithm() + ".p10");
                FileOutputStream fos = new FileOutputStream(file);
                baos.close();
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException ex) {

            }

            //store Private Key p8   
            try {
                File file = new File("D:\\PrivateKey_" + kpg.getAlgorithm() + ".p8");
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(kp.getPrivate().getEncoded());
                fos.flush();
                fos.close();
                System.out.println("Privated key stored as " + kp.getPrivate().getFormat());
            } catch (IOException ex) {
            }

            //p12
            /*KeyStore pkcs12 = KeyStore.getInstance("PKCS12", "BC");
            pkcs12.load(null, null);
            //pkcs12.setCertificateEntry("r2oot", holderRoot);
            pkcs12.setKeyEntry("PIZAINI_ECDSA", kp.getPrivate(), null, null);
            char[] password = "pass".toCharArray();
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            pkcs12.store(bOut, password);
                    
            ASN1InputStream asnInput = new ASN1InputStream(bOut.toByteArray());
            bOut.reset();
            DEROutputStream derOut = new DEROutputStream(bOut);
            derOut.writeObject(asnInput.readObject());
            byte[] derFormat = bOut.toByteArray();
            try{
            File file = new File("D:\\Pizaini_ECDSA_Private.p12");
            FileOutputStream fos = new FileOutputStream(file);
            bOut.close();
            fos.write(derFormat);
            fos.flush();
            fos.close();
            }catch(IOException ex){
                    
            }*/

        } else {
            System.out.println(signatureAlg + ": Failed verify check.");
        }
    } catch (OperatorCreationException | PKCSException ex) {

    }

}

From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java

License:Open Source License

/**
 * Verify a PKCS #10 certificate signing request (CSR).
 *
 * @param csr The certificate signing request
 * @return True if successfully verified
 * @throws CryptoException//from   w w  w .j  av a  2s.  c o  m
 *             If there was a problem verifying the CSR
 */
public static boolean verifyCsr(PKCS10CertificationRequest csr) throws CryptoException {
    try {
        PublicKey pubKey = new JcaPKCS10CertificationRequest(csr).getPublicKey();

        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider("BC").build(pubKey);
        return csr.isSignatureValid(contentVerifierProvider);
    } catch (InvalidKeyException e) {
        throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
    } catch (OperatorCreationException e) {
        throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
    } catch (PKCSException e) {
        throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
    }
}

From source file:net.sf.portecle.crypto.X509CertUtil.java

License:Open Source License

/**
 * Load a CSR from the specified URL.//from w  ww .  j  a  v a 2s.  co m
 * 
 * @param url The URL to load CSR from
 * @return The CSR
 * @throws CryptoException Problem encountered while loading the CSR
 * @throws FileNotFoundException If the CSR file does not exist, is a directory rather than a regular
 *             file, or for some other reason cannot be opened for reading
 * @throws IOException An I/O error occurred
 */
public static PKCS10CertificationRequest loadCSR(URL url) throws CryptoException, IOException {
    // TODO: handle DER encoded requests too?
    try (PEMParser pr = new PEMParser(new InputStreamReader(NetUtil.openGetStream(url)))) {
        PKCS10CertificationRequest csr = (PKCS10CertificationRequest) pr.readObject();
        ContentVerifierProvider prov = new JcaContentVerifierProviderBuilder()
                .build(csr.getSubjectPublicKeyInfo());

        if (!csr.isSignatureValid(prov)) {
            throw new CryptoException(RB.getString("NoVerifyCsr.exception.message"));
        }

        return csr;
    } catch (ClassCastException | OperatorCreationException | PKCSException ex) {
        throw new CryptoException(RB.getString("NoLoadCsr.exception.message"), ex);
    }
}

From source file:net.sf.portecle.crypto.X509CertUtil.java

License:Open Source License

/**
 * Create a PKCS #10 certification request (CSR) using the supplied certificate and private key.
 * /*from w w  w.  j a v a  2s .  c  om*/
 * @param cert The certificate
 * @param privateKey The private key
 * @throws CryptoException If there was a problem generating the CSR
 * @return The CSR
 */
public static PKCS10CertificationRequest generatePKCS10CSR(X509Certificate cert, PrivateKey privateKey)
        throws CryptoException {
    X500Name subject = new X500Name(cert.getSubjectDN().toString());

    JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(subject,
            cert.getPublicKey());
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(cert.getSigAlgName());

    try {
        ContentVerifierProvider prov = new JcaContentVerifierProviderBuilder().build(cert);
        PKCS10CertificationRequest csr = csrBuilder.build(signerBuilder.build(privateKey));

        if (!csr.isSignatureValid(prov)) {
            throw new CryptoException(RB.getString("NoVerifyGenCsr.exception.message"));
        }

        return csr;
    } catch (OperatorCreationException | PKCSException ex) {
        throw new CryptoException(RB.getString("NoGenerateCsr.exception.message"), ex);
    }
}

From source file:org.cesecore.certificates.certificate.CertificateCreateSessionTest.java

License:Open Source License

@Test
public void testPKCS10Request() throws Exception {
    String fp1 = null;// w  ww . j a v a2s .  co  m
    try {
        final String dn = "C=SE,O=PrimeKey,CN=pkcs10requesttest";
        final EndEntityInformation user = new EndEntityInformation("pkcs10requesttest", dn,
                testx509ca.getCAId(), null, "foo@anatom.se", new EndEntityType(EndEntityTypes.ENDUSER), 0,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityConstants.TOKEN_USERGEN, 0,
                null);
        user.setStatus(EndEntityConstants.STATUS_NEW);

        final KeyPair keyPair = KeyTools.genKeys("512", "RSA");
        final X500Name x509dn = new X500Name(dn);
        PKCS10CertificationRequest basicpkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                x509dn, keyPair.getPublic(), null, keyPair.getPrivate(), null);
        ContentVerifierProvider cvp = CertTools.genContentVerifierProvider(keyPair.getPublic());
        assertTrue("Request must verify (POP)", basicpkcs10.isSignatureValid(cvp));
        PKCS10RequestMessage req = new PKCS10RequestMessage(basicpkcs10.toASN1Structure().getEncoded());
        assertTrue("Request must verify (POP)", req.verify());
        X509ResponseMessage resp = (X509ResponseMessage) certificateCreateSession.createCertificate(
                roleMgmgToken, user, req, X509ResponseMessage.class, signSession.fetchCertGenParams());
        assertNotNull("Creating a cert should have worked", resp);
        X509Certificate cert = (X509Certificate) resp.getCertificate();
        fp1 = CertTools.getFingerprintAsString(cert);

        // Create a request with invalid PoP
        final KeyPair keyPair2 = KeyTools.genKeys("512", "RSA");
        PKCS10CertificationRequest invalidpoppkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                x509dn, keyPair.getPublic(), null, keyPair2.getPrivate(), null);
        req = new PKCS10RequestMessage(invalidpoppkcs10.toASN1Structure().getEncoded());
        try {
            resp = (X509ResponseMessage) certificateCreateSession.createCertificate(roleMgmgToken, user, req,
                    X509ResponseMessage.class, signSession.fetchCertGenParams());
            fail("Creating a cert from a request with invalid PoP (proof of possession) should not work");
        } catch (SignRequestSignatureException e) {
            // NOPMD: this is what we want
        }

        // Try with a PKCS#10 request with a asn.1 corrupt public key entry
        req = new PKCS10RequestMessage(invalidp10);
        try {
            resp = (X509ResponseMessage) certificateCreateSession.createCertificate(roleMgmgToken, user, req,
                    X509ResponseMessage.class, signSession.fetchCertGenParams());
            fail("Creating a cert from a request with invalid PoP (proof of possession) should not work");
        } catch (IllegalKeyException e) { // NOPMD: this is what we want
        } catch (SignRequestSignatureException e) {
        } // NOPMD: or this depending on BC version etc

    } finally {
        internalCertStoreSession.removeCertificate(fp1);
    }
}

From source file:org.cesecore.keys.util.KeyStoreTools.java

License:Open Source License

/** Generates a certificate request (CSR) in PKCS#10 format and writes to file
 * @param alias for the key to be used//from ww w  .j  a  v a  2s. co m
 * @param dn the DN to be used. If null the 'CN=alias' will be used
 * @param explicitEccParameters false should be default and will use NamedCurve encoding of ECC public keys (IETF recommendation), use true to include all parameters explicitly (ICAO ePassport requirement).
 * @throws Exception
 */
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()));
    }
    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.ejbca.core.ejb.ca.sign.SignSessionWithDsaTest.java

License:Open Source License

/**
 * tests bouncy PKCS10//from w w w  .j  av a 2s.  c  om
 * 
 * @throws Exception
 *             if en error occurs...
 */
@Test
public void testBCPKCS10DSAWithDSACA() throws Exception {
    log.trace(">test26TestBCPKCS10DSAWithDSACA()");
    endEntityManagementSession.setUserStatus(internalAdmin, DSA_USERNAME, EndEntityConstants.STATUS_NEW);
    log.debug("Reset status of 'foodsa' to NEW");
    KeyPair dsakeys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_DSA);
    // Create certificate request
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithDSA",
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=foodsa"), dsakeys.getPublic(), new DERSet(),
            dsakeys.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(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(DSA_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 {
        assertTrue("Public key is not DSA", false);
    }
    X509Certificate dsacacert = (X509Certificate) caSession.getCAInfo(internalAdmin, TEST_DSA_CA_NAME)
            .getCertificateChain().toArray()[0];
    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.SignSessionWithECGOST3410Test.java

License:Open Source License

/**
 * tests bouncy PKCS10//  w w w .j a v  a 2  s. c  o m
 */
@Test
public void testBCPKCS10ECGOST3410WithECGOST3410CA() throws Exception {
    assumeTrue(AlgorithmTools.isGost3410Enabled());
    log.trace(">test15TestBCPKCS10ECGOST3410WithECGOST3410CA()");
    userAdminSession.setUserStatus(internalAdmin, ECGOST3410_USERNAME, EndEntityConstants.STATUS_NEW);
    log.debug("Reset status of '" + ECGOST3410_USERNAME + "' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("GOST3411withECGOST3410",
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=" + ECGOST3410_USERNAME), gostkeys.getPublic(),
            new DERSet(), gostkeys.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(gostkeys.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(ECGOST3410_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();
    checkECKey(pk);
    try {
        X509Certificate ecdsacacert = (X509Certificate) caSession
                .getCAInfo(internalAdmin, TEST_ECGOST3410_CA_NAME).getCertificateChain().toArray()[0];
        cert.verify(ecdsacacert.getPublicKey());
    } catch (Exception e) {
        assertTrue("Verify failed: " + e.getMessage(), false);
    }

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

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

License:Open Source License

/**
 * tests bouncy PKCS10/* www .  j av  a2 s  .  c  om*/
 * 
 */
@Test
public void testBCPKCS10ECDSAWithRSACA() throws Exception {
    log.trace(">test13TestBCPKCS10ECDSAWithRSACA()");

    endEntityManagementSession.setUserStatus(internalAdmin, RSA_USERNAME, 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=foo"), 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(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();
    checkECKey(pk);
    try {
        X509Certificate rsacacert = (X509Certificate) caSession.getCAInfo(internalAdmin, getTestCAName())
                .getCertificateChain().toArray()[0];
        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.SignSessionWithEllipticCurveDsaTest.java

License:Open Source License

/**
 * tests bouncy PKCS10//from ww w. j av  a2s  . co m
 */
@Test
public void testBCPKCS10ECDSAWithECDSACA() throws Exception {
    log.trace(">test15TestBCPKCS10ECDSAWithECDSACA()");

    endEntityManagementSession.setUserStatus(internalAdmin, ECDSA_USERNAME, 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=" + ECDSA_USERNAME), 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(ECDSA_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();
    checkECKey(pk);
    try {
        X509Certificate ecdsacacert = (X509Certificate) caSession.getCAInfo(internalAdmin, TEST_ECDSA_CA_NAME)
                .getCertificateChain().toArray()[0];
        cert.verify(ecdsacacert.getPublicKey());
    } catch (Exception e) {
        assertTrue("Verify failed: " + e.getMessage(), false);
    }
    log.trace("<test15TestBCPKCS10ECDSAWithECDSACA()");
}