Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream.

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:org.eclipse.andmore.android.certmanager.packaging.sign.SignatureBlockFile.java

License:Apache License

/**
 * Writes this file to an output stream//from   w  ww .j  a va  2s.  com
 * 
 * @param outputStream
 *            the output stream to write the file
 * @throws IOException
 *             if an I/O error occurs during the signing process
 * @throws SignException
 *             if a processing error occurs during the signing process
 * @throws KeyStoreManagerException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException 
 * @throws CertificateEncodingException 
 * @throws OperatorCreationException 
 * @throws CMSException 
 */
public void write(OutputStream outputStream) throws IOException, SignException, UnrecoverableKeyException,
        KeyStoreException, KeyStoreManagerException, NoSuchAlgorithmException, InvalidKeyException,
        CertificateEncodingException, OperatorCreationException, CMSException {
    // get certificate from entry
    X509Certificate[] certChain = { keystoreEntry.getX509Certificate() };
    if (certChain.length > 0) {
        X509Certificate publicKey = certChain[0];
        PrivateKey privateKey = keystoreEntry.getPrivateKey(keyEntryPassword);
        String blockalgorithm = getBlockAlgorithm();
        if (!blockalgorithm.equalsIgnoreCase(ISignConstants.DSA)
                && !blockalgorithm.equalsIgnoreCase(ISignConstants.RSA)) {
            AndmoreLogger.error(SignatureBlockFile.class,
                    "Signing block algorithm not supported. Key algorithm must be DSA or RSA");
            throw new SignException("Signing block algorithm not supported");
        }

        String signatureAlgorithm = ISignConstants.SHA1 + ISignConstants.ALGORITHM_CONNECTOR + blockalgorithm;

        Security.addProvider(new BouncyCastleProvider());

        ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        certList.add(publicKey);
        JcaCertStore certs = new JcaCertStore(certList);

        ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        generator.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                        .setDirectSignature(true).build(signer, publicKey));
        generator.addCertificates(certs);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        signatureFile.write(baos);

        CMSTypedData cmsdata = new CMSProcessableByteArray(baos.toByteArray());
        CMSSignedData signeddata = generator.generate(cmsdata, false);

        ASN1InputStream asn1 = new ASN1InputStream(signeddata.getEncoded());
        DEROutputStream dos = new DEROutputStream(outputStream);
        dos.writeObject(asn1.readObject());
        dos.flush();
        dos.close();
        asn1.close();
    }
    AndmoreLogger.info(SignatureBlockFile.class, "Created signature block file");
}

From source file:org.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java

License:Open Source License

private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey,
        PublicKey pubKey, String sigAlg, boolean isCA)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, OperatorCreationException, CertificateException, IOException {
    int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
    // Create self signed certificate
    Date firstDate = new Date();
    // Set starting date to tomorrow
    firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000));
    Date lastDate = new Date();
    // Set Expiry in two days
    lastDate.setTime(lastDate.getTime() + ((2 * 24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from www  .j a  va  2s  .  c  o  m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            publicKey = pubKey;
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
        } catch (InvalidKeySpecException e) {
            publicKey = pubKey;
        } catch (NullPointerException e) {
            publicKey = pubKey;
        }
    } else {
        publicKey = pubKey;
    }
    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
            (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn),
            new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn),
            pkinfo);
    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }
    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            ASN1InputStream spkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream apkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) spkiAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) apkiAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                spkiAsn1InputStream.close();
                apkiAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }
    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

From source file:org.ejbca.core.ejb.ca.crl.CreateCRLSessionTest.java

License:Open Source License

/**
 * Tests the extension CRL Distribution Point on CRLs
 * /*  w  ww  .j a v  a2  s . c  o m*/
 * @throws Exception
 *             error
 */
