Example usage for org.bouncycastle.asn1.x500.style BCStyle SN

List of usage examples for org.bouncycastle.asn1.x500.style BCStyle SN

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x500.style BCStyle SN.

Prototype

ASN1ObjectIdentifier SN

To view the source code for org.bouncycastle.asn1.x500.style BCStyle SN.

Click Source Link

Document

device serial number name - StringType(SIZE(1..64))

Usage

From source file:ca.trustpoint.m2m.M2mTrustAnchor.java

License:Apache License

/**
 * Creates a new instance.//  w  ww  .  j a  v  a2  s  . co m
 *
 * @param x509Certificate X.509 certificate to use as trust anchor.
 * @throws IllegalArgumentException if x509Certificate is null.
 */
public M2mTrustAnchor(X509Certificate x509Certificate) throws IllegalArgumentException {
    if (x509Certificate == null) {
        throw new IllegalArgumentException("x509Certificate cannot be null.");
    }

    X500Name x500Name = JcaX500NameUtil.getSubject(x509Certificate);
    EntityName caName = new EntityName();
    int attributeCount = 0;

    for (RDN rdn : x500Name.getRDNs()) {
        AttributeTypeAndValue attr = rdn.getFirst();
        EntityNameAttributeId attributeId;

        if (BCStyle.C.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.Country;
        } else if (BCStyle.O.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.Organization;
        } else if (BCStyle.OU.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.OrganizationalUnit;
        } else if (BCStyle.DN_QUALIFIER.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.DistinguishedNameQualifier;
        } else if (BCStyle.ST.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.StateOrProvince;
        } else if (BCStyle.L.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.Locality;
        } else if (BCStyle.CN.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.CommonName;
        } else if (BCStyle.SN.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.SerialNumber;
        } else if (BCStyle.DC.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.DomainComponent;
        } else {
            // Unsupported attribute.
            continue;
        }

        caName.addAttribute(new EntityNameAttribute(attributeId, IETFUtils.valueToString(attr.getValue())));
        attributeCount++;

        if (attributeCount == EntityName.MAXIMUM_ATTRIBUTES) {
            // We have reached the maximum number of attributes for an EntityName, so stop here.
            break;
        }
    }

    this.caName = caName;
    this.publicKey = x509Certificate.getPublicKey();
    certificate = null;
}

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

License:Open Source License

@Override
protected void checkDN(X500Name expected, X500Name actual) {
    final ASN1ObjectIdentifier[] expectedOIDs = expected.getAttributeTypes();
    final ASN1ObjectIdentifier[] actualOIDs = actual.getAttributeTypes();
    assertEquals("Not the expected number of elements in the created certificate.", expectedOIDs.length,
            actualOIDs.length);//from   ww  w  .  j av  a  2s.  co m
    String expectedValue, actualValue;
    for (int i = 0; i < expectedOIDs.length; i++) {
        final ASN1ObjectIdentifier oid = expectedOIDs[i];
        expectedValue = expected.getRDNs(oid)[0].getFirst().getValue().toString();
        actualValue = actual.getRDNs(oid)[0].getFirst().getValue().toString();
        if (!oid.equals(BCStyle.SN)) {
            log.debug("Check that " + oid.getId() + " is OK. Expected '" + expectedValue + "'. Actual '"
                    + actualValue + "'.");
            assertEquals("Not expected " + oid, expectedValue, actualValue);
            continue;
        }
        log.debug("Special handling of the SN " + oid.getId() + ". Input '" + expectedValue + "'. Transformed '"
                + actualValue + "'.");
        final String expectedSNPrefix = UNIDPREFIX + LRA;
        final String actualSNPrefix = actualValue.substring(0, expectedSNPrefix.length());
        assertEquals("New serial number prefix not as expected.", expectedSNPrefix, actualSNPrefix);
        final String actualSNRandom = actualValue.substring(expectedSNPrefix.length());
        assertTrue("Random in serial number not OK: " + actualSNRandom,
                Pattern.compile("^\\w{6}$").matcher(actualSNRandom).matches());
    }
}

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

License:Open Source License

