Example usage for org.bouncycastle.asn1 DERSequence DERSequence

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

Introduction

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

Prototype

public DERSequence(ASN1Encodable[] elements) 

Source Link

Document

Create a sequence containing an array of objects.

Usage

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

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    DERSequence ret = null;// w  w w .j  a v a 2 s.c  o  m
    // The UserNotice policy qualifier can have two different character encodings,
    // the correct one (UTF8) or the wrong one (BMP) used by IE < 7.
    final X509CA x509ca = (X509CA) ca;
    int displayencoding = DisplayText.CONTENT_TYPE_BMPSTRING;
    if (x509ca.getUseUTF8PolicyText()) {
        displayencoding = DisplayText.CONTENT_TYPE_UTF8STRING;
    }
    // Iterate through policies and add oids and policy qualifiers if they exist
    final List policies = certProfile.getCertificatePolicies();
    final Map policiesMap = new HashMap(); //<DERObjectIdentifier, ASN1EncodableVector>
    // Each Policy OID can be entered several times, with different qualifiers, 
    // because of this we make a map of oid and qualifiers, and we can add a new qualifier
    // in each round of this for loop
    for (final Iterator it = policies.iterator(); it.hasNext();) {
        final CertificatePolicy policy = (CertificatePolicy) it.next();
        final DERObjectIdentifier oid = new DERObjectIdentifier(policy.getPolicyID());
        final ASN1EncodableVector qualifiers;
        if (policiesMap.containsKey(oid)) {
            qualifiers = (ASN1EncodableVector) policiesMap.get(oid);
        } else {
            qualifiers = new ASN1EncodableVector();
        }
        final PolicyQualifierInfo pqi = getPolicyQualifierInformation(policy, displayencoding);
        if (pqi != null) {
            qualifiers.add(pqi);
        }
        policiesMap.put(oid, qualifiers);
    }
    final ASN1EncodableVector seq = new ASN1EncodableVector();
    for (final Iterator it = policiesMap.keySet().iterator(); it.hasNext();) {
        final DERObjectIdentifier oid = (DERObjectIdentifier) it.next();
        final ASN1EncodableVector qualifiers = (ASN1EncodableVector) policiesMap.get(oid);
        if (qualifiers.size() == 0) {
            seq.add(new PolicyInformation(oid, null));
        } else {
            seq.add(new PolicyInformation(oid, new DERSequence(qualifiers)));
        }
    }
    if (seq.size() > 0) {
        ret = new DERSequence(seq);
    }
    if (ret == null) {
        log.error("Certificate policies missconfigured, no policies present!");
    }
    return ret;
}

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

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    String crldistpoint = certProfile.getCRLDistributionPointURI();
    String crlissuer = certProfile.getCRLIssuer();
    final X509CA x509ca = (X509CA) ca;
    if (certProfile.getUseDefaultCRLDistributionPoint()) {
        crldistpoint = x509ca.getDefaultCRLDistPoint();
        crlissuer = x509ca.getDefaultCRLIssuer();
    }//from   w  ww .java 2  s  .  c o m
    // Multiple CDPs are separated with the ';' sign                        
    final ArrayList<DistributionPointName> dpns = new ArrayList<DistributionPointName>();
    if (StringUtils.isNotEmpty(crldistpoint)) {
        final Iterator<String> it = StringTools.splitURIs(crldistpoint).iterator();
        while (it.hasNext()) {
            // 6 is URI
            final String uri = (String) it.next();
            final GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier,
                    new DERIA5String(uri));
            if (log.isDebugEnabled()) {
                log.debug("Added CRL distpoint: " + uri);
            }
            final ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(gn);
            final GeneralNames gns = new GeneralNames(new DERSequence(vec));
            final DistributionPointName dpn = new DistributionPointName(0, gns);
            dpns.add(dpn);
        }
    }
    // CRL issuer works much like Dist point URI. If separated by ; it is put in the same global distPoint as the URI, 
    // if there is more of one of them, the one with more is put in an own global distPoint.
    final ArrayList<GeneralNames> issuers = new ArrayList<GeneralNames>();
    if (StringUtils.isNotEmpty(crlissuer)) {
        final StringTokenizer tokenizer = new StringTokenizer(crlissuer, ";", false);
        while (tokenizer.hasMoreTokens()) {
            final String issuer = tokenizer.nextToken();
            final GeneralName gn = new GeneralName(new X509Name(issuer));
            if (log.isDebugEnabled()) {
                log.debug("Added CRL issuer: " + issuer);
            }
            final ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(gn);
            final GeneralNames gns = new GeneralNames(new DERSequence(vec));
            issuers.add(gns);
        }
    }
    final ArrayList<DistributionPoint> distpoints = new ArrayList<DistributionPoint>();
    if ((!issuers.isEmpty()) || (!dpns.isEmpty())) {
        int i = dpns.size();
        if (issuers.size() > i) {
            i = issuers.size();
        }
        for (int j = 0; j < i; j++) {
            DistributionPointName dpn = null;
            GeneralNames issuer = null;
            if (dpns.size() > j) {
                dpn = (DistributionPointName) dpns.get(j);
            }
            if (issuers.size() > j) {
                issuer = (GeneralNames) issuers.get(j);
            }
            if ((dpn != null) || (issuer != null)) {
                distpoints.add(new DistributionPoint(dpn, null, issuer));
            }
        }
    }
    CRLDistPoint ret = null;
    if (!distpoints.isEmpty()) {
        ret = new CRLDistPoint(
                (DistributionPoint[]) distpoints.toArray(new DistributionPoint[distpoints.size()]));
    }
    if (ret == null) {
        log.error("DrlDistributionPoints missconfigured, no distribution points available.");
    }
    return ret;
}

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

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    String freshestcrldistpoint = certProfile.getFreshestCRLURI();
    final X509CA x509ca = (X509CA) ca;
    if (certProfile.getUseCADefinedFreshestCRL()) {
        freshestcrldistpoint = x509ca.getCADefinedFreshestCRL();
    }/* w  w  w.j ava  2  s .  co  m*/
    // Multiple FCDPs are separated with the ';' sign
    CRLDistPoint ret = null;
    if (freshestcrldistpoint != null) {
        final StringTokenizer tokenizer = new StringTokenizer(freshestcrldistpoint, ";", false);
        final ArrayList<DistributionPoint> distpoints = new ArrayList<DistributionPoint>();
        while (tokenizer.hasMoreTokens()) {
            final String uri = tokenizer.nextToken();
            final GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier,
                    new DERIA5String(uri));
            if (log.isDebugEnabled()) {
                log.debug("Added freshest CRL distpoint: " + uri);
            }
            final ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(gn);
            final GeneralNames gns = new GeneralNames(new DERSequence(vec));
            final DistributionPointName dpn = new DistributionPointName(0, gns);
            distpoints.add(new DistributionPoint(dpn, null, null));
        }
        if (!distpoints.isEmpty()) {
            ret = new CRLDistPoint(
                    (DistributionPoint[]) distpoints.toArray(new DistributionPoint[distpoints.size()]));
        }
    }
    if (ret == null) {
        log.error("UseFreshestCRL is true, but no URI string defined!");
    }
    return ret;
}

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

