Example usage for org.bouncycastle.asn1.x500 X500Name X500Name

List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name

Introduction

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

Prototype

public X500Name(String dirName) 

Source Link

Usage

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

License:Open Source License

@Test
public void test06CrmfEcdsaCA() throws Exception {
    try {//from  w  w w .  ja  va  2  s . co m
        createEllipticCurveDsaCa();
        CAInfo caInfo = this.caSession.getCAInfo(ADMIN, "TESTECDSA");
        this.cmpConfiguration.setRACAName(cmpAlias, "TESTECDSA");
        this.globalConfSession.saveConfiguration(ADMIN, this.cmpConfiguration);

        final String issuerDN = caInfo.getSubjectDN(); // Make sure this CA is used for the test
        final X509Certificate caCert = (X509Certificate) caInfo.getCertificateChain().iterator().next();
        final KeyPair key1 = KeyTools.genKeys("secp256r1", AlgorithmConstants.KEYALGORITHM_ECDSA);
        final String userName1 = "cmptestecdsa1";
        final X500Name userDN1 = new X500Name("C=SE,O=PrimeKey,CN=" + userName1);
        try {
            // check that we can get a certificate from this ECDSA CA.
            X509Certificate cert = crmfHttpUserTest(userDN1, key1, null, null,
                    X9ObjectIdentifiers.ecdsa_with_SHA1.getId(), caCert, issuerDN);
            assertNotNull(cert);
            // Check that this was really signed using SHA256WithECDSA and that the users key algo is in there
            assertEquals(AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA,
                    AlgorithmTools.getSignatureAlgorithm(cert));
            // Keyspec we get back from AlgorithmTools.getKeySpecification seems to differ between OracleJDK and OpenJDK so we only check key type
            assertEquals(AlgorithmConstants.KEYALGORITHM_ECDSA,
                    AlgorithmTools.getKeyAlgorithm(cert.getPublicKey()));
        } finally {
            try {
                this.endEntityManagementSession.deleteUser(ADMIN, userName1);
            } catch (NotFoundException e) {// Do nothing
            }
        }
    } finally {
        // Reset this test class as it was before this test
        this.cmpConfiguration.setRACAName(cmpAlias, "TestCA");
        this.globalConfSession.saveConfiguration(ADMIN, this.cmpConfiguration);
        removeTestCA("TESTECDSA");
    }
}

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

License:Open Source License

@Test
public void test07EscapedCharsInDN() throws Exception {

    final String username = "another\0nullguy%00<do>";
    final String sUserDN = "CN=" + username + ", C=SE";
    final X500Name userDN = new X500Name(sUserDN);

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

    final int reqId;
    try {//from   w  w w  .  j  a v  a 2  s . c  om
        final PKIMessage one = genCertReq(ISSUER_DN, userDN, keys, this.cacert, nonce, transid, true, null,
                null, null, null, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567);

        final 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();
        {// this strange DN contains forbidden characters and may not be stored a a string in the DB, so it must be transformed by ejbca.
            final CertificateProfile cp = this.certProfileSession.getCertificateProfile(this.cpDnOverrideId);
            cp.setAllowDNOverride(false);
            this.certProfileSession.changeCertificateProfile(ADMIN, CP_DN_OVERRIDE_NAME, cp);
        }
        // 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, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpCertRepMessage(new X500Name(StringTools.strip(sUserDN)), this.cacert, resp, reqId);
        {
            final CertificateProfile cp = this.certProfileSession.getCertificateProfile(this.cpDnOverrideId);
            cp.setAllowDNOverride(true);
            this.certProfileSession.changeCertificateProfile(ADMIN, CP_DN_OVERRIDE_NAME, cp);
        }
    } finally {
        String escapedName = "another/nullguy/00\\<do\\>";
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, escapedName,
                    RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED);
        } catch (NotFoundException e) {
            log.debug("Failed to delete user: " + escapedName);
        }
    }
}

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

License:Open Source License

@Test
public void test01CrmfUnknowUser() throws Exception {
    // A name that does not exis
    final X500Name dn = new X500Name("CN=abc123rry5774466, O=PrimeKey Solutions AB, C=SE");

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(issuerDN, dn, this.keys, this.cacert, nonce, transid, true, null, null, null,
            null, null, null);/*  ww  w  .  j a v  a  2 s  .  c  o m*/
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567);
    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, issuerDN, dn, this.cacert, nonce, transid, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpCertRepMessage(dn, this.cacert, resp, reqId);
}

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

License:Open Source License

