Example usage for org.bouncycastle.asn1.x509 X509Extensions SubjectAlternativeName

List of usage examples for org.bouncycastle.asn1.x509 X509Extensions SubjectAlternativeName

Introduction

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

Prototype

ASN1ObjectIdentifier SubjectAlternativeName

To view the source code for org.bouncycastle.asn1.x509 X509Extensions SubjectAlternativeName.

Click Source Link

Document

Subject Alternative Name

Usage

From source file:org.ejbca.core.protocol.PKCS10RequestMessage.java

License:Open Source License

public String getRequestAltNames() {
    String ret = null;/*from   ww  w.  j  a va 2s  .  c o m*/
    try {
        X509Extensions exts = getRequestExtensions();
        if (exts != null) {
            X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName);
            if (ext != null) {
                // Finally read the value
                ret = CertTools.getAltNameStringFromExtension(ext);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("no subject altName extension");
                }
            }
        }
    } catch (IllegalArgumentException e) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "pkcs_9_extensionRequest does not contain Extensions that it should, ignoring invalid encoded extension request.");
        }
    }
    return ret;
}

From source file:org.ejbca.extra.ra.ScepRequestGenerator.java

License:Open Source License

/** Generates a SCEP CertReq. Keys must have been set in the generator for this to succeed 
 * /*ww  w  .j a  va2 s.c om*/
 */
public byte[] generateCertReq(String dn, String password, X509Certificate ca)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException,
        IOException, CMSException, InvalidAlgorithmParameterException, CertStoreException,
        CertificateEncodingException, IllegalStateException {
    this.cacert = ca;
    this.reqdn = dn;

    // Create challenge password attribute for PKCS10
    // Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
    //
    // Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
    //    type    ATTRIBUTE.&id({IOSet}),
    //    values  SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
    // }
    ASN1EncodableVector challpwdattr = new ASN1EncodableVector();
    // Challenge password attribute
    challpwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
    pwdvalues.add(new DERUTF8String(password));
    challpwdattr.add(new DERSet(pwdvalues));
    // Requested extensions attribute
    ASN1EncodableVector extensionattr = new ASN1EncodableVector();
    extensionattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    // AltNames
    GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo.bar.com,iPAddress=10.0.0.1");
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    try {
        dOut.writeObject(san);
    } catch (IOException e) {
        throw new IllegalArgumentException("error encoding value: " + e);
    }
    Vector oidvec = new Vector();
    oidvec.add(X509Extensions.SubjectAlternativeName);
    Vector valuevec = new Vector();
    valuevec.add(new X509Extension(false, new DEROctetString(bOut.toByteArray())));
    X509Extensions exts = new X509Extensions(oidvec, valuevec);
    extensionattr.add(new DERSet(exts));
    // Complete the Attribute section of the request, the set (Attributes) contains two sequences (Attribute)
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new DERSequence(challpwdattr));
    v.add(new DERSequence(extensionattr));
    DERSet attributes = new DERSet(v);
    // Create PKCS#10 certificate request
    p10request = new PKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX509Name(reqdn),
            keys.getPublic(), attributes, keys.getPrivate());

    // Create self signed cert, validity 1 day
    cert = CertTools.genSelfCert(reqdn, 24 * 60 * 60 * 1000, null, keys.getPrivate(), keys.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);

    // wrap message in pkcs#7
    byte[] msg = wrap(p10request.getEncoded(), "19");
    return msg;
}

From source file:org.ejbca.util.CertToolsTest.java

License:Open Source License

@SuppressWarnings("unchecked")
public void test19getAltNameStringFromExtension() throws Exception {
    PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(p10ReqWithAltNames);
    CertificationRequestInfo info = p10.getCertificationRequestInfo();
    ASN1Set set = info.getAttributes();
    // The set of attributes contains a sequence of with type oid
    // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest
    Enumeration<Object> en = set.getObjects();
    boolean found = false;
    while (en.hasMoreElements()) {
        ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement());
        DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0);
        if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            // The object at position 1 is a SET of x509extensions
            DERSet s = (DERSet) seq.getObjectAt(1);
            X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0));
            X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName);
            if (ext != null) {
                found = true;//from w  w  w  . j  av  a2 s .c om
                String altNames = CertTools.getAltNameStringFromExtension(ext);
                assertEquals("dNSName=ort3-kru.net.polisen.se, iPAddress=10.252.255.237", altNames);
            }
        }
    }
    assertTrue(found);

    p10 = new PKCS10CertificationRequest(p10ReqWithAltNames2);
    info = p10.getCertificationRequestInfo();
    set = info.getAttributes();
    // The set of attributes contains a sequence of with type oid
    // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest

    en = set.getObjects();
    found = false;
    while (en.hasMoreElements()) {
        ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement());
        DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0);
        if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            // The object at position 1 is a SET of x509extensions
            DERSet s = (DERSet) seq.getObjectAt(1);
            X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0));
            X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName);
            if (ext != null) {
                found = true;
                String altNames = CertTools.getAltNameStringFromExtension(ext);
                assertEquals("dNSName=foo.bar.com, iPAddress=10.0.0.1", altNames);
            }
        }
    }
    assertTrue(found);

}