License:Open Source License

private static DERSequence privateKeyUsagePeriod(final Date notBefore, final Date notAfter)
        throws CertificateExtentionConfigurationException {
    // Create the extension.
    // PrivateKeyUsagePeriod ::= SEQUENCE {
    //   notBefore       [0]     GeneralizedTime OPTIONAL,
    //   notAfter        [1]     GeneralizedTime OPTIONAL }
    final ASN1EncodableVector v = new ASN1EncodableVector();
    if (notBefore != null) {
        v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(notBefore)));
    }/* w  ww  . j av a2 s.  c o  m*/
    if (notAfter != null) {
        v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(notAfter)));
    }
    if (v.size() == 0) {
        throw new CertificateExtentionConfigurationException(
                "At least one of notBefore and notAfter must be specified!");
    }
    return new DERSequence(v);
}

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

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    DERSequence ret = null;//from  ww w . j  av a  2 s  .c  o  m
    final String names = certProfile.getQCStatementRAName();
    final GeneralNames san = CertTools.getGeneralNamesFromAltName(names);
    SemanticsInformation si = null;
    if (san != null) {
        if (StringUtils.isNotEmpty(certProfile.getQCSemanticsId())) {
            si = new SemanticsInformation(new DERObjectIdentifier(certProfile.getQCSemanticsId()),
                    san.getNames());
        } else {
            si = new SemanticsInformation(san.getNames());
        }
    } else if (StringUtils.isNotEmpty(certProfile.getQCSemanticsId())) {
        si = new SemanticsInformation(new DERObjectIdentifier(certProfile.getQCSemanticsId()));
    }
    final ArrayList<QCStatement> qcs = new ArrayList<QCStatement>();
    QCStatement qc = null;
    // First the standard rfc3739 QCStatement with an optional SematicsInformation
    DERObjectIdentifier pkixQcSyntax = RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v1;
    if (certProfile.getUsePkixQCSyntaxV2()) {
        pkixQcSyntax = RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v2;
    }
    if ((si != null)) {
        qc = new QCStatement(pkixQcSyntax, si);
        qcs.add(qc);
    } else {
        qc = new QCStatement(pkixQcSyntax);
        qcs.add(qc);
    }
    // ETSI Statement that the certificate is a Qualified Certificate
    if (certProfile.getUseQCEtsiQCCompliance()) {
        qc = new QCStatement(ETSIQCObjectIdentifiers.id_etsi_qcs_QcCompliance);
        qcs.add(qc);
    }
    // ETSI Statement regarding limit on the value of transactions
    // Both value and currency must be available for this extension
    if (certProfile.getUseQCEtsiValueLimit() && (certProfile.getQCEtsiValueLimit() >= 0)
            && (certProfile.getQCEtsiValueLimitCurrency() != null)) {
        final int limit = certProfile.getQCEtsiValueLimit();
        // The exponent should be default 0
        final int exponent = certProfile.getQCEtsiValueLimitExp();
        final MonetaryValue value = new MonetaryValue(
                new Iso4217CurrencyCode(certProfile.getQCEtsiValueLimitCurrency()), limit, exponent);
        qc = new QCStatement(ETSIQCObjectIdentifiers.id_etsi_qcs_LimiteValue, value);
        qcs.add(qc);
    }

    if (certProfile.getUseQCEtsiRetentionPeriod()) {
        final DERInteger years = new DERInteger(((Integer) certProfile.getQCEtsiRetentionPeriod()));
        qc = new QCStatement(ETSIQCObjectIdentifiers.id_etsi_qcs_RetentionPeriod, years);
        qcs.add(qc);
    }

    // ETSI Statement claiming that the private key resides in a Signature Creation Device
    if (certProfile.getUseQCEtsiSignatureDevice()) {
        qc = new QCStatement(ETSIQCObjectIdentifiers.id_etsi_qcs_QcSSCD);
        qcs.add(qc);
    }
    // Custom UTF8String QC-statement:
    // qcStatement-YourCustom QC-STATEMENT ::= { SYNTAX YourCustomUTF8String
    //   IDENTIFIED BY youroid }
    //   -- This statement gives you the possibility to define your own QC-statement
    //   -- using an OID and a simple UTF8String, with describing text. A sample text could for example be:
    //   -- This certificate, according to Act. No. xxxx Electronic Signature Law is a qualified electronic certificate
    //
    // YourCustomUTF8String ::= UTF8String
    if (certProfile.getUseQCCustomString() && !StringUtils.isEmpty(certProfile.getQCCustomStringOid())
            && !StringUtils.isEmpty(certProfile.getQCCustomStringText())) {
        final DERUTF8String str = new DERUTF8String(certProfile.getQCCustomStringText());
        final DERObjectIdentifier oid = new DERObjectIdentifier(certProfile.getQCCustomStringOid());
        qc = new QCStatement(oid, str);
        qcs.add(qc);
    }
    if (!qcs.isEmpty()) {
        final ASN1EncodableVector vec = new ASN1EncodableVector();
        final Iterator<QCStatement> iter = qcs.iterator();
        while (iter.hasNext()) {
            final QCStatement q = (QCStatement) iter.next();
            vec.add(q);
        }
        ret = new DERSequence(vec);
    }
    if (ret == null) {
        log.error("QcStatements is used, but no statement defined!");
    }
    return ret;
}

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

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    DEREncodable ret = null;/*from   w w w . ja  v  a 2  s .co  m*/
    final String dirAttrString = subject.getExtendedinformation() != null
            ? subject.getExtendedinformation().getSubjectDirectoryAttributes()
            : null;
    if (StringUtils.isNotEmpty(dirAttrString)) {
        // Subject Directory Attributes is a sequence of Attribute
        final Collection<Attribute> attr = SubjectDirAttrExtension.getSubjectDirectoryAttributes(dirAttrString);
        final ASN1EncodableVector vec = new ASN1EncodableVector();
        final Iterator<Attribute> iter = attr.iterator();
        while (iter.hasNext()) {
            vec.add(iter.next());
        }
        if (vec.size() > 0) {
            ret = new DERSequence(vec);
        }
    }
    if (ret == null) {
        log.debug("No directory attributes trying to create SubjectDirectoryAttributes extension: "
                + dirAttrString);
    }
    return ret;
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java

