Example usage for org.bouncycastle.jce PKCS10CertificationRequest PKCS10CertificationRequest

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

Introduction

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

Prototype

public PKCS10CertificationRequest(ASN1Sequence sequence) 

Source Link

Usage

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

License:Open Source License

/**
 * {@inheritDoc}//from  w  ww .j a  va  2  s  .c  o m
 */
@Override
public CSRInfo parseCSR(byte[] csr) throws CryptoException {
    return extractCSRInfo(new PKCS10CertificationRequest(csr));
}

From source file:ca.nrc.cadc.cred.client.CredClient.java

License:Open Source License

/**
 * Parses a byte array and constructs the corresponding
 * PKCS10CertificationRequest//from w  w w . j  a  v a 2 s.  c  o  m
 * 
 * @param code
 *            bytes containing the CSR
 * @return PKCS10CertificationRequest
 * @throws IOException
 */
public static PKCS10CertificationRequest readCSR(byte[] code) throws IOException {
    byte[] crt = getCSR(code);
    return new PKCS10CertificationRequest(crt);
}

From source file:com.ah.be.cloudauth.HmCloudAuthCertMgmtImpl.java

@SuppressWarnings("rawtypes")
private void verifyCSRContent(BeRadSecCertCreationResultEvent result, String commonName)
        throws HmCloudAuthException {
    String methodName = "verifyCSRContent";
    if (result.isCreateError()) {
        throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_CREATE_ERR);
    }/*from   ww w.j ava  2s.  c  o m*/
    if (result.isNeedCreate()) {
        byte[] csrContent = result.getCsrContent();
        final List pemItems = org.apache.commons.ssl.PEMUtil.decode(csrContent);
        if (pemItems.isEmpty()) {
            throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR);
        }

        final PEMItem csrPemItem = (PEMItem) pemItems.get(0);
        if (csrPemItem.pemType.startsWith(CERTIFICATE_REQUEST)) {
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(csrPemItem.getDerBytes());
            CertificationRequestInfo requestInfo = csr.getCertificationRequestInfo();
            X509Name subject = requestInfo.getSubject();

            Vector commondNameVector = subject.getValues(X509Name.CN);
            Vector countryVector = subject.getValues(X509Name.C);
            Vector organizationVector = subject.getValues(X509Name.O);
            if (commondNameVector.isEmpty() || countryVector.isEmpty() || organizationVector.isEmpty()) {
                throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_FORMAT_ERR);
            }
            if (!commonName.equalsIgnoreCase(commondNameVector.get(0).toString())
                    || !ORGANIZATION.equals(organizationVector.get(0).toString())
                    || !COUNTRY.equals(countryVector.get(0).toString())) {
                throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_VERIFY_ERR);
            }
        } else {
            throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR);
        }
    } else {
        throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_STATUS_ERR);
    }
    return;
}

From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationServerCore.java

License:Open Source License

public EntityAuthentication authenticateServer(EntityID serverID, byte[] encodedCertReq)
        throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException, UnrecoverableKeyException,
        KeyStoreException, IOException, CertificateParsingException, ServerNotRegisteredException,
        AuthenticationFailureException {
    Date startDate = new Date(System.currentTimeMillis() - (60L * 60L * 1000L)); // time from which certificate is valid
    Date expiryDate = new Date(startDate.getTime() + (30L * 24L * 60L * 60L * 1000L)); // time after which certificate is not valid
    BigInteger serialNumber = serverID.toBigInteger(); // serial number for certificate

    EntityAuthentication returnAuthentication = null;

    Certificate registeredCertificate = keyStore.getCertificate(serverID.toString());
    if (registeredCertificate != null) {
        PublicKey checkKey = registeredCertificate.getPublicKey();
        PKCS10CertificationRequest certReq = new PKCS10CertificationRequest(encodedCertReq);
        if (checkKey != null) {
            byte[] encodedCheckKey = checkKey.getEncoded();
            byte[] encodedCertKey = certReq.getPublicKey().getEncoded();
            if (Arrays.equals(encodedCheckKey, encodedCertKey)) {
                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
                X500Principal dnName = new X500Principal(
                        EntityAuthenticationClient.kEntityIDCNPrefix + serverID.toString());

                certGen.setSerialNumber(serialNumber);
                certGen.setIssuerDN(rootCertificate.getSubjectX500Principal());
                certGen.setNotBefore(startDate);
                certGen.setNotAfter(expiryDate);
                certGen.setSubjectDN(dnName); // note: same as issuer
                certGen.setPublicKey(certReq.getPublicKey());
                certGen.setSignatureAlgorithm(kCertificateSignatureAlg);

                certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                        new AuthorityKeyIdentifierStructure(rootCertificate));
                certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                        new SubjectKeyIdentifierStructure(certReq.getPublicKey()));

                X509Certificate cert = certGen.generate(signingKey, "BC");
                returnAuthentication = new EntityAuthentication(cert);
            } else {
                logger.error(new ErrorLogMessage(
                        "Server {0} requesting authentication, but registered key does not match", serverID));
                throw new AuthenticationFailureException();
            }/*w w  w. j  a  v  a  2 s .c o  m*/
        } else {
            logger.error(new ErrorLogMessage(
                    "Server {0} requesting authentication, no check key found in registered certificate",
                    serverID));
            throw new AuthenticationFailureException();
        }
    } else {
        logger.error(new ErrorLogMessage("Server {0} requesting authentication, but not registered", serverID));
        throw new ServerNotRegisteredException();
    }
    return returnAuthentication;
}

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

License:Open Source License