private void doTest(Connection dbConn) throws Exception {

    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;
    final String unid;
    {//from w ww.j  a  v a2s.c o  m
        // In this test SUBJECT_DN contains special, escaped characters to verify
        // that that works with CMP RA as well
        final PKIMessage one = genCertReq(CmpRAUnidTest.issuerDN, SUBJECT_DN, this.keys, this.cacert, nonce,
                transid, true, null, null, null, null, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, CPNAME, 567);
        assertNotNull(req);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        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, configAlias);

        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            PKIBody body = respObject.getBody();
            if (body.getContent() instanceof ErrorMsgContent) {
                ErrorMsgContent err = (ErrorMsgContent) body.getContent();
                String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                log.error(errMsg);
                fail("CMP ErrorMsg received: " + errMsg);
                unid = null;
            } else {
                checkCmpResponseGeneral(resp, CmpRAUnidTest.issuerDN, SUBJECT_DN, this.cacert, nonce, transid,
                        false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
                final X509Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqId);
                final X500Name name = X500Name.getInstance(cert.getSubjectX500Principal().getEncoded());
                unid = IETFUtils.valueToString(name.getRDNs(BCStyle.SN)[0].getFirst().getValue());
                log.debug("Unid received in certificate response: " + unid);
            }
        } finally {
            inputStream.close();
        }
    }
    {
        final PreparedStatement ps = dbConn.prepareStatement("select fnr from UnidFnrMapping where unid=?");
        ps.setString(1, unid);
        final ResultSet result = ps.executeQuery();
        assertTrue("Unid '" + unid + "' not found in DB.", result.next());
        final String fnr = result.getString(1);
        result.close();
        ps.close();
        log.debug("FNR read from DB: " + fnr);
        assertEquals("Right FNR not found in DB.", FNR, fnr);
    }
    {
        // Send a confirm message to the CA
        final String hash = "foo123";
        final PKIMessage confirm = genCertConfirm(SUBJECT_DN, this.cacert, nonce, transid, hash, reqId);
        assertNotNull(confirm);
        final PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, CPNAME, 567);
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req1);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, configAlias);
        checkCmpResponseGeneral(resp, CmpRAUnidTest.issuerDN, SUBJECT_DN, this.cacert, nonce, transid, false,
                PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(SUBJECT_DN, this.cacert, resp);
    }
}

From source file:org.opendaylight.snbi.southplugin.CertificateMgmt.java

License:Open Source License

public static PKCS10CertificationRequest generateCSRRequest(String name, KeyPair pair) throws Exception {
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    //        builder.addRDN(BCStyle.C, defaults.get("COUNTRY"));
    //        builder.addRDN(BCStyle.O, defaults.get("ORGANIZATION"));
    // builder.addRDN(BCStyle.ST, defaults.get("STATE"));
    // builder.addRDN(BCStyle.T, defaults.get("TITLE"));
    builder.addRDN(BCStyle.SN, BigInteger.valueOf(System.currentTimeMillis()).toString());
    builder.addRDN(BCStyle.CN, name);//from  w  w w  . j  a  va2s.  com
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(builder.build(),
            pair.getPublic());
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
            CertManagerConstants.CERT_ALGORITHM.SHA1withRSA.toString());
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    PKCS10CertificationRequest csr = p10Builder.build(signer);
    return csr;
}

From source file:org.opendaylight.snbi.southplugin.CertificateMgmt.java

License:Open Source License

public static void createCRL(String name) {
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    //        builder.addRDN(BCStyle.C, defaults.get("COUNTRY"));
    //        builder.addRDN(BCStyle.O, defaults.get("ORGANIZATION"));
    // builder.addRDN(BCStyle.ST, defaults.get("STATE"));
    // builder.addRDN(BCStyle.T, defaults.get("TITLE"));
    builder.addRDN(BCStyle.SN, BigInteger.valueOf(System.currentTimeMillis()).toString());
    builder.addRDN(BCStyle.CN, name);/*from   www.  j  a va2 s.co  m*/
    Calendar now = Calendar.getInstance();
    Date notBefore = now.getTime();
    now.add(Calendar.YEAR, 3);
    Date notAfter = now.getTime();
    X509v2CRLBuilder crlGen = new X509v2CRLBuilder(builder.build(), notBefore);
    crlGen.setNextUpdate(notAfter);
}

From source file:org.opendaylight.snbi.southplugin.SNBICAInterfaces.java

License:Open Source License

public PKCS10CertificationRequest generateCSRRequest(String... arguments) {
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.CN, arguments[0]); // common name, is the Device ID
    builder.addRDN(BCStyle.OU, arguments[1]); //  organisational unit is the Domain ID
    builder.addRDN(BCStyle.SN, arguments[2]); // serial number of the SubjectDN not the certificate Serial Number.
    // other defaults
    // builder.addRDN(BCStyle.C, CertificateMgmt.defaults.get("COUNTRY"));
    //builder.addRDN(BCStyle.ST, CertificateMgmt.defaults.get("STATE"));
    // builder.addRDN(BCStyle.T, CertificateMgmt.defaults.get("TITLE"));

    //generate key pair
    KeyPair keyPair = KeyPairMgmt.generateKeyPair(CertManagerConstants.ALGORITHM.RSA);

    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
            CertManagerConstants.CERT_ALGORITHM.SHA1withRSA.toString());
    ContentSigner signer = null;//from www.  j ava  2s. c  om
    try {
        signer = csBuilder.build(keyPair.getPrivate());
    } catch (OperatorCreationException e) {
        e.printStackTrace();
        return null;
    }
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(builder.build(),
            keyPair.getPublic());

    PKCS10CertificationRequest csr = p10Builder.build(signer);
    return csr;
}