Example usage for org.bouncycastle.asn1.x509 GeneralName GeneralName

List of usage examples for org.bouncycastle.asn1.x509 GeneralName GeneralName

Introduction

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

Prototype

public GeneralName(X500Name dirName) 

Source Link

Usage

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

License:Open Source License

@Test
public void test05CrmfRACertDoesNotExist()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, 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);/*from www  .ja va2  s .  c o m*/
    assertNotNull(na);

    KeyPair keys = null;
    keys = KeyTools.genKeys("1024", "RSA");
    PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID,
            false, null, nb, na, null, null, null);
    assertNotNull("Failed to create crmfMsg.", crmfMsg);

    // ---------------- Creating the 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()));
    // nonce
    DEROctetString dernonce = new DEROctetString(nonce);
    myPKIHeader.setSenderNonce(dernonce);
    myPKIHeader.setRecipNonce(dernonce);
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));

    PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    // Don't create a certificate, so there is no RA cert authorized on the server side.
    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);

    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("Wrong error message",
            "Could not verify the RA, signature verification on NestedMessageContent failed.", errMsg);

    NestedMessageContent nestedContent = new NestedMessageContent(myPKIMessage, cmpAlias,
            this.globalConfigurationSession);
    boolean ret = nestedContent.verify();
    assertFalse("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 {//w  ww.  jav a  2  s . c om
        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 test07ExpiredRACert()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {
    log.info(">test07ExpiredRACert()");

    //------------------- 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);/*  ww  w .  j a v a2s.co  m*/
    assertNotNull(na);

    KeyPair keys = null;
    keys = KeyTools.genKeys("1024", "RSA");
    PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID,
            false, null, nb, na, null, null, null);
    assertNotNull("Failed to create crmfMsg.", crmfMsg);

    // ---------------- Creating the NestedMessageContent ----------------------

    final 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));
    myPKIHeader.setRecipNonce(new DEROctetString(nonce));

    PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");

    long nbTime = (new Date()).getTime() - 1000000L;
    createRACertificate("raExpiredSignerTest07", "foo123", this.raCertsPath, cmpAlias, raKeys, new Date(nbTime),
            new Date(), CMPTESTPROFILE, this.caid);
    Thread.sleep(5000);
    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,
            myPKIMessage.getHeader().getSenderNonce().getOctets(),
            myPKIMessage.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    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("Wrong error message",
            "Could not verify the RA, signature verification on NestedMessageContent failed.", errMsg);
    log.info("<test07ExpiredRACert()");
}

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

License:Open Source License

@Test
public void test08MissingSignature()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {
    log.info(">test07ExpiredRACert()");

    //------------------- Creating Certificate Request ---------------
    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);/*  ww w .j  a  v  a2s  .co m*/
    assertNotNull(na);

    KeyPair keys = null;
    keys = KeyTools.genKeys("1024", "RSA");
    PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID,
            false, null, nb, na, null, null, null);
    assertNotNull("Failed to create crmfMsg.", crmfMsg);

    // ---------------- Creating the NestedMessageContent ----------------------

    final 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));
    myPKIHeader.setRecipNonce(new DEROctetString(nonce));

    PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    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,
            myPKIMessage.getHeader().getSenderNonce().getOctets(),
            myPKIMessage.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    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("Wrong error message",
            "Could not verify the RA, signature verification on NestedMessageContent failed.", errMsg);
    log.info("<test07ExpiredRACert()");
}

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);/* w  ww  .  j  av  a 2s .c  om*/
    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.ws.client.NestedCrmfRequestMissingStoredCertTestCommand.java

License:Open Source License

/**
 * Runs the command//from w  w  w.j a va 2  s  .  c  o m
 *
 * @throws IllegalAdminCommandException Error in command args
 * @throws ErrorAdminCommandException Error running command
 */