public void test06CRLDistPointOnCRL() throws Exception {
    log.trace(">test06CRLDistPointOnCRL()");

    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    X509CAInfo cainfo = (X509CAInfo) ca.getCAInfo();
    X509CRL x509crl;
    byte[] cdpDER;

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    caAdminSession.editCA(admin, cainfo);
    ca = caSession.getCA(admin, caid);
    crlCreateSession.run(admin, ca);
    x509crl = CertTools.getCRLfromByteArray(crlSession.getLastCRL(admin, cainfo.getSubjectDN(), false));
    cdpDER = x509crl.getExtensionValue(X509Extensions.IssuingDistributionPoint.getId());
    assertNotNull("CRL has no distribution points", cdpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cdpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    IssuingDistributionPoint cdp = new IssuingDistributionPoint((ASN1Sequence) aIn.readObject());
    DistributionPointName distpoint = cdp.getDistributionPoint();

    assertEquals("CRL distribution point is different", cdpURL,
            ((DERIA5String) ((GeneralNames) distpoint.getName()).getNames()[0].getName()).getString());

    cainfo.setUseCrlDistributionPointOnCrl(false);
    cainfo.setDefaultCRLDistPoint("");
    caAdminSession.editCA(admin, cainfo);
    ca = caSession.getCA(admin, caid);
    crlCreateSession.run(admin, ca);
    x509crl = CertTools.getCRLfromByteArray(crlSession.getLastCRL(admin, cainfo.getSubjectDN(), false));
    assertNull("CRL has distribution points",
            x509crl.getExtensionValue(X509Extensions.CRLDistributionPoints.getId()));

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

From source file:org.ejbca.core.ejb.ca.crl.CreateCRLSessionTest.java

License:Open Source License

/**
 * Tests the extension Freshest CRL DP./*  w w w.j av a 2 s .c om*/
 * 
 * @throws Exception
 *             in case of error.
 */
public void test07CRLFreshestCRL() throws Exception {
    log.trace(">test07CRLFreshestCRL()");

    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    final String freshestCdpURL = "http://www.ejbca.org/foo/delta.crl";
    X509CAInfo cainfo = (X509CAInfo) caAdminSession.getCAInfo(admin, caid);
    X509CRL x509crl;
    byte[] cFreshestDpDER;

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    cainfo.setCADefinedFreshestCRL(freshestCdpURL);
    caAdminSession.editCA(admin, cainfo);
    ca = caSession.getCA(admin, caid);
    crlCreateSession.run(admin, ca);
    x509crl = CertTools.getCRLfromByteArray(crlSession.getLastCRL(admin, cainfo.getSubjectDN(), false));
    cFreshestDpDER = x509crl.getExtensionValue(X509Extensions.FreshestCRL.getId());
    assertNotNull("CRL has no Freshest Distribution Point", cFreshestDpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cFreshestDpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    CRLDistPoint cdp = new CRLDistPoint((ASN1Sequence) aIn.readObject());
    DistributionPoint[] distpoints = cdp.getDistributionPoints();

    assertEquals("More CRL Freshest distributions points than expected", 1, distpoints.length);
    assertEquals("Freshest CRL distribution point is different", freshestCdpURL,
            ((DERIA5String) ((GeneralNames) distpoints[0].getDistributionPoint().getName()).getNames()[0]
                    .getName()).getString());

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

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

License:Open Source License

@Override
public IResponseMessage createCertificate(Admin admin, IRequestMessage req, Class responseClass,
        UserDataVO suppliedUserData) throws EjbcaException {
    if (log.isTraceEnabled()) {
        log.trace(">createCertificate(IRequestMessage)");
    }//from  w  ww  .j  av  a  2s  .  c  om
    // Get CA that will receive request
    UserDataVO data = null;
    IResponseMessage ret = null;
    CA ca;
    if (suppliedUserData == null) {
        ca = getCAFromRequest(admin, req);
    } else {
        ca = caSession.getCA(admin, suppliedUserData.getCAId()); // Take the CAId from the supplied userdata, if any
    }
    try {
        CATokenContainer catoken = ca.getCAToken();

        // See if we need some key material to decrypt request
        if (req.requireKeyInfo()) {
            // You go figure...scep encrypts message with the public CA-cert
            req.setKeyInfo(ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN),
                    catoken.getJCEProvider());
        }
        // Verify the request
        if (req.verify() == false) {
            String msg = intres.getLocalizedMessage("signsession.popverificationfailed");
            logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(),
                    null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
            throw new SignRequestSignatureException(msg);
        }

        if (ca.isUseUserStorage() && req.getUsername() == null) {
            String msg = intres.getLocalizedMessage("signsession.nouserinrequest", req.getRequestDN());
            logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(),
                    null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
            throw new SignRequestException(msg);
            //ret.setFailInfo(FailInfo.BAD_REQUEST);
            //ret.setStatus(ResponseStatus.FAILURE);
        } else if (ca.isUseUserStorage() && req.getPassword() == null) {
            String msg = intres.getLocalizedMessage("signsession.nopasswordinrequest");
            logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(),
                    null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
            throw new SignRequestException(msg);
        } else {
            ResponseStatus status = ResponseStatus.SUCCESS;
            FailInfo failInfo = null;
            String failText = null;
            Certificate cert = null;
            try {
                // If we haven't done so yet, authenticate user. (Only if we store UserData for this CA.)
                if (ca.isUseUserStorage()) {
                    data = authUser(admin, req.getUsername(), req.getPassword());
                } else {
                    data = suppliedUserData;
                }
                PublicKey reqpk = req.getRequestPublicKey();
                if (reqpk == null) {
                    logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(),
                            req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE,
                            intres.getLocalizedMessage("signsession.nokeyinrequest"));
                    throw new InvalidKeyException("Key is null!");
                }
                // We need to make sure we use the users registered CA here
                if (data.getCAId() != ca.getCAId()) {
                    failText = intres.getLocalizedMessage("signsession.wrongauthority",
                            Integer.valueOf(ca.getCAId()), Integer.valueOf(data.getCAId()));
                    status = ResponseStatus.FAILURE;
                    failInfo = FailInfo.WRONG_AUTHORITY;
                    logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(),
                            req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText);
                }

                if (status.equals(ResponseStatus.SUCCESS)) {
                    Date notBefore = req.getRequestValidityNotBefore(); // Optionally requested validity
                    Date notAfter = req.getRequestValidityNotAfter(); // Optionally requested validity
                    X509Extensions exts = req.getRequestExtensions(); // Optionally requested extensions
                    int keyusage = -1;
                    if (exts != null) {
                        if (log.isDebugEnabled()) {
                            log.debug(
                                    "we have extensions, see if we can override KeyUsage by looking for a KeyUsage extension in request");
                        }
                        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
                        if (ext != null) {
                            ASN1OctetString os = ext.getValue();
                            ByteArrayInputStream bIs = new ByteArrayInputStream(os.getOctets());
                            ASN1InputStream dIs = new ASN1InputStream(bIs);
                            DERObject dob = dIs.readObject();
                            DERBitString bs = DERBitString.getInstance(dob);
                            keyusage = bs.intValue();
                            if (log.isDebugEnabled()) {
                                log.debug("We have a key usage request extension: " + keyusage);
                            }
                        }
                    }
                    String sequence = null;
                    byte[] ki = req.getRequestKeyInfo();
                    if ((ki != null) && (ki.length > 0)) {
                        sequence = new String(ki);
                    }
                    cert = createCertificate(admin, data, req.getRequestX509Name(), ca, reqpk, keyusage,
                            notBefore, notAfter, exts, sequence);
                }
            } catch (ObjectNotFoundException oe) {
                // If we didn't find the entity return error message
                log.error("User not found: ", oe);
                failText = intres.getLocalizedMessage("signsession.nosuchuser", req.getUsername());
                status = ResponseStatus.FAILURE;
                failInfo = FailInfo.INCORRECT_DATA;
                logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(),
                        req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText);
            }

            //Create the response message with all nonces and checks etc
            ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(),
                    catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());

            if ((cert == null) && (status == ResponseStatus.SUCCESS)) {
                status = ResponseStatus.FAILURE;
                failInfo = FailInfo.BAD_REQUEST;
            } else {
                ret.setCertificate(cert);
            }
            ret.setStatus(status);
            if (failInfo != null) {
                ret.setFailInfo(failInfo);
                ret.setFailText(failText);
            }
        }
        ret.create();
        // Call authentication session and tell that we are finished with this user. (Only if we store UserData for this CA.)
        if (ca.isUseUserStorage() && data != null) {
            finishUser(ca, data);
        }
    } catch (NoUniqueCertSerialNumberIndexException e) {
        cleanUserCertDataSN(data);
        throw e.ejbcaException;
    } catch (IllegalKeyException ke) {
        log.error("Key is of unknown type: ", ke);
        throw ke;
    } catch (CATokenOfflineException ctoe) {
        String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getSubjectDN());
        CATokenOfflineException ex = new CATokenOfflineException(msg);
        ex.initCause(ctoe);
        throw ex;
        //} catch (EjbcaException e) {
        //    throw e;
    } catch (NoSuchProviderException e) {
        log.error("NoSuchProvider provider: ", e);
    } catch (InvalidKeyException e) {
        log.error("Invalid key in request: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("No such algorithm: ", e);
    } catch (IOException e) {
        log.error("Cannot create response message: ", e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<createCertificate(IRequestMessage)");
    }
    return ret;
}

From source file:org.ejbca.core.ejb.crl.PublishingCrlSessionTest.java

License:Open Source License

/**
 * Tests the extension CRL Distribution Point on CRLs
 *//*from   ww  w  . j a va2 s  .c  om*/
@Test
public void testCRLDistPointOnCRL() throws Exception {
    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    X509CAInfo cainfo = (X509CAInfo) testx509ca.getCAInfo();
    X509CRL x509crl;
    byte[] cdpDER;

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    caSession.editCA(roleMgmgToken, cainfo);
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl = CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    cdpDER = x509crl.getExtensionValue(Extension.issuingDistributionPoint.getId());
    assertNotNull("CRL has no distribution points", cdpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cdpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    IssuingDistributionPoint cdp = IssuingDistributionPoint.getInstance((ASN1Sequence) aIn.readObject());
    DistributionPointName distpoint = cdp.getDistributionPoint();

    assertEquals("CRL distribution point is different", cdpURL,
            ((DERIA5String) ((GeneralNames) distpoint.getName()).getNames()[0].getName()).getString());

    cainfo.setUseCrlDistributionPointOnCrl(false);
    cainfo.setDefaultCRLDistPoint("");
    caSession.editCA(roleMgmgToken, cainfo);
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl = CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    assertNull("CRL has distribution points",
            x509crl.getExtensionValue(Extension.cRLDistributionPoints.getId()));
}

From source file:org.ejbca.core.ejb.crl.PublishingCrlSessionTest.java

License:Open Source License

/**
 * Tests the extension Freshest CRL DP.//from w  w w  .j a v a2  s . c  om
 */
@Test
public void testCRLFreshestCRL() throws Exception {
    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    final String freshestCdpURL = "http://www.ejbca.org/foo/delta.crl";
    X509CAInfo cainfo = (X509CAInfo) testx509ca.getCAInfo();
    X509CRL x509crl;
    byte[] cFreshestDpDER;

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    cainfo.setCADefinedFreshestCRL(freshestCdpURL);
    caSession.editCA(roleMgmgToken, cainfo);
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl = CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    cFreshestDpDER = x509crl.getExtensionValue(Extension.freshestCRL.getId());
    assertNotNull("CRL has no Freshest Distribution Point", cFreshestDpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cFreshestDpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    CRLDistPoint cdp = CRLDistPoint.getInstance((ASN1Sequence) aIn.readObject());
    DistributionPoint[] distpoints = cdp.getDistributionPoints();

    assertEquals("More CRL Freshest distributions points than expected", 1, distpoints.length);
    assertEquals("Freshest CRL distribution point is different", freshestCdpURL,
            ((DERIA5String) ((GeneralNames) distpoints[0].getDistributionPoint().getName()).getNames()[0]
                    .getName()).getString());
}

From source file:org.ejbca.core.ejb.ra.CertificateRequestSessionBean.java

License:Open Source License

@Override
public byte[] processCertReq(Admin admin, UserDataVO userdata, String req, int reqType, String hardTokenSN,
        int responseType) throws CADoesntExistsException, AuthorizationDeniedException, NotFoundException,
        InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException,
        SignatureException, IOException, ObjectNotFoundException, CertificateException,
        UserDoesntFullfillEndEntityProfile, ApprovalException, EjbcaException {
    byte[] retval = null;

    // Check tokentype
    if (userdata.getTokenType() != SecConst.TOKEN_SOFT_BROWSERGEN) {
        throw new WrongTokenTypeException(
                "Error: Wrong Token Type of user, must be 'USERGENERATED' for PKCS10/SPKAC/CRMF/CVC requests");
    }/*from w ww .  ja  va 2 s. c  o m*/
    // This is the secret sauce, do the end entity handling automagically here before we get the cert
    addOrEditUser(admin, userdata, false, true);
    // Process request
    try {
        String password = userdata.getPassword();
        String username = userdata.getUsername();
        IRequestMessage imsg = null;
        if (reqType == SecConst.CERT_REQ_TYPE_PKCS10) {
            IRequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes());
            PublicKey pubKey = pkcs10req.getRequestPublicKey();
            imsg = new SimpleRequestMessage(pubKey, username, password);
        } else if (reqType == SecConst.CERT_REQ_TYPE_SPKAC) {
            // parts copied from request helper.
            byte[] reqBytes = req.getBytes();
            if (reqBytes != null) {
                log.debug("Received NS request: " + new String(reqBytes));
                byte[] buffer = Base64.decode(reqBytes);
                if (buffer == null) {
                    return null;
                }
                ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer));
                ASN1Sequence spkacSeq = (ASN1Sequence) in.readObject();
                in.close();
                NetscapeCertRequest nscr = new NetscapeCertRequest(spkacSeq);
                // Verify POPO, we don't care about the challenge, it's not important.
                nscr.setChallenge("challenge");
                if (nscr.verify("challenge") == false) {
                    log.debug("POPO verification Failed");
                    throw new SignRequestSignatureException(
                            "Invalid signature in NetscapeCertRequest, popo-verification failed.");
                }
                log.debug("POPO verification successful");
                PublicKey pubKey = nscr.getPublicKey();
                imsg = new SimpleRequestMessage(pubKey, username, password);
            }
        } else if (reqType == SecConst.CERT_REQ_TYPE_CRMF) {
            byte[] request = Base64.decode(req.getBytes());
            ASN1InputStream in = new ASN1InputStream(request);
            ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject();
            ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0);
            CertRequest certReq = new CertRequest(reqSeq);
            SubjectPublicKeyInfo pKeyInfo = certReq.getCertTemplate().getPublicKey();
            KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
            KeySpec keySpec = new X509EncodedKeySpec(pKeyInfo.getEncoded());
            PublicKey pubKey = keyFact.generatePublic(keySpec); // just check it's ok
            imsg = new SimpleRequestMessage(pubKey, username, password);
            // a simple crmf is not a complete PKI message, as desired by the CrmfRequestMessage class
            //PKIMessage msg = PKIMessage.getInstance(new ASN1InputStream(new ByteArrayInputStream(request)).readObject());
            //CrmfRequestMessage reqmsg = new CrmfRequestMessage(msg, null, true, null);
            //imsg = reqmsg;
        } else if (reqType == SecConst.CERT_REQ_TYPE_PUBLICKEY) {
            byte[] request;
            // Request can be Base64 encoded or in PEM format
            try {
                request = FileTools.getBytesFromPEM(req.getBytes(), CertTools.BEGIN_PUBLIC_KEY,
                        CertTools.END_PUBLIC_KEY);
            } catch (IOException ex) {
                try {
                    request = Base64.decode(req.getBytes());
                    if (request == null) {
                        throw new IOException("Base64 decode of buffer returns null");
                    }
                } catch (ArrayIndexOutOfBoundsException ae) {
                    throw new IOException(
                            "Base64 decode fails, message not base64 encoded: " + ae.getMessage());
                }
            }
            final ASN1InputStream in = new ASN1InputStream(request);
            final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(in.readObject());
            final AlgorithmIdentifier keyAlg = keyInfo.getAlgorithmId();
            final X509EncodedKeySpec xKeySpec = new X509EncodedKeySpec(new DERBitString(keyInfo).getBytes());
            final KeyFactory keyFact = KeyFactory.getInstance(keyAlg.getObjectId().getId(), "BC");
            final PublicKey pubKey = keyFact.generatePublic(xKeySpec);
            imsg = new SimpleRequestMessage(pubKey, username, password);
        }
        if (imsg != null) {
            retval = getCertResponseFromPublicKey(admin, imsg, hardTokenSN, responseType, userdata);
        }
    } catch (NotFoundException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (InvalidKeyException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (NoSuchAlgorithmException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (InvalidKeySpecException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (NoSuchProviderException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (SignatureException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (IOException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (CertificateException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (EjbcaException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    }
    return retval;
}

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

/** Generate a CRL or a deltaCRL
 * /*from ww  w. j  a  v a  2  s.  co  m*/
 * @param certs list of revoked certificates
 * @param crlnumber CRLNumber for this CRL
 * @param isDeltaCRL true if we should generate a DeltaCRL
 * @param basecrlnumber caseCRLNumber for a delta CRL, use 0 for full CRLs
 * @param certProfile certificate profile for CRL Distribution point in the CRL, or null
 * @return CRL
 * @throws CATokenOfflineException
 * @throws IllegalKeyStoreException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private CRL generateCRL(Collection<RevokedCertInfo> certs, long crlPeriod, int crlnumber, boolean isDeltaCRL,
        int basecrlnumber)
        throws CATokenOfflineException, IllegalKeyStoreException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }
    Date thisUpdate = new Date();
    Date nextUpdate = new Date();

    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    X509V2CRLGenerator crlgen = new X509V2CRLGenerator();
    crlgen.setThisUpdate(thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    crlgen.setSignatureAlgorithm(sigAlg);
    // Make DNs
    X509Certificate cacert = (X509Certificate) getCACertificate();
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        X509NameEntryConverter converter = null;
        if (getUsePrintableStringSubjectDN()) {
            converter = new PrintableStringEntryConverter();
        } else {
            converter = new X509DefaultEntryConverter();
        }

        X509Name caname = CertTools.stringToBcX509Name(getSubjectDN(), converter, getUseLdapDNOrder());
        crlgen.setIssuerDN(caname);
    } else {
        crlgen.setIssuerDN(cacert.getSubjectX500Principal());
    }
    if (certs != null) {
        Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(
                new ByteArrayInputStream(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN).getEncoded()))
                        .readObject());
        AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
        crlgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), getAuthorityKeyIdentifierCritical(),
                aki);
    }
    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(X509Extensions.CRLNumber.getId(), this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(X509Extensions.DeltaCRLIndicator.getId(), true, basecrlnum);
    }
    // CRL Distribution point URI and Freshest CRL DP
    if (getUseCrlDistributionPointOnCrl()) {
        String crldistpoint = getDefaultCRLDistPoint();
        List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint);

        if (distpoints.size() > 0) {
            IssuingDistributionPoint idp = new IssuingDistributionPoint(
                    distpoints.get(0).getDistributionPoint(), false, false, null, false, false);

            // According to the RFC, IDP must be a critical extension.
            // Nonetheless, at the moment, Mozilla is not able to correctly
            // handle the IDP extension and discards the CRL if it is critical.
            crlgen.addExtension(X509Extensions.IssuingDistributionPoint.getId(),
                    getCrlDistributionPointOnCrlCritical(), idp);
        }

        if (!isDeltaCRL) {
            String crlFreshestDP = getCADefinedFreshestCRL();
            List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP);
            if (freshestDistPoints.size() > 0) {
                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints
                        .toArray(new DistributionPoint[freshestDistPoints.size()]));

                // According to the RFC, the Freshest CRL extension on a
                // CRL must not be marked as critical. Therefore it is
                // hardcoded as not critical and is independent of
                // getCrlDistributionPointOnCrlCritical().
                crlgen.addExtension(X509Extensions.FreshestCRL.getId(), false, ext);
            }

        }
    }

    X509CRL crl;
    crl = crlgen.generate(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN),
            getCAToken().getProvider());
    // Verify using the CA certificate before returning
    // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL
    // because something is wrong...
    PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
    } else {
        verifyKey = getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN);
    }
    crl.verify(verifyKey);

    return crl;
}

