Example usage for org.bouncycastle.asn1 ASN1EncodableVector ASN1EncodableVector

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

Introduction

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

Prototype

public ASN1EncodableVector() 

Source Link

Usage

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 ww .j a  v a2 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 a  2 s.co 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   w  ww  .  ja  v  a 2  s. com
    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  .j  ava 2  s. c  om
    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/*from   w ww .ja  v a 2 s.  c  o m*/
 *  
 * @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  . j ava  2s.c o 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  w w.j  ava  2s .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);
    }/*  w w w.j av  a  2  s  .  com*/
    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;
}

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

License:Open Source License

protected static PKIMessage genRevReq(String issuerDN, X500Name userDN, BigInteger serNo, Certificate cacert,
        byte[] nonce, byte[] transid, boolean crlEntryExtension, AlgorithmIdentifier pAlg,
        DEROctetString senderKID) throws IOException {
    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setIssuer(new X500Name(issuerDN));
    myCertTemplate.setSubject(userDN);/*from   www. ja v  a2s  .co m*/
    myCertTemplate.setSerialNumber(new ASN1Integer(serNo));

    ExtensionsGenerator extgen = new ExtensionsGenerator();
    CRLReason crlReason;
    if (crlEntryExtension) {
        crlReason = CRLReason.lookup(CRLReason.cessationOfOperation);
    } else {
        crlReason = CRLReason.lookup(CRLReason.keyCompromise);
    }
    extgen.addExtension(Extension.reasonCode, false, crlReason);

    Extensions exts = extgen.generate();

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(myCertTemplate.build());
    v.add(exts);
    ASN1Sequence seq = new DERSequence(v);

    RevDetails myRevDetails = RevDetails.getInstance(seq); //new RevDetails(myCertTemplate.build(), exts);

    RevReqContent myRevReqContent = new RevReqContent(myRevDetails);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN),
            new GeneralName(new X500Name(((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(PKIBody.TYPE_REVOCATION_REQ, myRevReqContent); // revocation request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

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

License:Open Source License

protected static PKIMessage genCertConfirm(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid,
        String hash, int certReqId) {

    String issuerDN = "CN=foobarNoCA";
    if (cacert != null) {
        issuerDN = ((X509Certificate) cacert).getSubjectDN().getName();
    }/* ww w. j a  v a 2 s  . c o  m*/
    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN),
            new GeneralName(new X500Name(issuerDN)));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));

    CertStatus cs = new CertStatus(hash.getBytes(), new BigInteger(Integer.toString(certReqId)));

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(cs);
    CertConfirmContent cc = CertConfirmContent.getInstance(new DERSequence(v));

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_CERT_CONFIRM, cc); // Cert Confirm
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}