From source file:org.glite.slcs.pki.CertificateExtensionFactory.java

License:eu-egee.org license

/**
 * Creates a CertificateExtension. The id can be the OID or the name as
 * defined below. The values is a comma separated list of value(s)
 * <p>/*from w w  w  . j a v  a2 s .  c o  m*/
 * Valid names and values:
 * <ul>
 * <li>KeyUsage
 * <ul>
 * <li>DigitalSignature
 * <li>NonRepudiation
 * <li>KeyEncipherment
 * <li>DataEncipherment
 * <li>KeyAgreement
 * <li>KeyCertSign
 * <li>CRLSign
 * <li>EncipherOnly
 * <li>DecipherOnly
 * </ul>
 * <li>ExtendedKeyUsage
 * <ul>
 * <li>AnyExtendedKeyUsage
 * <li>ServerAuth
 * <li>ClientAuth
 * <li>CodeSigning
 * <li>EmailProtection
 * <li>IPSecEndSystem
 * <li>IPSecTunnel
 * <li>IPSecUser
 * <li>OCSPSigning
 * <li>Smartcardlogon
 * </ul>
 * <li>CertificatePolicies
 * <ul>
 * <li>The policy OID(s)
 * </ul>
 * <li>SubjectAltName
 * <ul>
 * <li>email:EMAIL_ADDRESS
 * <li>dns:HOSTNAME
 * </ul>
 * </ul>
 * <p>
 * Example:
 * <pre>
 * CertificateExtension keyUsageExtension = 
 *       CertificateExtensionFactory.createCertificateExtension("KeyUsage", "DigitalSignature,KeyEncipherment");
 * CertificateExtension subjectAltNameExtension = 
 *       CertificateExtensionFactory.createCertificateExtension("SubjectAltName", "email:john.doe@example.com,dns:www.exmaple.com");
 * </pre>
 * 
 * @param id
 *            The name or the OID of the extension.
 * @param values
 *            A comma separated list of extension value(s).
 * @return The corresponding CertificateExtension or <code>null</code> if
 *         the id (name or oid) is not supported.
 */