@Override
public synchronized X509Certificate signCertificate(byte[] csrBytes) throws CAException {
    ensureInitialized();//ww  w  . j  a v  a 2s  . c  om
    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:me.it_result.ca.bouncycastle.BouncyCAClientTest.java

License:Open Source License

@Test
public void testGenerateCSR() throws CertificateException, Exception {
    // Given CSR was never generated for 'CN=test,UID=test@test' subject name
    assertNull(client.getKeypair(SUBJECT_NAME));
    // When generateCSR('CN=test,UID=test@test') is invoked 
    Date minBeforeDate = new Date();
    byte[] csr = client.generateCSR(CERT_PARAMS);
    Date maxBeforeDate = new Date();
    // Then CSR is generated for the subject name
    PKCS10CertificationRequest parsedCsr = new PKCS10CertificationRequest(csr);
    assertEquals(new X509Principal(SUBJECT_NAME), parsedCsr.getCertificationRequestInfo().getSubject());
    // And a newly generated keypair is generated
    assertNotNull(client.getKeypair(SUBJECT_NAME));
    // And a self-signed certificate is generated
    X509Certificate selfSignedCert = client.getCertificate(SUBJECT_NAME);
    assertNotNull(selfSignedCert);//from   w w w  . jav a  2 s  .c o  m
    new X509Assertions(selfSignedCert).caCertificate(false).issuedBy(selfSignedCert)
            .serialNumber(new BigInteger("1")).signatureAlgrithm(jdkSignatureAlgorithm)
            .subjectName(SUBJECT_NAME).type("X.509").version(3)
            .validDuring(VALIDITY_DAYS, minBeforeDate, maxBeforeDate)
            .keyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment).containsAKI().containsSKI()
            .noMoreExtensions();
}

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

License:Open Source License

private PKCS10CertificationRequest readCsr(String base64EncodedCsr) {
    byte[] csr = Base64.decode(base64EncodedCsr);
    return new PKCS10CertificationRequest(csr);
}

From source file:me.it_result.ca.CAClientTest.java

License:Open Source License

private void assertDuplicateCsrInvocation(byte[] csr, KeyPair keypair, X509Certificate certificate)
        throws Exception {
    // When generateCSR('CN=test,UID=test@test') is invoked
    byte[] newCsr = client().generateCSR(CERT_PARAMS);
    // Then a new CSR is generated for the subject name using the keypair generated earlier
    PKCS10CertificationRequest parsedCsr = new PKCS10CertificationRequest(csr);
    PKCS10CertificationRequest newParsedCsr = new PKCS10CertificationRequest(newCsr);
    assertEquals(parsedCsr.getCertificationRequestInfo().getSubject(),
            newParsedCsr.getCertificationRequestInfo().getSubject());
    assertEquals(keypair.getPublic(), parsedCsr.getPublicKey());
    // And keypair is not modified
    KeyPair newKeypair = client().getKeypair(SUBJECT_NAME);
    assertEquals(keypair.getPrivate(), newKeypair.getPrivate());
    assertEquals(keypair.getPublic(), newKeypair.getPublic());
    // And a self-signed certificate is not modified
    X509Certificate newCertificate = client().getCertificate(SUBJECT_NAME);
    assertEquals(certificate, newCertificate);
}

From source file:me.it_result.ca.scep.ScepCAClient.java

License:Open Source License

/**
 * Enrolls a certificate via SCEP/*from   w w  w  .  ja  v  a 2s. co  m*/
 * 
 * @param certificateParameters certificate subject DN 
 * 
 * @return certificate enrolled
 *  
 * @throws DuplicateSubjectException In case certificate was enrolled 
 * already
 * @throws ScepFailureException In case enrollment resulted in SCEP failure
 * status returned
 * @throws CAException
 */
public X509Certificate enrollCertificate(CertificateParameters certificateParameters) throws CAException {
    try {
        String subject = certificateParameters.getSubjectDN();
        ensureCertificateNotSignedYet(subject);
        byte[] csr = caClient.generateCSR(certificateParameters);
        X509Certificate identity = caClient.getCertificate(subject);
        KeyPair keyPair = caClient.getKeypair(subject);
        Client scep = initializeScepClient(identity, keyPair);
        // TODO: take into account scepPassword value
        EnrolmentTransaction transaction = scep.enrol(new PKCS10CertificationRequest(csr));
        State state = executeScepTransaction(transaction);
        if (state == State.CERT_ISSUED) {
            X509Certificate certificate = extractCertificate(transaction.getCertStore(), keyPair.getPublic());
            return certificate;
        } else if (state == State.CERT_NON_EXISTANT) {
            FailInfo fail = transaction.getFailInfo();
            throw new ScepFailureException(fail.toString());
        } else if (state == State.CERT_REQ_PENDING) {
            return null;
        } else {
            throw new CAException("Unexpected transaction state: " + state);
        }
    } catch (DuplicateSubjectException e) {
        throw new DuplicateSubjectException(e);
    } catch (ScepFailureException e) {
        throw new ScepFailureException(e);
    } catch (Exception e) {
        throw new CAException(e);
    }
}

From source file:me.it_result.ca.scep.ScepServer.java

License:Open Source License

public Collection<CertificationRequest> getManuallyAuthorizedCsrs() throws CAException {
    try {/*from   w  ww.  j a v  a  2 s.  c om*/
        Database db = getContext().getDatabase();
        Set<String> aliases = db.listAliases(ScepServlet.MANUAL_AUTHORIZATION_CSR_PROPERTY);
        List<CertificationRequest> csrs = new ArrayList<CertificationRequest>();
        for (String alias : aliases) {
            byte[] csrBytes = db.readBytes(alias, ScepServlet.MANUAL_AUTHORIZATION_CSR_PROPERTY);
            CertificationRequest csr = new PKCS10CertificationRequest(csrBytes);
            csrs.add(csr);
        }
        return csrs;
    } catch (Exception e) {
        throw new CAException(e);
    }
}