@Test
public void test02CrmfOkUser() throws Exception {

    // Create a new good user
    final X500Name dn = new X500Name("C=SE,O=PrimeKey,CN=cmptest");
    createCmpUser(CMP_USERNAME, dn.toString());
    try {/*from  ww  w. ja v  a  2  s  .  c  o m*/
        byte[] nonce = CmpMessageHelper.createSenderNonce();
        byte[] transid = CmpMessageHelper.createSenderNonce();

        PKIMessage one = genCertReq(issuerDN, dn, this.keys, this.cacert, nonce, transid, true, null, null,
                null, null, null, null);
        PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        assertNotNull(req);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpTcp(ba, 5);
        checkCmpResponseGeneral(resp, issuerDN, dn, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpCertRepMessage(dn, this.cacert, resp, reqId);

        // Send a confirm message to the CA
        String hash = "foo123";
        PKIMessage confirm = genCertConfirm(dn, this.cacert, nonce, transid, hash, reqId);
        assertNotNull(confirm);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(confirm);
        ba = bao.toByteArray();
        // Send request and receive response
        resp = sendCmpTcp(ba, 5);
        checkCmpResponseGeneral(resp, issuerDN, dn, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(dn, this.cacert, resp);
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, CMP_USERNAME);
    }
}

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

License:Open Source License

/**
 * Try a request with SubjectDN email and special characters.
 * /*from w  w  w.j av a 2s . co  m*/
 * @throws Exception
 */
@Test
public void test06DnEmail() throws Exception {
    try {
        final X500Name subjectDN = new X500Name("C=SE,CN=Gran Strmfrare,E=adam@eva.se");
        // createCmpUser("cmptest2", subjectDN);

        byte[] nonce = CmpMessageHelper.createSenderNonce();
        byte[] transid = CmpMessageHelper.createSenderNonce();

        PKIMessage one = genCertReq(issuerDN, subjectDN, null, this.keys, this.cacert, nonce, transid, true,
                null, null, null, null, null, null);
        PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        assertNotNull(req);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpTcp(ba, 5);
        checkCmpResponseGeneral(resp, issuerDN, subjectDN, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpCertRepMessage(subjectDN, this.cacert, resp, reqId);

        // Send a confirm message to the CA
        String hash = "foo123";
        PKIMessage confirm = genCertConfirm(subjectDN, this.cacert, nonce, transid, hash, reqId);
        assertNotNull(confirm);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(confirm);
        ba = bao.toByteArray();
        // Send request and receive response
        resp = sendCmpTcp(ba, 5);
        checkCmpResponseGeneral(resp, issuerDN, subjectDN, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(subjectDN, this.cacert, resp);
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, "Gran Strmfrare");
    }
}

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 {//w  w w.jav  a2 s .  c  o m
        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.CrmfRequestTest.java

License:Open Source License

@Test
public void test04BlueXCrmf() throws Exception {
    log.trace(">test04BlueXCrmf");
    byte[] resp = sendCmpHttp(bluexir, 200, cmpAlias);
    assertNotNull(resp);//from  w w  w .ja  va 2 s .  co m
    checkCmpPKIErrorMessage(resp, "C=NL,O=A.E.T. Europe B.V.,OU=Development,CN=Test CA 1",
            new X500Name(new RDN[0]), PKIFailureInfo.badPOP, null); // expecting a bad_pop
    log.trace("<test04BlueXCrmf");
}

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

License:Open Source License

@Test
public void test07SignedConfirmationMessage() throws Exception {
    log.trace(">test07SignedConfirmationMessage()");
    CmpConfirmResponseMessage cmpConfRes = new CmpConfirmResponseMessage();
    cmpConfRes.setSignKeyInfo(this.testx509ca.getCertificateChain(), this.keys.getPrivate(), null);
    cmpConfRes.setSender(new GeneralName(USER_DN));
    cmpConfRes.setRecipient(new GeneralName(new X500Name("CN=cmpRecipient, O=TEST")));
    cmpConfRes.setSenderNonce("DAxFSkJDQSBTYW");
    cmpConfRes.setRecipientNonce("DAxFSkJDQSBTYY");
    cmpConfRes.setTransactionId("DAxFS");
    cmpConfRes.create();/*from  w  w  w  .j  a  v  a 2 s. c om*/
    byte[] resp = cmpConfRes.getResponseMessage();
    PKIMessage msg = PKIMessage.getInstance(ASN1Primitive.fromByteArray(resp));
    boolean veriStatus = CmpMessageHelper.verifyCertBasedPKIProtection(msg, this.keys.getPublic());
    assertTrue("Verification failed.", veriStatus);
    log.trace("<test07SignedConfirmationMessage()");
}

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

License:Open Source License

@Test
public void test09KeyIdTest() {
    log.trace(">test09KeyIdTest()");

    DEROctetString octs = new DEROctetString("foo123".getBytes());
    String keyid = CmpMessageHelper.getStringFromOctets(octs);
    assertEquals("foo123", keyid);

    PKIHeaderBuilder headerbuilder = new PKIHeaderBuilder(2, new GeneralName(new X500Name("CN=Sender")),
            new GeneralName(new X500Name("CN=Recipient")));
    headerbuilder.setSenderKID(new DEROctetString("foo123".getBytes()));
    PKIHeader header = headerbuilder.build();
    keyid = CmpMessageHelper.getStringFromOctets(header.getSenderKID());
    assertEquals("foo123", keyid);

    log.trace("<test09KeyIdTest()");
}

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

License:Open Source License

@Test
public void test10EscapedCharsInDN() throws Exception {
    log.trace(">test10EscapedCharsInDN");

    this.cmpConfiguration.setExtractUsernameComponent(cmpAlias, "DN");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // --------------- Send a CRMF request with the whole DN as username with escapable characters --------------- //
    final String sRequestName = "CN=another\0nullguy%00<do>";
    // Create a new good USER
    final X500Name requestName = createCmpUser(sRequestName, sRequestName, false);

    try {//from   w  w w.  j  a  v a  2s  .  c  o  m
        PKIMessage req = genCertReq(ISSUER_DN, requestName, this.keys, this.cacert, nonce, transid, false, null,
                null, null, null, null, null);
        assertNotNull(req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, requestName, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(new X500Name(StringTools.strip(sRequestName)),
                this.cacert, resp, reqId);
        assertNotNull(cert);

        // Now revoke the bastard!
        PKIMessage rev = genRevReq(ISSUER_DN, requestName, cert.getSerialNumber(), this.cacert, nonce, transid,
                true, null, null);
        assertNotNull(rev);
        rev = protectPKIMessage(rev, false, "foo123", 567);
        ByteArrayOutputStream baorev = new ByteArrayOutputStream();
        DEROutputStream outrev = new DEROutputStream(baorev);
        outrev.writeObject(rev);
        byte[] barev = baorev.toByteArray();
        // Send request and receive response
        resp = sendCmpHttp(barev, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, requestName, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(ISSUER_DN, CertTools.getSerialNumber(cert));
        assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
                revStatus);
    } finally {
        String escapedName = StringTools.stripUsername(sRequestName);
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, escapedName);
        } catch (NotFoundException e) {
            // A test probably failed before creating the entity
            log.debug("Failed to delete USER: " + escapedName);
        }
    }

    // --------------- Send a CRMF request with a username with escapable characters --------------- //
    final String username = "another\0nullguy%00";
    final String sDN = "CN=" + username + ", C=SE, O=hejsan";
    KeyPair key2 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    // Create a new good USER
    final X500Name dn = createCmpUser(username, sDN, false);

    try {

        PKIMessage req = genCertReq(ISSUER_DN, dn, key2, this.cacert, nonce, transid, false, null, null, null,
                null, null, null);
        assertNotNull(req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        byte[] ba = bao.toByteArray();
        // Send request and receive response
        byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, dn, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(dn, this.cacert, resp, reqId);
        assertNotNull(cert);

        // Now revoke the bastard!
        PKIMessage rev = genRevReq(ISSUER_DN, dn, cert.getSerialNumber(), this.cacert, nonce, transid, true,
                null, null);
        assertNotNull(rev);
        rev = protectPKIMessage(rev, false, "foo123", 567);
        ByteArrayOutputStream baorev = new ByteArrayOutputStream();
        DEROutputStream outrev = new DEROutputStream(baorev);
        outrev.writeObject(rev);
        byte[] barev = baorev.toByteArray();
        // Send request and receive response
        resp = sendCmpHttp(barev, 200, cmpAlias);
        checkCmpResponseGeneral(resp, ISSUER_DN, dn, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(ISSUER_DN, CertTools.getSerialNumber(cert));
        assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
                revStatus);

    } finally {
        String escapedName = StringTools.strip(username);
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, escapedName);
        } catch (NotFoundException e) {
            // A test probably failed before creating the entity
            log.debug("Failed to delete USER: " + escapedName);
        }
    }

    log.trace("<test10EscapedCharsInDN");
}