From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtension.java

License:Open Source License

/**
 * Tries to read the hex-string as an DERObject. If it contains more than one DEREncodable object, return a DERSequence of the objects.
 *///from ww w  .  jav  a2s.  c  o m
private DEREncodable parseHexEncodedDERObject(String value) throws CertificateExtentionConfigurationException {
    DEREncodable retval = null;
    if (value.matches("^\\p{XDigit}*")) {
        byte[] bytes = Hex.decode(value);
        try {
            ASN1InputStream ais = new ASN1InputStream(bytes);
            DEREncodable firstObject = ais.readObject();
            if (ais.available() > 0) {
                ASN1EncodableVector ev = new ASN1EncodableVector();
                ev.add(firstObject);
                while (ais.available() > 0) {
                    ev.add(ais.readObject());
                }
                retval = new DERSequence(ev);
            } else {
                retval = firstObject;
            }
        } catch (Exception e) {
            throw new CertificateExtentionConfigurationException(intres.getLocalizedMessage(
                    "certext.basic.illegalvalue", value, Integer.valueOf(getId()), getOID()));
        }
    } else {
        throw new CertificateExtentionConfigurationException(intres
                .getLocalizedMessage("certext.basic.illegalvalue", value, Integer.valueOf(getId()), getOID()));
    }
    return retval;
}