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.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

/**
 * This test tests that the OCSP response contains is signed by the preferred signature algorithm specified in the request.
 * /*w  w w  .j  a v a  2  s.  co  m*/
 * @throws Exception
*/
@Test
@Deprecated // This test verifies legacy behavior from EJBCA 6.1.0 and should be removed when we no longer need to support it
public void testSigAlgExtensionLegacy() throws Exception {
    loadUserCert(this.caid);

    // Try sending a request where the preferred signature algorithm in the extension is expected to be used to sign the response.

    // set ocsp configuration
    Map<String, String> map = new HashMap<String, String>();
    map.put("ocsp.signaturealgorithm",
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA + ";" + AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
    this.helper.alterConfig(map);

    ASN1EncodableVector algVec = new ASN1EncodableVector();
    algVec.add(X9ObjectIdentifiers.ecdsa_with_SHA256);
    algVec.add(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    ASN1Sequence algSeq = new DERSequence(algVec);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    // RFC 6960: id-pkix-ocsp-pref-sig-algs   OBJECT IDENTIFIER ::= { id-pkix-ocsp 8 } 
    extgen.addExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"), false, algSeq);
    Extensions exts = extgen.generate();
    assertNotNull(exts);

    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()), exts);
    gen.setRequestExtensions(exts);
    OCSPReq req = gen.build();
    assertTrue(req.hasExtensions());

    BasicOCSPResp response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200);
    assertNotNull("Could not retrieve response, test could not continue.", response);
    assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption, response.getSignatureAlgOID());

    // Try sending a request where the preferred signature algorithm is not compatible with the signing key, but 
    // the configured algorithm is. Expected a response signed using the first configured algorithm

    algVec = new ASN1EncodableVector();
    algVec.add(X9ObjectIdentifiers.ecdsa_with_SHA256);
    algSeq = new DERSequence(algVec);

    extgen = new ExtensionsGenerator();
    extgen.addExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"), false, algSeq);
    exts = extgen.generate();
    assertNotNull(exts);

    gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()), exts);
    gen.setRequestExtensions(exts);
    req = gen.build();
    assertTrue(req.hasExtensions());

    response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200);
    assertNotNull("Could not retrieve response, test could not continue.", response);
    assertEquals(PKCSObjectIdentifiers.sha256WithRSAEncryption, response.getSignatureAlgOID());
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

/** @return a RFC 6960 PreferredSignatureAlgorithms object. */
private ASN1Sequence getPreferredSignatureAlgorithms(final ASN1ObjectIdentifier... algorithmOids) {
    final ASN1Encodable[] asn1Encodables = new ASN1Encodable[algorithmOids.length];
    for (int i = 0; i < algorithmOids.length; i++) {
        // PreferredSignatureAlgorithm ::= SEQUENCE { sigIdentifier AlgorithmIdentifier, pubKeyAlgIdentifier SMIMECapability OPTIONAL } 
        final ASN1Sequence preferredSignatureAlgorithm = new DERSequence(
                new ASN1Encodable[] { new AlgorithmIdentifier(algorithmOids[i]) });
        asn1Encodables[i] = preferredSignatureAlgorithm;
    }//w w  w .  j a va2  s  . c o m
    // PreferredSignatureAlgorithms ::= SEQUENCE OF PreferredSignatureAlgorithm 
    final ASN1Sequence preferredSignatureAlgorithms = new DERSequence(asn1Encodables);
    return preferredSignatureAlgorithms;
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

License:Open Source License

private PKCS10CertificationRequest getP10Request() throws Exception {
    final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    // Make a PKCS10 request with extensions
    ASN1EncodableVector attributes = new ASN1EncodableVector();
    // Add a custom extension (dummy)
    ASN1EncodableVector attr = new ASN1EncodableVector();
    attr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(new ASN1ObjectIdentifier("1.2.3.4"), false, new DEROctetString("foo123".getBytes()));
    Extensions exts = extgen.generate();
    attr.add(new DERSet(exts));
    attributes.add(new DERSequence(attr));
    PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA1WithRSA",
            CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(attributes),
            keys.getPrivate(), null);//from   ww w .  ja va2 s. com
    return pkcs10;
}

From source file:org.ejbca.extra.ra.ScepRequestGenerator.java

License:Open Source License

/** Generates a SCEP CertReq. Keys must have been set in the generator for this to succeed 
 * /*from w ww  .jav  a  2  s .c  o  m*/
 */
public byte[] generateCertReq(String dn, String password, X509Certificate ca)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException,
        IOException, CMSException, InvalidAlgorithmParameterException, CertStoreException,
        CertificateEncodingException, IllegalStateException {
    this.cacert = ca;
    this.reqdn = dn;

    // Create challenge password attribute for PKCS10
    // Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
    //
    // Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
    //    type    ATTRIBUTE.&id({IOSet}),
    //    values  SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
    // }
    ASN1EncodableVector challpwdattr = new ASN1EncodableVector();
    // Challenge password attribute
    challpwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
    pwdvalues.add(new DERUTF8String(password));
    challpwdattr.add(new DERSet(pwdvalues));
    // Requested extensions attribute
    ASN1EncodableVector extensionattr = new ASN1EncodableVector();
    extensionattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    // AltNames
    GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo.bar.com,iPAddress=10.0.0.1");
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    try {
        dOut.writeObject(san);
    } catch (IOException e) {
        throw new IllegalArgumentException("error encoding value: " + e);
    }
    Vector oidvec = new Vector();
    oidvec.add(X509Extensions.SubjectAlternativeName);
    Vector valuevec = new Vector();
    valuevec.add(new X509Extension(false, new DEROctetString(bOut.toByteArray())));
    X509Extensions exts = new X509Extensions(oidvec, valuevec);
    extensionattr.add(new DERSet(exts));
    // Complete the Attribute section of the request, the set (Attributes) contains two sequences (Attribute)
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new DERSequence(challpwdattr));
    v.add(new DERSequence(extensionattr));
    DERSet attributes = new DERSet(v);
    // Create PKCS#10 certificate request
    p10request = new PKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX509Name(reqdn),
            keys.getPublic(), attributes, keys.getPrivate());

    // Create self signed cert, validity 1 day
    cert = CertTools.genSelfCert(reqdn, 24 * 60 * 60 * 1000, null, keys.getPrivate(), keys.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);

    // wrap message in pkcs#7
    byte[] msg = wrap(p10request.getEncoded(), "19");
    return msg;
}