static public CertificateExtension createCertificateExtension(String id, String values) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("id:" + id + " value(s):" + values);
    }
    if (id.equals(X509Extensions.KeyUsage.getId()) || id.equalsIgnoreCase("KeyUsage")) {
        // parse the comma separated list of key usage
        int usage = 0;
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String keyUsage = (String) st.nextElement();
            keyUsage = keyUsage.trim();

            if (keyUsage.equalsIgnoreCase("DigitalSignature")) {
                usage += KeyUsage.digitalSignature;
            } else if (keyUsage.equalsIgnoreCase("NonRepudiation")) {
                usage += KeyUsage.nonRepudiation;
            } else if (keyUsage.equalsIgnoreCase("KeyEncipherment")) {
                usage += KeyUsage.keyEncipherment;
            } else if (keyUsage.equalsIgnoreCase("DataEncipherment")) {
                usage += KeyUsage.dataEncipherment;
            } else if (keyUsage.equalsIgnoreCase("KeyAgreement")) {
                usage += KeyUsage.keyAgreement;
            } else if (keyUsage.equalsIgnoreCase("KeyCertSign")) {
                usage += KeyUsage.keyCertSign;
            } else if (keyUsage.equalsIgnoreCase("CRLSign")) {
                usage += KeyUsage.cRLSign;
            } else if (keyUsage.equalsIgnoreCase("EncipherOnly")) {
                usage += KeyUsage.encipherOnly;
            } else if (keyUsage.equalsIgnoreCase("DecipherOnly")) {
                usage += KeyUsage.decipherOnly;
            } else {
                LOG.error("Unknown KeyUsage: " + keyUsage);
            }

        }
        return createKeyUsageExtension(usage, values);
    } else if (id.equals(X509Extensions.ExtendedKeyUsage.getId()) || id.equalsIgnoreCase("ExtendedKeyUsage")) {
        // value is a comma separated list of keyPurpose
        Vector keyPurposeIds = new Vector();
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String keyPurpose = (String) st.nextElement();
            keyPurpose = keyPurpose.trim();
            if (keyPurpose.equalsIgnoreCase("AnyExtendedKeyUsage")) {
                keyPurposeIds.add(KeyPurposeId.anyExtendedKeyUsage);
            } else if (keyPurpose.equalsIgnoreCase("ServerAuth")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_serverAuth);
            } else if (keyPurpose.equalsIgnoreCase("ClientAuth")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_clientAuth);
            } else if (keyPurpose.equalsIgnoreCase("CodeSigning")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_codeSigning);
            } else if (keyPurpose.equalsIgnoreCase("EmailProtection")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_emailProtection);
            } else if (keyPurpose.equalsIgnoreCase("IPSecEndSystem")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_ipsecEndSystem);
            } else if (keyPurpose.equalsIgnoreCase("IPSecTunnel")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_ipsecTunnel);
            } else if (keyPurpose.equalsIgnoreCase("IPSecUser")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_ipsecUser);
            } else if (keyPurpose.equalsIgnoreCase("TimeStamping")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_timeStamping);
            } else if (keyPurpose.equalsIgnoreCase("OCSPSigning")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_OCSPSigning);
            } else if (keyPurpose.equalsIgnoreCase("Smartcardlogon")) {
                keyPurposeIds.add(KeyPurposeId.id_kp_smartcardlogon);
            } else {
                LOG.error("Unknown ExtendedKeyUsage: " + keyPurpose);
            }
        }
        return createExtendedKeyUsageExtension(keyPurposeIds, values);
    } else if (id.equals(X509Extensions.CertificatePolicies.getId())
            || id.equalsIgnoreCase("CertificatePolicies")) {
        // values is a comma separated list of policyOIDs
        Vector policyOIDs = new Vector();
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String policyOID = (String) st.nextElement();
            policyOID = policyOID.trim();
            policyOIDs.add(policyOID);
        }
        return createCertificatePoliciesExtension(policyOIDs, values);
    } else if (id.equals(X509Extensions.SubjectAlternativeName.getId())
            || id.equalsIgnoreCase("SubjectAltName")) {
        // values is a comma separated list of altername names prefixed with
        // the type (email: or dns:)
        Vector typedSubjectAltNames = new Vector();
        StringTokenizer st = new StringTokenizer(values, ",");
        while (st.hasMoreElements()) {
            String typedAltName = (String) st.nextElement();
            typedAltName = typedAltName.trim();
            typedSubjectAltNames.add(typedAltName);
        }
        return createSubjectAltNameExtension(typedSubjectAltNames, values);
    }
    LOG.error("Unsupported CertificateExtension: " + id);
    return null;
}

From source file:org.glite.slcs.pki.CertificateExtensionFactory.java

License:eu-egee.org license

/**
 * Creates a RFC882 Subject Alternative Name: email:johndoe@example.com
 * extension./*from   w  w w.j a  v a2 s  .c o m*/
 * 
 * @param emailAddress
 *            The email address to be included as alternative name.
 * @return The subject alternative name CertificateExtension.
 */
static protected CertificateExtension createSubjectAltNameExtension(String emailAddress) {
    GeneralName subjectAltName = new GeneralName(GeneralName.rfc822Name, emailAddress);
    GeneralNames subjectAltNames = new GeneralNames(subjectAltName);
    X509Extension subjectAltNameExtension = new X509Extension(false, new DEROctetString(subjectAltNames));
    return new CertificateExtension(X509Extensions.SubjectAlternativeName, "SubjectAltName",
            subjectAltNameExtension, emailAddress);

}

From source file:org.glite.slcs.pki.CertificateExtensionFactory.java

License:eu-egee.org license

/**
 * //from   w  w w .  j  a va 2s .c  o  m
 * @param prefixedAltNames
 * @param values
 * @return
 */
