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.protocol.cmp.CmpTestCase.java

License:Open Source License

protected static PKIMessage genRenewalReq(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid,
        KeyPair keys, boolean raVerifiedPopo, X500Name reqSubjectDN, String reqIssuerDN,
        AlgorithmIdentifier pAlg, DEROctetString senderKID) throws IOException, NoSuchAlgorithmException,
        InvalidKeyException, SignatureException, CertificateEncodingException {

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

    if (reqSubjectDN != null) {
        myCertTemplate.setSubject(reqSubjectDN);
    }/*from   w w  w .  j  a va  2  s  .c o m*/
    if (reqIssuerDN != null) {
        myCertTemplate.setIssuer(new X500Name(reqIssuerDN));
    }

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

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

    // 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("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 JcaX509CertificateHolder((X509Certificate) cacert).getSubject()));
    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_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;

}

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

License:Open Source License

/**
 * Send a CMP request with SubjectAltName containing OIDs that are not defined by Ejbca.
 * Expected to pass and a certificate containing the unsupported OIDs is returned.
 * /*from   w ww. j  av a 2 s .c om*/
 * @throws Exception
 */
@Test
public void test04UsingOtherNameInSubjectAltName() throws Exception {

    ASN1EncodableVector vec = new ASN1EncodableVector();
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new ASN1ObjectIdentifier(CertTools.UPN_OBJECTID));
    v.add(new DERTaggedObject(true, 0, new DERUTF8String("boo@bar")));
    GeneralName gn = GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v)));
    vec.add(gn);

    v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier("2.5.5.6"));
    v.add(new DERTaggedObject(true, 0,
            new DERIA5String("2.16.528.1.1007.99.8-1-993000027-N-99300011-00.000-00000000")));
    gn = GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v)));
    vec.add(gn);

    GeneralNames san = GeneralNames.getInstance(new DERSequence(vec));

    ExtensionsGenerator gen = new ExtensionsGenerator();
    gen.addExtension(Extension.subjectAlternativeName, false, san);
    Extensions exts = gen.generate();

    final X500Name userDN = new X500Name("CN=TestAltNameUser");
    final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;
    String fingerprint = null;

    try {
        final PKIMessage one = genCertReq(ISSUER_DN, userDN, keys, this.cacert, nonce, transid, true, exts,
                null, null, null, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        Assert.assertNotNull(req);
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        // do not check signing if we expect a failure (sFailMessage==null)
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        fingerprint = CertTools.getFingerprintAsString(cert);

    } finally {
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "TestAltNameUser",
                    RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE);
        } catch (NotFoundException e) {
            /*Do nothing*/}

        try {
            this.internalCertStoreSession.removeCertificate(fingerprint);
        } catch (Exception e) {
            /*Do nothing*/}
    }

}

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

License:Open Source License

private PKIMessage createPKIMessage(final String issuerDN, final String subjectDN)
        throws InvalidAlgorithmParameterException, IOException {
    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    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));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    myCertTemplate.setIssuer(new X500Name(issuerDN));
    myCertTemplate.setSubject(new X500Name(subjectDN));
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {/*from  w  ww  . j  a  va  2  s. c  om*/
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    int bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation;
    X509KeyUsage ku = new X509KeyUsage(bcku);
    bOut = new ByteArrayOutputStream();
    dOut = new DEROutputStream(bOut);
    dOut.writeObject(ku);
    byte[] value = bOut.toByteArray();
    extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value));
    myCertTemplate.setExtensions(extgen.generate());

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

    ProofOfPossession myProofOfPossession = new ProofOfPossession();
    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(new X500Name("CN=bogusSubject")),
            new GeneralName(new X500Name("CN=bogusIssuer")));
    myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
    myPKIHeader.setSenderNonce(new DEROctetString(CmpMessageHelper.createSenderNonce()));
    myPKIHeader.setTransactionID(new DEROctetString(CmpMessageHelper.createSenderNonce()));

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

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

License:Open Source License

