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

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

Introduction

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

Prototype

ASN1ObjectIdentifier SERIALNUMBER

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

Click Source Link

Document

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

Usage

From source file:ee.ria.xroad.common.util.CertUtils.java

License:Open Source License

/**
 * @param cert certificate from which to get the subject serial number
 * @return the SerialNumber component of the Subject field.
 *///from w  w w  . j a v a2  s .  c om
public static String getSubjectSerialNumber(X509Certificate cert) {
    X500Principal principal = cert.getSubjectX500Principal();
    X500Name x500name = new X500Name(principal.getName());

    return getRDNValue(x500name, BCStyle.SERIALNUMBER);
}

From source file:ee.ria.xroad.common.util.FISubjectClientIdDecoder.java

License:Open Source License

/**
 * @param cert certificate from which to construct the client ID
 * @return a fully constructed Client identifier from DN of the certificate.
 *///w w w.  j av  a2s. c om
public static ClientId getSubjectClientId(X509Certificate cert) {
    X500Principal principal = cert.getSubjectX500Principal();
    X500Name x500name = new X500Name(principal.getName());

    if (getRDNValue(x500name, BCStyle.SERIALNUMBER) == null) {
        if (getRDNValue(x500name, BCStyle.OU) == null) {
            return CertUtils.getSubjectClientId(cert);
        }
        return parseClientIdFromLegacyName(x500name);
    }
    return parseClientId(x500name);
}

From source file:ee.ria.xroad.common.util.FISubjectClientIdDecoder.java

License:Open Source License

private static ClientId parseClientId(X500Name x500name) {
    String c = getRDNValue(x500name, BCStyle.C);
    if (!"FI".equals(c)) {
        throw new CodedException(ErrorCodes.X_INCORRECT_CERTIFICATE,
                "Certificate subject name does not contain valid country code");
    }//from w  w w.ja v  a2 s  .  c om

    if (getRDNValue(x500name, BCStyle.O) == null) {
        throw new CodedException(ErrorCodes.X_INCORRECT_CERTIFICATE,
                "Certificate subject name does not contain organization");
    }

    String memberCode = getRDNValue(x500name, BCStyle.CN);
    if (memberCode == null) {
        throw new CodedException(ErrorCodes.X_INCORRECT_CERTIFICATE,
                "Certificate subject name does not contain common name");
    }

    String serialNumber = getRDNValue(x500name, BCStyle.SERIALNUMBER);
    if (serialNumber == null) {
        throw new CodedException(ErrorCodes.X_INCORRECT_CERTIFICATE,
                "Certificate subject name does not contain serial number");
    }

    final String[] components = SPLIT_PATTERN.split(serialNumber);
    if (components.length != NUM_COMPONENTS) {
        throw new CodedException(ErrorCodes.X_INCORRECT_CERTIFICATE,
                "Certificate subject name's attribute serialNumber has invalid value");
    }

    // Note. components[1] = serverCode, unused
    return ClientId.create(components[0], // instanceId
            components[2], // memberClass
            memberCode);

}

From source file:ee.ria.xroad.common.util.SkCprKlass3.java

License:Open Source License