static protected CertificateExtension createSubjectAltNameExtension(Vector prefixedAltNames, String values) {
    ASN1EncodableVector altNames = new ASN1EncodableVector();
    Enumeration typeAndNames = prefixedAltNames.elements();
    while (typeAndNames.hasMoreElements()) {
        String typeAndName = (String) typeAndNames.nextElement();
        typeAndName = typeAndName.trim();
        if (typeAndName.startsWith("email:")) {
            String emailAddress = typeAndName.substring("email:".length());
            GeneralName altName = new GeneralName(GeneralName.rfc822Name, emailAddress);
            altNames.add(altName);

        } else if (typeAndName.startsWith("dns:")) {
            String hostname = typeAndName.substring("dns:".length());
            GeneralName altName = new GeneralName(GeneralName.dNSName, hostname);
            altNames.add(altName);
        } else {
            LOG.error("Unsupported subjectAltName: " + typeAndName);
        }
    }
    DERSequence subjectAltNames = new DERSequence(altNames);
    GeneralNames generalNames = new GeneralNames(subjectAltNames);
    X509Extension subjectAltNameExtension = new X509Extension(false, new DEROctetString(generalNames));
    return new CertificateExtension(X509Extensions.SubjectAlternativeName, "SubjectAltName",
            subjectAltNameExtension, values);

}

From source file:org.globus.security.trustmanager.X509ProxyCertPathValidator.java

License:Apache License

@SuppressWarnings("unused")
protected void checkProxyConstraints(TBSCertificateStructure proxy, TBSCertificateStructure issuer,
        X509Certificate checkedProxy) throws CertPathValidatorException, IOException {

    X509Extensions extensions;/*w ww  . j  av  a  2 s.c  o  m*/
    DERObjectIdentifier oid;
    X509Extension proxyExtension;

    X509Extension proxyKeyUsage = null;

    extensions = proxy.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            proxyExtension = extensions.getExtension(oid);
            if (oid.equals(X509Extensions.SubjectAlternativeName)
                    || oid.equals(X509Extensions.IssuerAlternativeName)) {
                // No Alt name extensions - 3.2 & 3.5
                throw new CertPathValidatorException("Proxy violation: no Subject or Issuer Alternative Name");
            } else if (oid.equals(X509Extensions.BasicConstraints)) {
                // Basic Constraint must not be true - 3.8
                BasicConstraints basicExt = CertificateUtil.getBasicConstraints(proxyExtension);
                if (basicExt.isCA()) {
                    throw new CertPathValidatorException("Proxy violation: Basic Constraint CA is set to true");
                }
            } else if (oid.equals(X509Extensions.KeyUsage)) {
                proxyKeyUsage = proxyExtension;

                checkKeyUsage(issuer, proxyExtension);
            }
        }
    }

    extensions = issuer.getExtensions();

    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            proxyExtension = extensions.getExtension(oid);
            checkExtension(oid, proxyExtension, proxyKeyUsage);
        }
    }

}

From source file:org.jivesoftware.util.CertificateManager.java

License:Open Source License

/**
 * Creates an X509 version3 certificate.
 *
 * @param kp           KeyPair that keeps the public and private keys for the new certificate.
 * @param months       time to live//  w w w.j ava 2s  .c  om
 * @param issuerDN     Issuer string e.g "O=Grid,OU=OGSA,CN=ACME"
 * @param subjectDN    Subject string e.g "O=Grid,OU=OGSA,CN=John Doe"
 * @param domain       Domain of the server.
 * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
 * @return X509 V3 Certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
private static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int months, String issuerDN,
        String subjectDN, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();

    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();

    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
    certGenerator.reset();

    certGenerator.setSerialNumber(serial);
    certGenerator.setIssuerDN(new X509Name(issuerDN));
    certGenerator.setNotBefore(new Date(System.currentTimeMillis()));
    certGenerator.setNotAfter(new Date(System.currentTimeMillis() + months * (1000L * 60 * 60 * 24 * 30)));
    certGenerator.setSubjectDN(new X509Name(subjectDN));
    certGenerator.setPublicKey(pubKey);
    certGenerator.setSignatureAlgorithm(signAlgoritm);

    // Generate the subject alternative name
    boolean critical = subjectDN == null || "".equals(subjectDN.trim());
    ASN1Sequence othernameSequence = new DERSequence(
            new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                    new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    // Add subject alternative name extension
    certGenerator.addExtension(X509Extensions.SubjectAlternativeName, critical, subjectAltNames);

    X509Certificate cert = certGenerator.generateX509Certificate(privKey, "BC", new SecureRandom());
    cert.checkValidity(new Date());
    cert.verify(pubKey);

    return cert;
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

License:Open Source License

protected CertificationRequest generateCSR(KeyPair keyPair, UserInfo userInfo) throws CertException {

    CertificationRequest csr;/*from www  .ja  v a 2 s  .co m*/

    GeneralNames subjectAltName = new GeneralNames(
            new GeneralName(GeneralName.rfc822Name, userInfo.getUserFields().get(CNField.Email)));

    Vector<DERObjectIdentifier> objectIdentifiers = new Vector<DERObjectIdentifier>();
    Vector<X509Extension> extensionValues = new Vector<X509Extension>();

    objectIdentifiers.add(X509Extensions.SubjectAlternativeName);
    extensionValues.add(new X509Extension(false, new DEROctetString(subjectAltName)));

    X509Extensions extensions = new X509Extensions(objectIdentifiers, extensionValues);

    Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            new DERSet(extensions));
    try {
        csr = new PKCS10CertificationRequest(CERT_SIGNATURE_ALGORITHM, userInfo.getX500Principal(),
                keyPair.getPublic(), new DERSet(attribute), keyPair.getPrivate());
    } catch (InvalidKeyException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (NoSuchProviderException e) {
        throw new CertException(e);
    } catch (java.security.SignatureException e) {
        throw new CertException(e);
    } catch (Exception e) {
        throw new CertException(e);
    }
    return csr;
}