@Test
public void test01CrmfReq()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {

    //-----------------Creating CRMF request
    //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN);
    byte[] senderNonce = CmpMessageHelper.createSenderNonce();
    byte[] transactionID = CmpMessageHelper.createSenderNonce();
    Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago
    Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now
    assertNotNull(nb);/*from ww  w  . ja va  2s.co  m*/
    assertNotNull(na);

    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID,
            false, null, nb, na, null, pAlg, new DEROctetString(senderNonce));

    String adminName = "cmpTestAdmin";
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE");
    Certificate admCert = getCertFromCredentials(adminToken);
    CMPCertificate[] cmpcert = getCMPCert(admCert);
    crmfMsg = CmpMessageHelper.buildCertBasedPKIProtection(crmfMsg, cmpcert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(crmfMsg);
    CertReqMessages ir = (CertReqMessages) crmfMsg.getBody().getContent();
    int reqID = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

    //------------------Creating NestedMessageContent
    String reqSubjectDN = "CN=bogusSubjectNested";
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(crmfMsg);
    DERSequence seq = new DERSequence(v);
    PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent
    assertNotNull("Failed to create nested Message PKIBody", myPKIBody);

    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    assertNotNull("Failed to created nested message PKIMessage", myPKIMessage);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    assertEquals(
            "RACertPath is suppose to be '" + this.raCertsPath + "', instead it is '"
                    + this.cmpConfiguration.getRACertPath(cmpAlias) + "'.",
            this.cmpConfiguration.getRACertPath(cmpAlias), this.raCertsPath);
    createRACertificate("raCrmfSigner", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null,
            CMPTESTPROFILE, this.caid);
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");

    assertNotNull("Failed to create myPKIHeader", myPKIHeader);
    assertNotNull("myPKIBody is null", myPKIBody);
    assertNotNull("myPKIMessage is null", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);

    // do not check signing if we expect a failure (sFailMessage==null)
    checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert,
            crmfMsg.getHeader().getSenderNonce().getOctets(),
            crmfMsg.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    final Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqID);
    assertTrue(cert instanceof X509Certificate);
    log.debug("Subject DN of created certificate: "
            + X500Name.getInstance(((X509Certificate) cert).getSubjectX500Principal().getEncoded()));
    assertNotNull("CrmfRequest did not return a certificate", cert);

    removeAuthenticationToken(adminToken, admCert, adminName);
}

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

License:Open Source License

