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

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

Introduction

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

Prototype

public X509Name(String dirName) 

Source Link

Document

Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or some such, converting it into an ordered set of name attributes.

Usage

From source file:gridReq.java

License:Open Source License

/**
 * Generates a encrypted private key and certificate request.
 *//*from   w  ww.j  a v  a 2  s. c o m*/
static public void genCertificateRequest(String dname, String emailAddressOfCA, String password,
        String privKeyLoc, String certLoc, String certReqLoc) throws Exception {

    String sigAlgName = "MD5WithRSA";
    String keyAlgName = "RSA";

    //CertUtil.init();

    // Generate a new key pair.
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName);
    KeyPair keyPair = keygen.genKeyPair();
    PrivateKey privKey = keyPair.getPrivate();
    PublicKey pubKey = keyPair.getPublic();

    // Generate the certificate request.        
    X509Name name = new X509Name(dname);
    DERConstructedSet derSet = new DERConstructedSet();
    PKCS10CertificationRequest request = new PKCS10CertificationRequest(sigAlgName, name, pubKey, derSet,
            privKey);

    // Save the certificate request to a .pem file.
    byte[] data = request.getEncoded();
    PrintStream ps = new PrintStream(new FileOutputStream(certReqLoc));

    // build / delimited name.        
    String certSubject = "";
    StringTokenizer tokens = new StringTokenizer(dname, ",");
    while (tokens.hasMoreTokens()) {
        certSubject = certSubject + "/" + tokens.nextToken();
    }

    ps.print("\n\n" + "Please mail the following certificate request to " + emailAddressOfCA + "\n" + "\n"
            + "==================================================================\n" + "\n"
            + "Certificate Subject:\n" + "\n" + certSubject + "\n" + "\n"
            + "The above string is known as your user certificate subject, and it \n"
            + "uniquely identifies this user.\n" + "\n"
            + "To install this user certificate, please save this e-mail message\n"
            + "into the following file.\n" + "\n" + "\n" + certLoc + "\n" + "\n" + "\n"
            + "      You need not edit this message in any way. Simply \n"
            + "      save this e-mail message to the file.\n" + "\n" + "\n"
            + "If you have any questions about the certificate contact\n" + "the Certificate Authority at "
            + emailAddressOfCA + "\n" + "\n");
    ps.print(toPEM(data));
    ps.close();

    // Save private key to a .pem file.
    OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey);
    if (password.length() != 0) {
        key.encrypt(password);
    }
    key.writeTo(new File(privKeyLoc).getAbsolutePath());
    // set read only permissions
    //Util.setFilePermissions(privKeyLoc, 600);

    // Create an empty cert file.
    File f = new File(certLoc);
    f.createNewFile();
}

From source file:android.net.http.DomainNameChecker.java

License:Apache License

/**
 * Checks the site certificate against the DNS domain name of the site being visited
 * @param certificate The certificate to check
 * @param thisDomain The DNS domain name of the site being visited
 * @return True iff if there is a domain match as specified by RFC2818
 *//*w  w  w.  ja v  a 2s  .c o  m*/