From source file:org.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

/**
 * //from   ww  w.j  a v a  2  s . com
 * @param commonName - Common Name (CN) for generated certificate
 * @param organisation - Organisation (O) for generated certificate
 * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null
 * @param validityTime - the time that the certificate is valid (in days)
 * @return
 * @throws IOException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws CertificateParsingException
 */
public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate(
        String commonName, String organisation, String applicationUri, int validityTime) throws IOException,
        InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException,
        IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException {
    if (applicationUri == null)
        throw new NullPointerException("applicationUri must not be null");
    //Add provider for generator
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    //Initializes generator 
    SecureRandom srForCert = new SecureRandom();
    RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator();

    //Used for generating prime
    Random r = new Random(System.currentTimeMillis());
    int random = -1;

    while (random < 3) {
        random = r.nextInt(32);
    }
    //calculate(generate) possible value for public modulus
    //used method is "monte carlo -algorithm", so we calculate it as long as it generates value.
    BigInteger value = null;
    while (value == null) {
        value = BigInteger.probablePrime(random, new SecureRandom());
    }

    //Generate (Java) keypair
    genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80));
    AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair();

    //Extract the keys from parameters
    logger.debug("Generated keypair, extracting components and creating public structure for certificate");
    RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic();
    RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate();
    // used to get proper encoding for the certificate
    RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(),
            clientPublicKey.getExponent());
    logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent="
            + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus());

    // JCE format needed for the certificate - because getEncoded() is necessary...
    PublicKey certPubKey = KeyFactory.getInstance("RSA")
            .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent()));
    // and this one for the KeyStore
    PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate(
            new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(),
                    clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(),
                    clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv()));

    //The data for the certificate..
    Calendar expiryTime = Calendar.getInstance();
    expiryTime.add(Calendar.DAY_OF_YEAR, validityTime);

    X509Name certificateX509Name = new X509Name(
            "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country"));

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    certGen.setSerialNumber(serial);
    //Issuer and subject must be the same (because this is self signed)
    certGen.setIssuerDN(certificateX509Name);
    certGen.setSubjectDN(certificateX509Name);

    //expiry & start time for this certificate
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks)
    certGen.setNotAfter(expiryTime.getTime());

    certGen.setPublicKey(certPubKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //******* X.509 V3 Extensions *****************

    SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject());
    SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki);

    /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
    new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey)));
        */
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski);
    certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage(
                    KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation
                            | KeyUsage.dataEncipherment | KeyUsage.keyCertSign));

    BasicConstraints b = new BasicConstraints(false);

    Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>();
    extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage(
                    extendedKeyUsages));

    // create the extension value
    ASN1EncodableVector names = new ASN1EncodableVector();
    names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));
    //      GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri);
    //      names.add(dnsName);
    final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames);

    // AuthorityKeyIdentifier

    final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name));
    AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki);
    //***** generate certificate ***********/
    X509Certificate cert = certGen.generate(certPrivKey, "BC");

    //Encapsulate Certificate and private key to CertificateKeyPair
    Cert certificate = new Cert(cert);
    org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey(
            (RSAPrivateKey) certPrivKey);
    return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey);
}