License:Open Source License

/**
 * Converts the header and the body of a PKIMessage to an ASN1Encodable and 
 * returns the as a byte array/*  ww  w .j a  va2  s  .com*/
 *  
 * @param header
 * @param body
 * @return the PKIMessage's header and body in byte array
 */
public static byte[] getProtectedBytes(PKIHeader header, PKIBody body) {
    byte[] res = null;
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(header);
    v.add(body);
    ASN1Encodable protectedPart = new DERSequence(v);
    try {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(protectedPart);
        res = bao.toByteArray();
    } catch (Exception ex) {
        LOG.error(ex.getLocalizedMessage(), ex);
    }
    return res;
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java

License:Open Source License

public static RevDetails getNovosecRevDetails(RevReqContent revContent) {
    // Novosec implements RFC2510, while bouncycastle 1.47 implements RFC4210.
    ////from w w w .ja  v  a2  s  .  co  m
    // In RFC2510/novosec, the RevDetails structure looks like this:
    //              RevDetails ::= SEQUENCE {
    //                                  certDetails         CertTemplate,
    //                                  revocationReason    ReasonFlags      OPTIONAL,
    //                                  badSinceDate        GeneralizedTime  OPTIONAL,
    //                                  crlEntryDetails     Extensions       OPTIONAL
    //             }
    //
    // In RFC4210/bouncycastle, the REVDetails structure looks like this:
    //                 RevDetails ::= SEQUENCE {
    //                                  certDetails         CertTemplate,
    //                                  crlEntryDetails     Extensions       OPTIONAL
    //                  }
    //
    // This means that there is a chance that the request generated using novosec specifies the revocation reason in 'revocationReason' and not
    // as an extension, leading to Ejbca not being able to parse the request using bouncycastle OR not setting the correct revocation reason.

    ASN1Encodable o2 = ((DERSequence) revContent.toASN1Primitive()).getObjectAt(0);
    ASN1Encodable o3 = ((DERSequence) o2).getObjectAt(0);
    CertTemplate ct = CertTemplate.getInstance(o3);

    ReasonFlags reasonbits = null;
    Extensions crlEntryDetails = null;
    int seqSize = ((DERSequence) o2).size();
    for (int i = 1; i < seqSize; i++) {
        ASN1Encodable o4 = ((DERSequence) o2).getObjectAt(i);
        if (o4 instanceof DERBitString) {
            reasonbits = new ReasonFlags((DERBitString) o4);
        } else if (o4 instanceof DERGeneralizedTime) {
            DERGeneralizedTime.getInstance(o4); // bad since time, not used in the bouncycastle class
        } else if (o4 instanceof DERSequence) {
            crlEntryDetails = Extensions.getInstance(o4);
        }
    }

    if ((crlEntryDetails != null) && (reasonbits != null)) {
        Extension reason = crlEntryDetails.getExtension(Extension.reasonCode);
        if (reason == null) {
            reason = new Extension(Extension.reasonCode, true,
                    ASN1OctetString.getInstance(reasonbits.getBytes()));
        }
    } else if ((crlEntryDetails == null) && (reasonbits != null)) {
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        try {
            extgen.addExtension(Extension.reasonCode, true, ASN1OctetString.getInstance(reasonbits.getBytes()));
            crlEntryDetails = extgen.generate();
        } catch (IOException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }

    //The constructor RevDetails(certTemplate, crlEntryDetails) only sets 'crlEntryDetails' and ignores 'certTemplate'
    //This is a reported bug in bouncycastle. For now, the only way to have both of them set is to create a ASN1/DERSequence 
    ASN1EncodableVector seq = new ASN1EncodableVector();
    seq.add(ct);
    seq.add(crlEntryDetails);
    RevDetails res = RevDetails.getInstance(new DERSequence(seq));
    return res;
}

From source file:org.ejbca.core.protocol.cmp.CmpResponseMessage.java

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    boolean ret = false;
    // Some general stuff, common for all types of messages
    String issuer = null;//from   w ww.  ja va  2  s . co  m
    String subject = null;
    if (cert != null) {
        X509Certificate x509cert = (X509Certificate) cert;
        issuer = x509cert.getIssuerDN().getName();
        subject = x509cert.getSubjectDN().getName();
    } else if ((signCertChain != null) && (signCertChain.size() > 0)) {
        issuer = ((X509Certificate) signCertChain.iterator().next()).getSubjectDN().getName();
        subject = "CN=fooSubject";
    } else {
        issuer = "CN=fooIssuer";
        subject = "CN=fooSubject";
    }

    final GeneralName issuerName = new GeneralName(new X500Name(issuer));
    final GeneralName subjectName = new GeneralName(new X500Name(subject));
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(issuerName, subjectName,
            senderNonce, recipientNonce, transactionId);
    PKIBody myPKIBody = null;
    final PKIMessage myPKIMessage;

    try {
        if (status.equals(ResponseStatus.SUCCESS)) {
            if (cert != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Creating a CertRepMessage 'accepted'");
                }
                PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
                ASN1InputStream certASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cert.getEncoded()));
                ASN1InputStream cacertASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cacert.getEncoded()));
                try {
                    try {
                        CMPCertificate cmpcert = CMPCertificate.getInstance(certASN1InputStream.readObject());
                        CertOrEncCert retCert = new CertOrEncCert(cmpcert);
                        CertifiedKeyPair myCertifiedKeyPair = new CertifiedKeyPair(retCert);
                        CertResponse myCertResponse = new CertResponse(new ASN1Integer(requestId),
                                myPKIStatusInfo, myCertifiedKeyPair, null);

                        CertResponse[] certRespos = { myCertResponse };
                        CMPCertificate[] caPubs = {
                                CMPCertificate.getInstance(cacertASN1InputStream.readObject()) };

                        CertRepMessage myCertRepMessage = new CertRepMessage(caPubs, certRespos);

                        int respType = requestType + 1; // 1 = intitialization response, 3 = certification response etc
                        if (log.isDebugEnabled()) {
                            log.debug("Creating response body of type " + respType);
                        }
                        myPKIBody = new PKIBody(respType, myCertRepMessage);
                    } finally {
                        certASN1InputStream.close();
                        cacertASN1InputStream.close();
                    }
                } catch (IOException e) {
                    throw new IllegalStateException("Unexpected IOException caught.", e);
                }
            }
        } else if (status.equals(ResponseStatus.FAILURE)) {
            if (log.isDebugEnabled()) {
                log.debug("Creating a CertRepMessage 'rejected'");
            }
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(ASN1Integer.getInstance(PKIStatus.rejection.toASN1Primitive()));
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo
                    .getInstance(ASN1Sequence.getInstance(new DERSequence(statusInfoV)));
            myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType);

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Creating a 'waiting' message?");
            }
            // Not supported, lets create a PKIError failure instead
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(PKIStatus.rejection); // 2 = rejection
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo.getInstance(new DERSequence(statusInfoV));

            ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo);
            myPKIBody = new PKIBody(23, myErrorContent); // 23 = error                
        }

        if ((pbeKeyId != null) && (pbeKey != null) && (pbeDigestAlg != null) && (pbeMacAlg != null)) {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, pbeKeyId, pbeKey,
                    pbeDigestAlg, pbeMacAlg, pbeIterationCount);
        } else {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digest));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digest,
                    provider);
        }

        ret = true;

    } catch (CertificateEncodingException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (InvalidKeyException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchProviderException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SecurityException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SignatureException e) {
        log.error("Error creating CertRepMessage: ", e);
    }

    return ret;
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

License:Open Source License

protected static PKIMessage genCertReq(String issuerDN, X500Name userDN, String altNames, KeyPair keys,
        Certificate cacert, byte[] nonce, byte[] transid, boolean raVerifiedPopo, Extensions extensions,
        Date notBefore, Date notAfter, BigInteger customCertSerno, AlgorithmIdentifier pAlg,
        DEROctetString senderKID) throws NoSuchAlgorithmException, NoSuchProviderException, IOException,
        InvalidKeyException, SignatureException {
    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    if (notBefore != null) {
        nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    }//from  ww w.  j  a va  2  s. c o m
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    if (notAfter != null) {
        na = new org.bouncycastle.asn1.x509.Time(notAfter);
    }
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    if (issuerDN != null) {
        myCertTemplate.setIssuer(new X500Name(issuerDN));
    }
    myCertTemplate.setSubject(userDN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
    dIn.close();
    myCertTemplate.setPublicKey(keyInfo);
    // If we did not pass any extensions as parameter, we will create some of our own, standard ones
    Extensions exts = extensions;
    if (exts == null) {

        // SubjectAltName
        // Some altNames
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ASN1OutputStream dOut = new ASN1OutputStream(bOut);
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        if (altNames != null) {
            GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames);
            dOut.writeObject(san);
            byte[] value = bOut.toByteArray();
            extgen.addExtension(Extension.subjectAlternativeName, false, value);
        }

        // KeyUsage
        int bcku = 0;
        bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation;
        KeyUsage ku = new KeyUsage(bcku);
        extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku));

        // Make the complete extension package
        exts = extgen.generate();
    }
    myCertTemplate.setExtensions(exts);
    if (customCertSerno != null) {
        // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order
        // to request a custom certificate serial number (something not standard anyway)
        myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno));
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (raVerifiedPopo) {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg, "BC");
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);
        DERBitString bs = new DERBitString(sig.sign());
        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(
            new X500Name(issuerDN != null ? issuerDN : ((X509Certificate) cacert).getSubjectDN().getName())));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization
                                                           // request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}