From source file:org.ejbca.extra.ra.ScepRequestGenerator.java

License:Open Source License

public byte[] generateGetCertInitial(String dn, X509Certificate ca)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException,
        CertStoreException, IOException, CMSException {
    this.cacert = ca;
    this.reqdn = dn;

    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(new DERUTF8String(ca.getIssuerDN().getName()));
    vec.add(new DERUTF8String(dn));
    DERSequence seq = new DERSequence(vec);

    // wrap message in pkcs#7
    byte[] msg = wrap(seq.getEncoded(), "20");
    return msg;//ww  w  . j a  v a2  s  .  c o  m
}

From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.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  w w .j a  v  a 2  s .c  o  m
 *  
 * @param header
 * @param body
 * @return the PKIMessage's header and body in byte array
 */
private 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.ui.cmpclient.commands.ConfirmationRequestCommand.java

License:Open Source License

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {

    final boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name("CN=foo");
    String issuer = parameters.get(ISSUERDN_KEY);
    if (issuer == null) {
        issuer = "CN=foobar";
        log.info("Using default issuerDN: " + issuer);
    }/* w  w w . ja  va  2 s. c  o  m*/
    final X500Name issuerDN = new X500Name(issuer);

    if (verbose) {
        log.info("Creating confirmation request with: SubjectDN=" + userDN.toString());
        log.info("Creating confirmation request with: IssuerDN=" + issuerDN.toString());
    }

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] hash = new byte[0];

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));

    CertStatus cs = new CertStatus(hash, new BigInteger("0"));

    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;
}

From source file:org.ejbca.ui.cmpclient.commands.CrmfRequestCommand.java

License:Open Source License

@Override
public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception {

    final boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));

    String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY);
    String endentityPassword = "";
    if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) {
        endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY)
                ? parameters.get(AUTHENTICATION_PARAM_KEY)
                : "foo123";
    }//from w  w  w  .  j a  v a 2 s  . c o  m

    String altNames = parameters.get(ALTNAME_KEY);
    String serno = parameters.get(SERNO_KEY);
    BigInteger customCertSerno = null;
    if (serno != null) {
        customCertSerno = new BigInteger(serno, 16);
    }
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating CRMF request with: SubjectDN=" + userDN.toString());
        log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating CRMF request with: AuthenticationModule=" + authmodule);
        log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword);
        log.info("Creating CRMF request with: SubjectAltName=" + altNames);
        log.info("Creating CRMF request with: CustomCertSerno="
                + (customCertSerno == null ? "" : customCertSerno.toString(16)));
        log.info("Creating CRMF request with: IncludePopo=" + includePopo);
    }

    final KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    final byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    final byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();

    // We should be able to back date the start time when allow validity
    // override is enabled in the certificate profile
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_WEEK, -1);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    // in validity
    Date notBefore = cal.getTime();
    cal.add(Calendar.DAY_OF_WEEK, 3);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    // in validity
    Date notAfter = cal.getTime();
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter);

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    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(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);

    // Create standard extensions
    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
    Extensions 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 (includePopo) {
        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);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(endentityPassword));
    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(issuerDN));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);
    myPKIHeader.setSenderKID(new byte[0]);

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

    return myPKIMessage;
}

From source file:org.ejbca.ui.cmpclient.commands.KeyUpdateRequestCommand.java

License:Open Source License

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating KeyUpdate request with: SubjectDN=" + userDN.toString());
        log.info("Creating KeyUpdate request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating KeyUpdate request with: IncludePopo=" + includePopo);
    }//from   ww w. j av  a 2  s  .  c  o  m

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();
    KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    myCertTemplate.setValidity(myOptionalValidity);

    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }

    myCertTemplate.setSubject(userDN);

    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 (includePopo) {
        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);
        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);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new
    // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new
    // DERInteger(1122334455)));
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(""));
    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(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}

From source file:org.ejbca.ui.cmpclient.commands.RevocationRequestCommand.java

License:Open Source License

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name("CN=foo");
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    BigInteger serno = new BigInteger(parameters.get(SERNO_KEY), 16);

    if (verbose) {
        log.info("Creating revocation request with: SubjectDN=" + userDN.toString());
        log.info("Creating revocation request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating revocation request with: CertSerno=" + serno.toString(16));
    }/*from   w  ww . j  a  va  2  s  .  c  o  m*/

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setIssuer(issuerDN);
    myCertTemplate.setSubject(userDN);
    myCertTemplate.setSerialNumber(new ASN1Integer(serno));

    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(Extension.reasonCode, false, getCRLReason(parameters.get(REVOCATION_REASON_KEY)));

    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);

    RevReqContent myRevReqContent = new RevReqContent(myRevDetails);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);
    myPKIHeader.setSenderKID(new byte[0]);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, myRevReqContent); // revocation request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}