@Test
public void test03RevReq() throws NoSuchAlgorithmException, AuthorizationDeniedException, EjbcaException,
        IOException, InvalidAlgorithmParameterException, RoleNotFoundException, InvalidKeyException,
        NoSuchProviderException, SecurityException, SignatureException, ObjectNotFoundException,
        CertificateException, CADoesntExistsException, IllegalKeyException, CertificateCreateException,
        IllegalNameException, CertificateRevokeException, CertificateSerialNumberException,
        CryptoTokenOfflineException, IllegalValidityException, CAOfflineException, InvalidAlgorithmException,
        CustomCertificateSerialNumberException, UserDoesntFullfillEndEntityProfile, RemoveException,
        WaitingForApprovalException, FinderException {
    Collection<Certificate> certs = this.certificateStoreSession
            .findCertificatesBySubjectAndIssuer(SUBJECT_DN.toString(), this.issuerDN);
    log.debug("Found " + certs.size() + " certificates for userDN \"" + SUBJECT_DN + "\"");
    Certificate cert = null;// w w w . j av  a2 s.com
    for (Certificate tmp : certs) {
        if (!this.certificateStoreSession.isRevoked(this.issuerDN, CertTools.getSerialNumber(tmp))) {
            cert = tmp;
            break;
        }
    }
    assertNotNull("Could not find a suitable certificate to revoke.", cert);

    //----------- creating the revocation signed request-------------------
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage revMsg = genRevReq(this.issuerDN, SUBJECT_DN, CertTools.getSerialNumber(cert), this.cacert,
            nonce, transid, false, pAlg, new DEROctetString(nonce));
    assertNotNull("Generating CrmfRequest failed." + revMsg);

    String adminName = "cmpTestAdmin";
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE");
    Certificate admCert = getCertFromCredentials(adminToken);
    CMPCertificate[] cmpcert = getCMPCert(admCert);
    revMsg = CmpMessageHelper.buildCertBasedPKIProtection(revMsg, cmpcert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(revMsg);

    //----------------- Creating the nested PKIMessage -----------------------
    String reqSubjectDN = "CN=bogusSubjectNested";
    final byte[] reqNonce = CmpMessageHelper.createSenderNonce();
    final byte[] reqTransid = CmpMessageHelper.createSenderNonce();
    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(reqNonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(reqTransid));

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(revMsg);
    DERSequence seq = new DERSequence(v);
    PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    createRACertificate("raRevSigner", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE,
            this.caid);
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");

    assertNotNull("Failed to create myPKIHeader", myPKIHeader);
    assertNotNull("myPKIBody is null", myPKIBody);
    assertNotNull("myPKIMessage is null", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert, nonce, transid, false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    int revStatus = checkRevokeStatus(this.issuerDN, CertTools.getSerialNumber(cert));
    assertNotEquals("Revocation request failed to revoke the certificate",
            Integer.valueOf(RevokedCertInfo.NOT_REVOKED), Integer.valueOf(revStatus));

    removeAuthenticationToken(adminToken, admCert, adminName);
}

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

License:Open Source License

@Test
public void test04CrmfRACertExist()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {

    //------------------- Creating Certificate Request ---------------
    //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN);
    byte[] senderNonce = CmpMessageHelper.createSenderNonce();
    byte[] transactionID = CmpMessageHelper.createSenderNonce();
    Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago
    Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now
    assertNotNull(nb);// www  .  ja v  a 2s . c  o m
    assertNotNull(na);

    KeyPair keys = null;
    keys = KeyTools.genKeys("1024", "RSA");
    PKIMessage crmfReqMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID,
            false, null, nb, na, null, null, null);
    assertNotNull("Failed to create crmfMsg.", crmfReqMsg);
    PKIMessage crmfMsg = protectPKIMessage(crmfReqMsg, false, "foo123", 567);
    CertReqMessages ir = (CertReqMessages) crmfMsg.getBody().getContent();
    int reqID = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

    // ---------------- Creating the NestedMessageContent ----------------------
    X500Name reqSubjectDN = new X500Name("CN=bogusSubjectNested");
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(reqSubjectDN),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(crmfMsg);
    DERSequence seq = new DERSequence(v);
    PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    createRACertificate("raSignerTest04", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null,
            CMPTESTPROFILE, this.caid);
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null,
            "BC");

    assertNotNull("Failed to create myPKIHeader", myPKIHeader);
    assertNotNull("myPKIBody is null", myPKIBody);
    assertNotNull("myPKIMessage is null", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    //final byte[] resp = sendCmpHttp(myPKIMessage.toASN1Primitive().toASN1Object().getEncoded(), 200);
    // do not check signing if we expect a failure (sFailMessage==null)
    checkCmpResponseGeneral(resp, this.issuerDN, reqSubjectDN, this.cacert,
            crmfMsg.getHeader().getSenderNonce().getOctets(),
            crmfMsg.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    final Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqID);
    assertNotNull("CrmfRequest did not return a certificate", cert);
    assertTrue(cert instanceof X509Certificate);
    log.debug("Subject DN of created certificate: "
            + X500Name.getInstance(((X509Certificate) cert).getSubjectX500Principal().getEncoded()));

    NestedMessageContent nestedContent = new NestedMessageContent(myPKIMessage, cmpAlias,
            this.globalConfigurationSession);
    boolean ret = nestedContent.verify();
    assertTrue("The message verification failed, yet the a certificate was returned.", ret);

}

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

License:Open Source License

@Test
public void test06NotNestedMessage()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {

    ASN1EncodableVector optionaValidityV = 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());
    optionaValidityV.add(new DERTaggedObject(true, 0, nb));
    optionaValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionaValidityV));

    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    myCertTemplate.setIssuer(new X500Name(this.issuerDN));
    myCertTemplate.setSubject(SUBJECT_DN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {//from w ww. j  a  va  2 s. co m
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
        // If we did not pass any extensions as parameter, we will create some of our own, standard ones
    } finally {
        dIn.close();
    }
    final Extensions exts;
    {
        // SubjectAltName
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        // KeyUsage
        int bcku = 0;
        bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation;
        X509KeyUsage ku = new X509KeyUsage(bcku);
        bOut = new ByteArrayOutputStream();
        dOut = new DEROutputStream(bOut);
        dOut.writeObject(ku);
        byte[] value = bOut.toByteArray();
        extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value));

        // Make the complete extension package
        exts = extgen.generate();
    }
    myCertTemplate.setExtensions(exts);
    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);
    ProofOfPossession myProofOfPossession = new ProofOfPossession();
    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(SUBJECT_DN),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    PKIBody myPKIBody = new PKIBody(20, myCertReqMessages); // nestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    createRACertificate("raSignerTest06", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null,
            CMPTESTPROFILE, this.caid);
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null,
            "BC");

    assertNotNull("Failed to create PKIHeader", myPKIHeader);
    assertNotNull("Failed to create PKIBody", myPKIBody);
    assertNotNull("Failed to create PKIMessage", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    assertEquals("unknown object in getInstance: org.bouncycastle.asn1.DERSequence", errMsg);
}

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