static String[] getSubjectIdentifier(X500Name x500name) throws Exception {
    String sn = CertUtils.getRDNValue(x500name, BCStyle.SERIALNUMBER);
    if (sn == null) {
        throw new Exception("Subject name does not contain serial number");
    }//from w  ww  .  java  2s .c o  m

    if (sn.length() != SN_LENGTH) {
        throw new Exception("Serial number length must be " + SN_LENGTH);
    }

    return new String[] { getMemberClass(sn), sn };
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509ResourceCertificateParser.java

License:BSD License

public boolean mayHaveOneValidSerialNumber(X500Name principal) {
    RDN[] serialNumbers = principal.getRDNs(BCStyle.SERIALNUMBER);
    return serialNumbers.length <= 1;
}

From source file:org.cesecore.certificates.util.DnComponentsTest.java

License:Open Source License

@Test
public void test02() {
    String dn = CertTools.stringToBCDNString("uri=fff,CN=oid,SN=12345,NAME=name,C=se");
    final X500Name name = CertTools.stringToBcX500Name(dn);
    ASN1ObjectIdentifier[] oids = name.getAttributeTypes();
    assertEquals(BCStyle.CN, oids[0]);/*www.  j av  a2s  . c o m*/
    assertEquals(BCStyle.NAME, oids[1]);
    assertEquals(BCStyle.SERIALNUMBER, oids[2]);
    assertEquals(BCStyle.C, oids[3]);
    assertEquals("CN=oid,Name=name,SN=12345,C=se", dn);

    String dn1 = CertTools.stringToBCDNString("SURNAME=Json,=fff,CN=oid,SN=12345,NAME=name,C=se");
    final X500Name name1 = CertTools.stringToBcX500Name(dn1);
    ASN1ObjectIdentifier[] oids1 = name1.getAttributeTypes();
    assertEquals(BCStyle.CN, oids1[0]);
    assertEquals(BCStyle.NAME, oids1[1]);
    assertEquals(BCStyle.SERIALNUMBER, oids1[2]);
    assertEquals(BCStyle.SURNAME, oids1[3]);
    assertEquals(BCStyle.C, oids1[4]);
    assertEquals("CN=oid,Name=name,SN=12345,SURNAME=Json,C=se", dn1);

    String dn2 = CertTools.stringToBCDNString(
            "jurisdictionCountry=SE,jurisdictionState=Stockholm,SURNAME=Json,=fff,CN=oid,jurisdictionLocality=Solna,SN=12345,unstructuredname=foo.bar.com,unstructuredaddress=1.2.3.4,NAME=name,C=se");
    final X500Name name2 = CertTools.stringToBcX500Name(dn2);
    ASN1ObjectIdentifier[] oids2 = name2.getAttributeTypes();
    assertEquals(CeSecoreNameStyle.JURISDICTION_COUNTRY, oids2[0]);
    assertEquals(CeSecoreNameStyle.JURISDICTION_STATE, oids2[1]);
    assertEquals(CeSecoreNameStyle.JURISDICTION_LOCALITY, oids2[2]);
    assertEquals(CeSecoreNameStyle.UnstructuredAddress, oids2[3]);
    assertEquals(CeSecoreNameStyle.UnstructuredName, oids2[4]);
    assertEquals(BCStyle.CN, oids2[5]);
    assertEquals(BCStyle.NAME, oids2[6]);
    assertEquals(BCStyle.SERIALNUMBER, oids2[7]);
    assertEquals(BCStyle.SURNAME, oids2[8]);
    assertEquals(BCStyle.C, oids2[9]);
    assertEquals(
            "JurisdictionCountry=SE,JurisdictionState=Stockholm,JurisdictionLocality=Solna,unstructuredAddress=1.2.3.4,unstructuredName=foo.bar.com,CN=oid,Name=name,SN=12345,SURNAME=Json,C=se",
            dn2);

}

From source file:org.poreid.verify.sod.Validator.java

License:Open Source License

private String getCivilianIdNumber(X509Certificate certificate) throws InvalidNameException {
    String serialNumber = BCStyle.INSTANCE.oidToDisplayName(BCStyle.SERIALNUMBER);
    Map<String, String> oidMap = new HashMap<>();

    oidMap.put(BCStyle.SERIALNUMBER.getId(), serialNumber);
    String subjectName = certificate.getSubjectX500Principal().getName(X500Principal.RFC2253, oidMap);

    for (Rdn rdn : new LdapName(subjectName).getRdns()) {
        if (serialNumber.equalsIgnoreCase(rdn.getType())) {
            return rdn.getValue().toString().toLowerCase().replace(BI, "");
        }/*from  w w  w.  jav  a 2 s.  c  o m*/
    }

    return "";
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

License:Open Source License

    public X509Certificate generateCertificateFromCSR(PrivateKey privateKey,
                                                      PKCS10CertificationRequest request,
                                                      String issueSubject)
            throws KeystoreException {

        CommonUtil commonUtil = new CommonUtil();
        Date validityBeginDate = commonUtil.getValidityStartDate();
        Date validityEndDate = commonUtil.getValidityEndDate();

        X500Name certSubject = new X500Name(CertificateManagementConstants.DEFAULT_PRINCIPAL);
        //X500Name certSubject = request.getSubject();

        Attribute attributes[] = request.getAttributes();

//        if (certSubject == null) {
//            certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
//        } else {
//            org.bouncycastle.asn1.x500.RDN[] rdn = certSubject.getRDNs();
///* ww w  .  j  a  va2s  .c  o m*/
//            if (rdn == null || rdn.length == 0) {
//                certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
//            }
//        }


        RDN[] certUniqueIdRDN;
        BigInteger certUniqueIdentifier;

        // IMPORTANT: "Serial-Number" of the certificate used when creating it, is set as its "Alias" to save to
        // keystore.
        if (request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER).length != 0) {
            // if certificate attribute "UNIQUE_IDENTIFIER" exists use its hash as the "Serial-Number" for the
            // certificate.
            certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER);
            certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode());

        } else if (request.getSubject().getRDNs(BCStyle.SERIALNUMBER).length != 0) {
            // else if certificate attribute "SERIAL_NUMBER" exists use its hash as the "Serial-Number" for the
            // certificate.
            certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.SERIALNUMBER);
            certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode());

        } else {
            // else get the BigInteger Value of the integer that is the current system-time in millis as the
            // "Serial-Number".
            certUniqueIdentifier = CommonUtil.generateSerialNumber();
        }

        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
                new X500Name(issueSubject), certUniqueIdentifier, validityBeginDate, validityEndDate, certSubject,
                request.getSubjectPublicKeyInfo());

        ContentSigner sigGen;
        X509Certificate issuedCert;

        try {
            certificateBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(
                    KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

            if (attributes != null) {
                ASN1Encodable extractedValue = getChallengePassword(attributes);

                if (extractedValue != null) {
                    certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, true,
                                                    extractedValue);
                }
            }

            sigGen = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA)
                    .setProvider(CertificateManagementConstants.PROVIDER).build(privateKey);
            issuedCert = new JcaX509CertificateConverter().setProvider(
                    CertificateManagementConstants.PROVIDER).getCertificate(
                    certificateBuilder.build(sigGen));
            org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate =
                    new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
            List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
            certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
            certificate.setCertificate(issuedCert);
            certificates.add(certificate);
            saveCertInKeyStore(certificates);
        } catch (CertIOException e) {
            String errorMsg = "Certificate Input output issue occurred when generating generateCertificateFromCSR";
            throw new KeystoreException(errorMsg, e);
        } catch (OperatorCreationException e) {
            String errorMsg = "Operator creation issue occurred when generating generateCertificateFromCSR";
            throw new KeystoreException(errorMsg, e);
        } catch (CertificateException e) {
            String errorMsg = "Certificate issue occurred when generating generateCertificateFromCSR";
            throw new KeystoreException(errorMsg, e);
        }

        return issuedCert;
    }

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager.java