private static boolean matchDns(X509Certificate certificate, String thisDomain) {
    boolean hasDns = false;
    try {
        Collection subjectAltNames = certificate.getSubjectAlternativeNames();
        if (subjectAltNames != null) {
            Iterator i = subjectAltNames.iterator();
            while (i.hasNext()) {
                List altNameEntry = (List) (i.next());
                if (altNameEntry != null && 2 <= altNameEntry.size()) {
                    Integer altNameType = (Integer) (altNameEntry.get(0));
                    if (altNameType != null) {
                        if (altNameType.intValue() == ALT_DNS_NAME) {
                            hasDns = true;
                            String altName = (String) (altNameEntry.get(1));
                            if (altName != null) {
                                if (matchDns(thisDomain, altName)) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (CertificateParsingException e) {
        // one way we can get here is if an alternative name starts with
        // '*' character, which is contrary to one interpretation of the
        // spec (a valid DNS name must start with a letter); there is no
        // good way around this, and in order to be compatible we proceed
        // to check the common name (ie, ignore alternative names)
        if (HttpLog.LOGV) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to parse certificate";
            }

            if (HttpLog.LOGV) {
                HttpLog.v("DomainNameChecker.matchDns(): " + errorMessage);
            }
        }
    }

    if (!hasDns) {
        X509Name xName = new X509Name(certificate.getSubjectDN().getName());
        Vector val = xName.getValues();
        Vector oid = xName.getOIDs();
        for (int i = 0; i < oid.size(); i++) {
            if (oid.elementAt(i).equals(X509Name.CN)) {
                return matchDns(thisDomain, (String) (val.elementAt(i)));
            }
        }
    }

    return false;
}

From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java

License:Open Source License

public static void checkSigningCertificate(X509Certificate signingCertificate,
        SignedSignaturePropertiesType signedSignatureProperties)
        throws XAdESValidationException, CertificateEncodingException {
    CertIDListType signingCertificateCertIDList = signedSignatureProperties.getSigningCertificate();
    List<CertIDType> signingCertificateCertIDs = signingCertificateCertIDList.getCert();
    CertIDType signingCertificateCertID = signingCertificateCertIDs.get(0);
    DigestAlgAndValueType signingCertificateDigestAlgAndValue = signingCertificateCertID.getCertDigest();
    String certXmlDigestAlgo = signingCertificateDigestAlgAndValue.getDigestMethod().getAlgorithm();
    String certDigestAlgo = XAdESUtils.getDigestAlgo(certXmlDigestAlgo);
    byte[] certDigestValue = signingCertificateDigestAlgAndValue.getDigestValue();
    MessageDigest messageDigest;/*from   w  w  w .  j a v  a  2s .c om*/
    try {
        messageDigest = MessageDigest.getInstance(certDigestAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new XAdESValidationException("message digest algo error: " + e.getMessage(), e);
    }
    byte[] actualCertDigestValue = messageDigest.digest(signingCertificate.getEncoded());
    if (!Arrays.equals(actualCertDigestValue, certDigestValue)) {
        throw new XAdESValidationException(
                "XAdES signing certificate not corresponding with actual signing certificate");
    }

    X509IssuerSerialType issuerSerial = signingCertificateCertID.getIssuerSerial();
    BigInteger serialNumber = issuerSerial.getX509SerialNumber();
    if (false == signingCertificate.getSerialNumber().equals(serialNumber)) {
        throw new XAdESValidationException("xades:SigningCertificate serial number mismatch");
    }
    X509Name issuerName;
    try {
        /*issuerName = new X509Name(
              (ASN1Sequence) new ASN1InputStream(signingCertificate
             .getIssuerX500Principal().getEncoded())
             .readObject());*/
        X509Principal sprin = new X509Principal(signingCertificate.getIssuerX500Principal().getEncoded());

        //issuerName = new X509Name( signingCertificate.getIssuerX500Principal().getName(X500Principal.RFC1779) );
        issuerName = new X509Name(sprin.getName());

    } catch (IOException e) {
        throw new XAdESValidationException("error parsing xades:SigningCertificate ds:X509IssuerName: " + e);
    }
    X509Name xadesIssuerName = new X509Name(issuerSerial.getX509IssuerName());
    if (false == issuerName.equals(xadesIssuerName)) {
        throw new XAdESValidationException("xades:SigningCertificate issuer name mismatch");
    }
    LOG.debug("XAdES SigningCertificate OK");
}

From source file:be.fedict.eid.pki.ra.xkms.ws.MockXKMSWebService.java

License:Open Source License

private byte[] createCertificate(byte[] csr, ValidityIntervalType validityInterval) {
    try {/* www  .j  a  v a2  s . c  om*/
        CSRParserImpl csrParserImpl = new CSRParserImpl();
        String dn = csrParserImpl.parseCSR(csr).getSubject();

        Date startDate = validityInterval.getNotBefore().toGregorianCalendar().getTime();
        Date expiryDate = validityInterval.getNotAfter().toGregorianCalendar().getTime();
        BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());

        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
        generator.initialize(512);
        KeyPair keyPair = generator.generateKeyPair();

        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X509Name dnName = new X509Name(dn);

        certGen.setSerialNumber(serialNumber);
        certGen.setIssuerDN(dnName);
        certGen.setNotBefore(startDate);
        certGen.setNotAfter(expiryDate);
        certGen.setSubjectDN(dnName);
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA1withRSA");

        X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
        return cert.getEncoded();
    } catch (Exception e) {
        throw new RuntimeException("Error creating self-signed demo certificate", e);
    }
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.attribute.BCSigningCertificate.java

License:Open Source License

@Override
public ASN1Set getValue() {
    SigningCertificate attribute = (SigningCertificate) super.getAttribute();
    X509Certificate cert = attribute.getValue();
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_1);
    byte[] certHash = null;
    try {//  w  w  w  .  j  a va  2s  . co m
        certHash = digest.digest(cert.getEncoded());
    } catch (CertificateEncodingException ex) {
        ex.printStackTrace();
    }
    X509Name dirName = new X509Name(cert.getSubjectDN().getName());
    GeneralName name = new GeneralName(dirName);
    GeneralNames issuer = new GeneralNames(name);
    DERInteger serialNumber = new DERInteger(cert.getSerialNumber());
    IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber);
    ESSCertID essCertId = new ESSCertID(certHash, issuerSerial);
    return new DERSet(new DERSequence(
            new ASN1Encodable[] { new DERSequence(essCertId), new DERSequence(new DERNull()) }));
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.attribute.BCSigningCertificateV2.java

License:Open Source License

@Override
public ASN1Set getValue() {
    SigningCertificateV2 attribute = (SigningCertificateV2) super.getAttribute();
    X509Certificate cert = attribute.getValue();
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
    byte[] certHash = null;
    try {//from  www  .  j  a  v  a2  s. co m
        certHash = digest.digest(cert.getEncoded());
    } catch (CertificateEncodingException ex) {
        ex.printStackTrace();

    }
    X509Name dirName = new X509Name(cert.getSubjectDN().getName());
    GeneralName name = new GeneralName(dirName);
    GeneralNames issuer = new GeneralNames(name);
    DERInteger serial = new DERInteger(cert.getSerialNumber());
    IssuerSerial issuerSerial = new IssuerSerial(issuer, serial);
    String algorithmHashOID = SignerAlgorithmEnum.getSignerAlgorithmEnum(attribute.getAlgorithmHash())
            .getOIDAlgorithmHash();
    AlgorithmIdentifier algorithmId = new AlgorithmIdentifier(algorithmHashOID);
    ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(algorithmId, certHash, issuerSerial);
    return new DERSet(new DERSequence(
            new ASN1Encodable[] { new DERSequence(essCertIDv2), new DERSequence(new DERNull()) }));
}

From source file:ca.nrc.cadc.cred.server.actions.DelegationAction.java

License:Open Source License

X509CertificateChain prepareCert(X509CertificateChain signCert) throws InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException, CertificateParsingException,
        CertificateEncodingException, CertificateExpiredException, CertificateNotYetValidException {
    log.debug("prepareCert - START");
    if (!(signCert.getPrivateKey() instanceof RSAKey)) {
        // TODO - Only RSA keys are supported. Generate a proxy cert
        // if this is not the case
        // This should probably be cached somehow
        if (daysValid == Float.MAX_VALUE) {
            daysValid = 30.0f;//from w w  w. jav  a 2 s.c  o m
        }
    }

    if (daysValid == Float.MAX_VALUE) {
        // return the stored certificate as it is
        log.debug("daysValid = " + daysValid + ", returning bare certificate");
        return signCert;
    } else {
        // return proxy certificate signed with the key of the
        // stored certificate

        try {

            // Add the Bouncy Castle JCE provider. This allows the CSR
            // classes to work. The BC implementation of PKCS#10 depends
            // on the ciphers in the BC provider.
            if (Security.getProvider("BC") == null) {
                Security.addProvider(new BouncyCastleProvider());
            }

            KeyPairGenerator keyPairGenerator = null;
            try {
                keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            } catch (NoSuchAlgorithmException ex) {
                ex.printStackTrace();
                throw new RuntimeException("The JCE doesn't do RSA! Game over.");
            }
            keyPairGenerator.initialize(CertUtil.DEFAULT_KEY_LENGTH);

            // generate the subject
            String subject = signCert.getChain()[0].getSubjectX500Principal().getName(X500Principal.CANONICAL);

            // generated the key pair
            KeyPair keys = keyPairGenerator.generateKeyPair();

            // generate the CSR
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                    CertUtil.DEFAULT_SIGNATURE_ALGORITHM, new X509Name(subject), keys.getPublic(), null,
                    keys.getPrivate(), "BC");
            log.debug("PKCS10CertificationRequest " + csr.getSignatureAlgorithm().toString());

            // sign the CSR
            X509Certificate newCert = CertUtil.generateCertificate(csr, Math.round(daysValid * 24 * 60 * 60),
                    signCert);

            // package and return
            X509Certificate[] certChain = new X509Certificate[signCert.getChain().length + 1];
            certChain[0] = newCert;
            System.arraycopy(signCert.getChain(), 0, certChain, 1, signCert.getChain().length);
            X509CertificateChain result = new X509CertificateChain(certChain, keys.getPrivate());
            result.setPrincipal(signCert.getPrincipal());

            return result;
        } finally {
            profiler.checkpoint("prepareCert");
        }
    }
}

From source file:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.java

License:Apache License

/**
 * Parses a X.500 distinguished name for the value of the 
 * "Common Name" field./*from ww  w. ja  v a  2 s.co m*/
 * This is done a bit sloppy right now and should probably be done a bit
 * more according to <code>RFC 2253</code>.
 *
 * @param dn  a X.500 distinguished name.
 * @return the value of the "Common Name" field.
 */
private String getCN(String dn) {
    X509Name name = new X509Name(dn);
    Vector<?> vector = name.getValues(X509Name.CN);
    if ((vector != null) && (vector.size() > 0)) {
        return (String) vector.get(0);
    } else {
        return null;
    }
}

From source file:ch.bfh.unicert.certimport.CertificateIssuer.java

License:GNU General Public License

public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity,
        String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL,
        String section) throws CertificateCreationException {

    X509Certificate caCert;//from ww w .  j  av  a2s .co  m
    RSAPrivateCrtKey privKey;
    try {
        caCert = this.readIssuerCertificate(this.issuerId);
        privKey = this.readPrivateKey(this.issuerId, this.privKeyPass);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        logger.log(Level.SEVERE, null, ex);
        throw new CertificateCreationException("230 Could not create client certificate. Key error");
    }

    RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey);

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(getExpiryDate(validity).getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(),
            id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(),
            id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles,
            id.getIdentityProvider(), extensionMap);

    //post message on UniBoard if corresponding JNDI parameter is defined
    postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(),
            privKey);

    return cert;

}

From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java

License:GNU General Public License

/**
 * Actually creates the requestor certificate.
 *
 * @param id requestor identity data/*from w w w .  j  av  a2s .co  m*/
 * @param caCert certificate of the certification authority
 * @param cipherParams issuer private key parameters used for signing
 * @param pk public key of the requestor to certify
 * @param expiry the expiry date
 * @param applicationIdentifier the application identifier for which te certificate is issued
 * @param role role for which the certificate is issued
 * @return the certificate object containing the X509 certificate
 * @throws CertificateCreationException if an error occurs
 */
private Certificate createClientCertificate(IdentityData id, X509Certificate caCert,
        CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier,
        String[] roles) throws CertificateCreationException {

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(expiry.getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException
            | NoSuchProviderException | InvalidCipherTextException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(),
            id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(),
            id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap);

}