public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {

    try {

        CertRequest certReq = genCertReq(userDN, null);

        PKIMessage certMsg = genPKIMessage(false, certReq);
        if (certMsg == null) {
            getPrintStream().println("No certificate request.");
            System.exit(-1);
        }
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        certMsg.getHeader().setProtectionAlg(pAlg);
        certMsg.getHeader().setSenderKID(new DEROctetString("EMPTY".getBytes()));
        PKIMessage signedMsg = signPKIMessage(certMsg, innerSignKey);
        addExtraCert(signedMsg, innerCertificate);
        if (signedMsg == null) {
            getPrintStream().println("No protected message.");
            System.exit(-1);
        }

        PKIHeader myPKIHeader = new PKIHeader(new DERInteger(2),
                new GeneralName(new X509Name("CN=CMSSender,C=SE")),
                new GeneralName(new X509Name(((X509Certificate) cacert).getSubjectDN().getName())));
        myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
        // senderNonce
        myPKIHeader.setSenderNonce(new DEROctetString(nonce));
        // TransactionId
        myPKIHeader.setTransactionID(new DEROctetString(nonce));
        //myPKIHeader.addGeneralInfo(new InfoTypeAndValue(ASN1Sequence.getInstance(crmfMsg)));
        byte[] recipNonce = new byte[16];
        random.nextBytes(recipNonce);
        myPKIHeader.setRecipNonce(new DEROctetString(recipNonce));

        PKIBody myPKIBody = new PKIBody(signedMsg, 20); // NestedMessageContent
        PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody);
        KeyPair signkeys = KeyTools.genKeys("1024", "RSA");
        PKIMessage cmsMessage = signPKIMessage(myPKIMessage, signkeys.getPrivate());

        reqId = signedMsg.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(cmsMessage);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmp(ba);
        if (resp == null || resp.length <= 0) {
            getPrintStream().println("No response message.");
            System.exit(-1);
        }

        PKIMessage respObject = PKIMessage
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(resp)).readObject());
        if (respObject == null) {
            getPrintStream().println("No response message object could be optained");
            System.exit(-1);
        }

        PKIBody body = respObject.getBody();
        if (body.getTagNo() != 23) {
            getPrintStream().println("Expected tagnr 23, but found " + body.getTagNo());
            System.exit(-1);
        }
        getPrintStream().println("Response tagnr checked 23 ok");
        getPrintStream()
                .println("FailInfo error code: " + body.getError().getPKIStatus().getFailInfo().getPadBits());
        getPrintStream().println(
                "Error Message: " + body.getError().getPKIStatus().getStatusString().getString(0).getString());

    } catch (IOException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidKeyException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (SignatureException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchProviderException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (CertificateEncodingException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    }

    getPrintStream().println("Test successfull");
}

From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java

License:Open Source License

/**
 * Runs the command/* ww  w . j  av  a  2 s  .  c o m*/
 *
 * @throws IllegalAdminCommandException Error in command args
 * @throws ErrorAdminCommandException Error running command
 */
public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {

    try {

        CertRequest certReq = genCertReq(userDN, null);

        PKIMessage certMsg = genPKIMessage(false, certReq);
        if (certMsg == null) {
            getPrintStream().println("No certificate request.");
            System.exit(-1);
        }
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption);
        certMsg.getHeader().setProtectionAlg(pAlg);
        certMsg.getHeader().setSenderKID(new DEROctetString("CMPEnduser".getBytes()));
        PKIMessage signedMsg = signPKIMessage(certMsg, innerSignKey);
        addExtraCert(signedMsg, innerCertificate);
        if (signedMsg == null) {
            getPrintStream().println("No protected message.");
            System.exit(-1);
        }

        PKIHeader myPKIHeader = new PKIHeader(new DERInteger(2),
                new GeneralName(new X509Name("CN=CMSSender,C=SE")),
                new GeneralName(new X509Name(((X509Certificate) cacert).getSubjectDN().getName())));
        myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
        // senderNonce
        myPKIHeader.setSenderNonce(new DEROctetString(nonce));
        // TransactionId
        myPKIHeader.setTransactionID(new DEROctetString(nonce));
        //myPKIHeader.addGeneralInfo(new InfoTypeAndValue(ASN1Sequence.getInstance(crmfMsg)));

        PKIBody myPKIBody = new PKIBody(signedMsg, 20); // NestedMessageContent
        PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody);
        PKIMessage cmsMessage = signPKIMessage(myPKIMessage, outerSignKey);

        reqId = signedMsg.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(cmsMessage);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmp(ba);
        if (resp == null || resp.length <= 0) {
            getPrintStream().println("No response message.");
            System.exit(-1);
        }
        /*
        if ( !checkCmpResponseGeneral(resp, true) ) {
           System.exit(-1);
        }
        */
        final X509Certificate cert = checkCmpCertRepMessage(resp, reqId);
        if (cert == null) {
            getPrintStream().println("No certificate was created.");
            System.exit(-1);
        }
        getPrintStream().println("Certificate for " + userDN + " was created with the serialnumber: "
                + cert.getSerialNumber().toString());

        if (createsCertsPath != null) {
            String filename = CertTools.getPartFromDN(cert.getSubjectDN().toString(), "CN") + ".pem";
            writeCertificate(cert, createsCertsPath, filename);
            getPrintStream().println("Certificate was written to: " + createsCertsPath + "/" + filename);
        }

    } catch (IOException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidKeyException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (SignatureException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchProviderException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (CertificateEncodingException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    }
    getPrintStream().println("Test successfull");
}

From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestWrongSignatureTestCommand.java

License:Open Source License

/**
 * Runs the command/*from   w w w  .  ja  v a2  s .c o  m*/
 *
 * @throws IllegalAdminCommandException Error in command args
 * @throws ErrorAdminCommandException Error running command
 */
public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {

    try {

        CertRequest certReq = genCertReq(userDN, null);

        PKIMessage certMsg = genPKIMessage(false, certReq);
        if (certMsg == null) {
            getPrintStream().println("No certificate request.");
            System.exit(-1);
        }
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        certMsg.getHeader().setProtectionAlg(pAlg);
        certMsg.getHeader().setSenderKID(new DEROctetString("EMPTY".getBytes()));
        PKIMessage signedMsg = signPKIMessage(certMsg, innerSignKey);
        addExtraCert(signedMsg, innerCertificate);
        if (signedMsg == null) {
            getPrintStream().println("No protected message.");
            System.exit(-1);
        }

        PKIHeader myPKIHeader = new PKIHeader(new DERInteger(2),
                new GeneralName(new X509Name("CN=CMSSender,C=SE")),
                new GeneralName(new X509Name(((X509Certificate) cacert).getSubjectDN().getName())));
        myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
        // senderNonce
        myPKIHeader.setSenderNonce(new DEROctetString(nonce));
        // TransactionId
        myPKIHeader.setTransactionID(new DEROctetString(nonce));
        //myPKIHeader.addGeneralInfo(new InfoTypeAndValue(ASN1Sequence.getInstance(crmfMsg)));
        byte[] recipNonce = new byte[16];
        random.nextBytes(recipNonce);
        myPKIHeader.setRecipNonce(new DEROctetString(recipNonce));

        PKIBody myPKIBody = new PKIBody(signedMsg, 20); // NestedMessageContent
        PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody);
        PKIMessage signedCrmfMsg2 = signPKIMessage(certMsg, outerSignKey);
        myPKIMessage.setProtection(signedCrmfMsg2.getProtection());

        reqId = signedMsg.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();
        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 = sendCmp(ba);
        if (resp == null || resp.length <= 0) {
            getPrintStream().println("No response message.");
            System.exit(-1);
        }
        getPrintStream().println("Got response");
        /*
        if ( !checkCmpResponseGeneral(resp, false) ) {
           System.exit(-1);
        }
        getPrintStream().println("Response checked OK");
        */
        PKIMessage respObject = PKIMessage
                .getInstance(new ASN1InputStream(new ByteArrayInputStream(resp)).readObject());
        if (respObject == null) {
            getPrintStream().println("No response message object could be optained");
            System.exit(-1);
        }
        getPrintStream().println("Response object created OK");

        PKIBody body = respObject.getBody();

        /*
        if(body.getTagNo() == 23) {
           getPrintStream().println("Response tagnr 23 checked OK");
           getPrintStream().println("FailInfo error code: " + body.getError().getPKIStatus().getFailInfo().intValue());
           getPrintStream().println("Error Message: " + body.getError().getPKIStatus().getStatusString().getString(0).getString());             
        } else if(body.getTagNo() == 1) {
          final X509Certificate cert = checkCmpCertRepMessage(resp, reqId);
          if ( cert==null ) {
             getPrintStream().println("No certificate was created");
          } else {
             getPrintStream().println("Certificate for " + userDN + " was created with the serialnumber: " + cert.getSerialNumber().toString());
          }             
        } else {
           getPrintStream().println("Expected tagnr 23 or 1, but found " + body.getTagNo() + ". ERROR");
        }
        */

        if (body.getTagNo() != 23) {
            getPrintStream().println("Expected tagnr 23 or 1. Found tagnr " + body.getTagNo() + ".");
            if (body.getTagNo() == 1) {

                final X509Certificate cert = checkCmpCertRepMessage(resp, reqId);
                if (cert == null) {
                    getPrintStream().println("No certificate was created");
                } else {
                    getPrintStream().println("Certificate for " + userDN
                            + " was created with the serialnumber: " + cert.getSerialNumber().toString());
                }
            }
        } else {
            getPrintStream().println("Response tagnr 23 checked OK");
            getPrintStream().println(
                    "FailInfo error code: " + body.getError().getPKIStatus().getFailInfo().getPadBits());
            getPrintStream().println("Error Message: "
                    + body.getError().getPKIStatus().getStatusString().getString(0).getString());
        }

    } catch (IOException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidKeyException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (SignatureException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (NoSuchProviderException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (CertificateEncodingException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace(getPrintStream());
        System.exit(-1);
    }

    getPrintStream().println("Test successfull");
}

From source file:org.ejbca.extra.caservice.processor.CertificateRequestRequestProcessor.java

License:Open Source License

/**
 * Extracts the certificate signing request type and requests a new certificate using the provided credentials.
 */// w  ww  .j  av a  2  s  .co m
private CertificateRequestResponse processCertificateRequestRequest(Admin admin,
        CertificateRequestRequest submessage) {
    if (log.isDebugEnabled()) {
        log.debug("Processing CertificateRequestRequest");
    }
    try {
        byte[] result = null;
        if (submessage.createOrEditUser()) {
            if (log.isDebugEnabled()) {
                log.debug("createOrEditUser == true, will use one-shot request processing.");
            }
            final UserDataVO userdatavo = getUserDataVO(admin, submessage);
            final String requestData = new String(submessage.getRequestData());
            final int requestTypeInt = submessage.getRequestType();
            final int responseTypeInt = submessage.getResponseType();

            final String hardTokenSN = null;
            result = certificateRequestSession.processCertReq(admin, userdatavo, requestData, requestTypeInt,
                    hardTokenSN, responseTypeInt);
        } else {
            switch (submessage.getRequestType()) {
            case CertificateRequestRequest.REQUEST_TYPE_PKCS10:
                Certificate cert = null;
                PKCS10RequestMessage req = RequestMessageUtils
                        .genPKCS10RequestMessage(submessage.getRequestData());
                req.setUsername(submessage.getUsername());
                req.setPassword(submessage.getPassword());
                IResponseMessage resp = signSession.createCertificate(admin, req, X509ResponseMessage.class,
                        null);
                cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
                if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_CERTIFICATE) {
                    result = cert.getEncoded();
                } else {
                    result = signSession.createPKCS7(admin, cert, true);
                }
                break;
            case CertificateRequestRequest.REQUEST_TYPE_SPKAC:
                ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(submessage.getRequestData()));
                ASN1Sequence spkac = (ASN1Sequence) in.readObject();
                in.close();
                NetscapeCertRequest nscr = new NetscapeCertRequest(spkac);
                cert = signSession.createCertificate(admin, submessage.getUsername(), submessage.getPassword(),
                        nscr.getPublicKey());
                if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_CERTIFICATE) {
                    result = cert.getEncoded();
                } else if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_PKCS7) {
                    result = signSession.createPKCS7(admin, cert, true);
                } else if (submessage
                        .getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_PKCS7WITHCHAIN) {
                    // Read certificate chain
                    ArrayList<Certificate> certList = new ArrayList<Certificate>();
                    certList.add(cert);
                    certList.addAll(
                            caSession.getCA(Admin.getInternalAdmin(), CertTools.getIssuerDN(cert).hashCode())
                                    .getCertificateChain());
                    // Create large certificate-only PKCS7
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    CertPath certPath = cf
                            .generateCertPath(new ByteArrayInputStream(CertTools.getPEMFromCerts(certList)));
                    result = certPath.getEncoded("PKCS7");
                } else {
                    return new CertificateRequestResponse(submessage.getRequestId(), false,
                            MSG_UNSUPPORTED_RESPONSE_TYPE, null, null);
                }
                break;
            case CertificateRequestRequest.REQUEST_TYPE_CRMF:
                // Extract request in a format that EJBCA can process
                CertReqMessages certReqMessages = CertReqMessages
                        .getInstance(new ASN1InputStream(submessage.getRequestData()).readObject());
                PKIMessage msg = new PKIMessage(new PKIHeader(new DERInteger(2),
                        new GeneralName(new X509Name("CN=unused")), new GeneralName(new X509Name("CN=unused"))),
                        new PKIBody(certReqMessages, 2)); // [2] CertReqMessages --Certification Request
                CrmfRequestMessage crmfReq = new CrmfRequestMessage(msg, null, true, null);
                crmfReq.setUsername(submessage.getUsername());
                crmfReq.setPassword(submessage.getPassword());
                // Request and extract certificate from response
                IResponseMessage response = signSession.createCertificate(admin, crmfReq,
                        org.ejbca.core.protocol.cmp.CmpResponseMessage.class, null);
                ASN1InputStream ais = new ASN1InputStream(
                        new ByteArrayInputStream(response.getResponseMessage()));
                CertRepMessage certRepMessage = PKIMessage.getInstance(ais.readObject()).getBody().getCp();
                InputStream inStream = new ByteArrayInputStream(certRepMessage.getResponse(0)
                        .getCertifiedKeyPair().getCertOrEncCert().getCertificate().getEncoded());
                cert = CertificateFactory.getInstance("X.509").generateCertificate(inStream);
                inStream.close();
                // Convert to the right response type
                if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_CERTIFICATE) {
                    result = cert.getEncoded();
                } else if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_PKCS7) {
                    result = signSession.createPKCS7(admin, cert, false);
                } else if (submessage
                        .getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_PKCS7WITHCHAIN) {
                    // Read certificate chain
                    ArrayList<Certificate> certList = new ArrayList<Certificate>();
                    certList.add(cert);
                    certList.addAll(
                            caSession.getCA(Admin.getInternalAdmin(), CertTools.getIssuerDN(cert).hashCode())
                                    .getCertificateChain());
                    // Create large certificate-only PKCS7
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    CertPath certPath = cf
                            .generateCertPath(new ByteArrayInputStream(CertTools.getPEMFromCerts(certList)));
                    result = certPath.getEncoded("PKCS7");
                } else {
                    return new CertificateRequestResponse(submessage.getRequestId(), false,
                            MSG_UNSUPPORTED_RESPONSE_TYPE, null, null);
                }
                break;
            default:
                return new CertificateRequestResponse(submessage.getRequestId(), false,
                        MSG_UNSUPPORTED_REQUEST_TYPE, null, null);
            }
        }

        // Return the response when we have response data (byte[])
        return new CertificateRequestResponse(submessage.getRequestId(), true, null,
                submessage.getResponseType(), result);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("External RA request generated an error: " + e.getMessage());
        }
        return new CertificateRequestResponse(submessage.getRequestId(), false, "Error " + e.getMessage(), null,
                null);
    }
}

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);
    }//ww w .  j av  a  2s. co 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;
}