License:Open Source License

@Test
public void test09CrmfWrongIssuerAndDoNotCheckAdmin()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {

    this.cmpConfiguration.setAuthenticationParameters(cmpAlias, "-;foo123");
    this.cmpConfiguration.setOmitVerificationsInECC(cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(this.admin, this.cmpConfiguration);

    //-----------------Creating CRMF request
    //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN);
    byte[] senderNonce = CmpMessageHelper.createSenderNonce();
    byte[] transactionID = CmpMessageHelper.createSenderNonce();
    Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago
    Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now
    assertNotNull(nb);/*from   w ww .  java 2s  .  c o m*/
    assertNotNull(na);

    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID,
            false, null, nb, na, null, pAlg, new DEROctetString(senderNonce));

    KeyPair nonAdminKeys = KeyTools.genKeys("1024", "RSA");
    Certificate nonAdminCert = CertTools.genSelfCert("CN=cmpTestAdmin,C=SE", 365, null,
            nonAdminKeys.getPrivate(), nonAdminKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA,
            false);
    CMPCertificate[] cmpcert = getCMPCert(nonAdminCert);
    crmfMsg = CmpMessageHelper.buildCertBasedPKIProtection(crmfMsg, cmpcert, nonAdminKeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(crmfMsg);
    CertReqMessages ir = (CertReqMessages) crmfMsg.getBody().getContent();
    int reqID = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

    //------------------Creating NestedMessageContent
    String reqSubjectDN = "CN=bogusSubjectNested";
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(crmfMsg);
    DERSequence seq = new DERSequence(v);
    PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent
    assertNotNull("Failed to create nested Message PKIBody", myPKIBody);

    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    assertNotNull("Failed to created nested message PKIMessage", myPKIMessage);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    createRACertificate("raCrmfSigner", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null,
            CMPTESTPROFILE, this.caid);
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");

    assertNotNull("Failed to create myPKIHeader", myPKIHeader);
    assertNotNull("myPKIBody is null", myPKIBody);
    assertNotNull("myPKIMessage is null", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    //final byte[] resp = sendCmpHttp(myPKIMessage.toASN1Primitive().toASN1Object().getEncoded(), 200);
    // do not check signing if we expect a failure (sFailMessage==null)
    checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert,
            crmfMsg.getHeader().getSenderNonce().getOctets(),
            crmfMsg.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    final Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqID);
    assertNotNull("CrmfRequest did not return a certificate", cert);
    assertTrue(cert instanceof X509Certificate);
    log.debug("Subject DN of created certificate: "
            + X500Name.getInstance(((X509Certificate) cert).getSubjectX500Principal().getEncoded()));
}

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.
 * // www  .  ja  v  a 2  s. c o 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.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);//  w ww  .j ava2  s. c o m
    return pkcs10;
}