License:Open Source License

/**
 * This method creates the PKCS10 Certificate Sign Request which is to be sent to the SCEP Server using the
 * generated PublicKey of the client. The certificate parameters used here are the ones from the AgentManager
 * which are the values read from the configurations file.
 *
 * @return the PKCS10CertificationRequest object created using the client specific configs and the generated
 * PublicKey//w w w  . java  2s  . c  om
 * @throws AgentCoreOperationException if an error occurs when creating a content signer to sign the CSR.
 */
private PKCS10CertificationRequest generateCertSignRequest() throws AgentCoreOperationException {
    // Build the CN for the cert that's being requested.
    X500NameBuilder nameBld = new X500NameBuilder(BCStyle.INSTANCE);
    nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getTenantDomain());
    nameBld.addRDN(BCStyle.O, AgentManager.getInstance().getAgentConfigs().getDeviceOwner());
    nameBld.addRDN(BCStyle.OU, AgentManager.getInstance().getAgentConfigs().getDeviceOwner());
    nameBld.addRDN(BCStyle.UNIQUE_IDENTIFIER, AgentManager.getInstance().getAgentConfigs().getDeviceId());
    nameBld.addRDN(BCStyle.SERIALNUMBER, AgentManager.getInstance().getAgentConfigs().getDeviceId());
    X500Name principal = nameBld.build();

    JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(SIGNATURE_ALG)
            .setProvider(PROVIDER);
    ContentSigner contentSigner;

    try {
        contentSigner = contentSignerBuilder.build(this.privateKey);
    } catch (OperatorCreationException e) {
        String errorMsg = "Could not create content signer with private key.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    // Generate the certificate signing request (csr = PKCS10)
    PKCS10CertificationRequestBuilder reqBuilder = new JcaPKCS10CertificationRequestBuilder(principal,
            this.publicKey);
    return reqBuilder.build(contentSigner);
}