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.pidome.server.services.provider.CertGen.java

License:Apache License

private void gen() throws CertGenException {
    try {/*from  w w w .j  a v  a 2 s .co m*/
        File store = new File(SystemConfig.getProperty("system", "server.keystore"));
        store.getParentFile().mkdirs();
        if (store.exists()) {
            store.delete();
        }
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setSubjectDN(new X500Principal("CN=" + curHost));
        certGen.setIssuerDN(new X500Principal("CN=PiDome Server at " + curHost));
        certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        certGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        certGen.setPublicKey(KPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

        GeneralName altName = new GeneralName(GeneralName.iPAddress,
                Network.getIpAddressProperty().get().getHostAddress());
        GeneralNames subjectAltName = new GeneralNames(altName);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);

        X509Certificate cert = certGen.generate(KPair.getPrivate(), "BC");

        /// Always, but always create a new keystore. a new keystore pass has is always created.
        privateKS = KeyStore.getInstance("JKS");
        privateKS.load(null, null);

        String storePass = MessageDigest.getInstance("MD5").toString();

        privateKS.setKeyEntry("PiDome.Default", KPair.getPrivate(), storePass.toCharArray(),
                new java.security.cert.Certificate[] { cert });

        store.createNewFile();

        privateKS.store(new FileOutputStream(store), storePass.toCharArray());

        System.setProperty("javax.net.ssl.keyStore", SystemConfig.getProperty("system", "server.keystore"));
        System.setProperty("javax.net.ssl.keyStorePassword", storePass);

        available = true;

        LOG.info("Certificate(s) generated.");

    } catch (CertificateEncodingException ex) {
        throw new CertGenException("Could not encode certificate, can not continue: " + ex.getMessage());
    } catch (IllegalStateException ex) {
        throw new CertGenException("Illegal state, can not continue: " + ex.getMessage());
    } catch (NoSuchProviderException ex) {
        throw new CertGenException("No known provider, can not continue: " + ex.getMessage());
    } catch (NoSuchAlgorithmException ex) {
        throw new CertGenException("No such algorithm, can not continue: " + ex.getMessage());
    } catch (SignatureException ex) {
        throw new CertGenException("Signature problem, can not continue: " + ex.getMessage());
    } catch (InvalidKeyException ex) {
        throw new CertGenException("Invalid key used, can not continue: " + ex.getMessage());
    } catch (KeyStoreException ex) {
        throw new CertGenException("KeyStore problem, can not continue: " + ex.getMessage());
    } catch (IOException ex) {
        throw new CertGenException("KeyStore can not be opened, can not continue: " + ex.getMessage());
    } catch (CertificateException ex) {
        throw new CertGenException("KeyStore certificate problem, can not continue: " + ex.getMessage());
    } catch (ConfigPropertiesException ex) {
        throw new CertGenException(
                "KeyStore location configuration problem, can not continue: " + ex.getMessage());
    }
}

From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java

License:Open Source License

@Override
public GeneralNames getSubjectAlternativeNames(X509Certificate cert) {
    try {// w ww.  j a v a 2  s  .  c  o  m
        byte[] value = cert.getExtensionValue(X509Extensions.SubjectAlternativeName.getId());
        if (value == null) {
            return null;
        }
        return GeneralNames.getInstance(
                ASN1Object.fromByteArray(((ASN1OctetString) ASN1Object.fromByteArray(value)).getOctets()));
    } catch (IOException ex) {
        throw new CryptoFailure("Unable to extract SubjectAlternativeName from X509Certificate extensions", ex);
    }
}

From source file:org.qipki.crypto.x509.X509GeneratorImpl.java

License:Open Source License

@SuppressWarnings({ "UseOfObsoleteCollectionType", "unchecked" })
private DERSet generateSANAttribute(GeneralNames subGeneralNames) {
    if (subGeneralNames == null) {
        return new DERSet();
    }//from  w ww .j a v a 2  s.c om
    Vector oids = new Vector();
    Vector values = new Vector();
    oids.add(X509Extensions.SubjectAlternativeName);
    values.add(new X509Extension(false, new DEROctetString(subGeneralNames)));
    X509Extensions extensions = new X509Extensions(oids, values);
    Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            new DERSet(extensions));
    return new DERSet(attribute);
}

From source file:org.sufficientlysecure.keychain.pgp.PgpToX509.java

License:Open Source License

/**
 * Creates a self-signed certificate from a public and private key. The (critical) key-usage
 * extension is set up with: digital signature, non-repudiation, key-encipherment, key-agreement
 * and certificate-signing. The (non-critical) Netscape extension is set up with: SSL client and
 * S/MIME. A URI subjectAltName may also be set up.
 *
 * @param pubKey         public key/* w  w w  .  j a v a2  s.c om*/
 * @param privKey        private key
 * @param subject        subject (and issuer) DN for this certificate, RFC 2253 format preferred.
 * @param startDate      date from which the certificate will be valid (defaults to current date and time
 *                       if null)
 * @param endDate        date until which the certificate will be valid (defaults to current date and time
 *                       if null) *
 * @param subjAltNameURI URI to be placed in subjectAltName
 * @return self-signed certificate
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws IllegalStateException
 * @throws NoSuchProviderException
 * @throws CertificateException
 * @throws Exception
 * @author Bruno Harbulot
 */
public static X509Certificate createSelfSignedCert(PublicKey pubKey, PrivateKey privKey, X509Name subject,
        Date startDate, Date endDate, String subjAltNameURI) throws InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException {

    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();

    certGenerator.reset();
    /*
     * Sets up the subject distinguished name. Since it's a self-signed certificate, issuer and
     * subject are the same.
     */
    certGenerator.setIssuerDN(subject);
    certGenerator.setSubjectDN(subject);

    /*
     * Sets up the validity dates.
     */
    if (startDate == null) {
        startDate = new Date(System.currentTimeMillis());
    }
    certGenerator.setNotBefore(startDate);
    if (endDate == null) {
        endDate = new Date(startDate.getTime() + (365L * 24L * 60L * 60L * 1000L));
        Log.d(Constants.TAG, "end date is=" + DateFormat.getDateInstance().format(endDate));
    }

    certGenerator.setNotAfter(endDate);

    /*
     * The serial-number of this certificate is 1. It makes sense because it's self-signed.
     */
    certGenerator.setSerialNumber(BigInteger.ONE);
    /*
     * Sets the public-key to embed in this certificate.
     */
    certGenerator.setPublicKey(pubKey);
    /*
     * Sets the signature algorithm.
     */
    String pubKeyAlgorithm = pubKey.getAlgorithm();
    if (pubKeyAlgorithm.equals("DSA")) {
        certGenerator.setSignatureAlgorithm("SHA1WithDSA");
    } else if (pubKeyAlgorithm.equals("RSA")) {
        certGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption");
    } else {
        RuntimeException re = new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm);
        Log.e(Constants.TAG, re.getMessage(), re);
        throw re;
    }

    /*
     * Adds the Basic Constraint (CA: true) extension.
     */
    certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

    /*
     * Adds the subject key identifier extension.
     */
    SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pubKey);
    certGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier);

    /*
     * Adds the authority key identifier extension.
     */
    AuthorityKeyIdentifier authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(pubKey);
    certGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);

    /*
     * Adds the subject alternative-name extension.
     */
    if (subjAltNameURI != null) {
        GeneralNames subjectAltNames = new GeneralNames(
                new GeneralName(GeneralName.uniformResourceIdentifier, subjAltNameURI));
        certGenerator.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltNames);
    }

    /*
     * Creates and sign this certificate with the private key corresponding to the public key of
     * the certificate (hence the name "self-signed certificate").
     */
    X509Certificate cert = certGenerator.generate(privKey);

    /*
     * Checks that this certificate has indeed been correctly signed.
     */
    cert.verify(pubKey);

    return cert;
}

From source file:org.tramaci.onionmail.LibSTLS.java

License:Open Source License

public static X509Certificate CreateCert(KeyPair KP, String onion, long Dfrom, long Dto, String info,
        String[] AltName) throws Exception { //OK

    byte[] bi = Stdio.md5(onion.getBytes());
    byte[] bx = new byte[bi.length + 9];
    System.arraycopy(bi, 0, bx, 1, bi.length);
    bx[0] = 0x7C;/*from   ww w  .j  a va 2s .co m*/
    byte[] tmp = Stdio.Stosx(new long[] { Dfrom / 1000L, Dto / 1000L }, 4);
    int bp = 17;
    for (int ax = 0; ax < 8; ax++)
        bx[bp++] = tmp[ax];

    Date startDate = new Date(Dfrom); // time from which certificate is valid
    Date expiryDate = new Date(Dto); // time after which certificate is not valid
    BigInteger serialNumber = new BigInteger(bx); // serial number for certificate
    KeyPair keyPair = KP; // EC public/private key pair

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    if (info != null && info.length() > 0)
        info = ", " + info;
    else
        info = "";
    X500Principal dnName = new X500Principal("CN=" + onion + info);
    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(dnName); // note: same as issuer
    certGen.setPublicKey(KP.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    if (AltName != null) {
        int cx = AltName.length;
        for (int ax = 0; ax < cx; ax++)
            try {
                GeneralName generalName = new GeneralName(GeneralName.dNSName,
                        new DERIA5String(AltName[ax].toLowerCase().trim()));
                GeneralNames subjectAltNames = new GeneralNames(generalName);
                certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
                        new DEROctetString(subjectAltNames));
            } catch (Exception EI) {
                Main.echo("CreateCert Error: " + EI.getMessage() + " (altName=`" + AltName[ax] + "`)\n");
            }
    }

    X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");

    return cert;
}

From source file:org.xwiki.crypto.x509.internal.X509Keymaker.java

License:Open Source License

/**
 * Create a new X509 client certificate.
 *
 * @param forCert the public key which will be embedded in the certificate, whoever has the matching private key
 *                "owns" the certificate.
 * @param toSignWith the private key in this pair will be used to sign the certificate.
 * @param daysOfValidity number of days the cert should be valid for.
 * @param nonRepudiable this should only be true if the private key is not stored on the server.
 * @param webId the URI to put as the alternative name (for FOAFSSL webId compatibility)
 * @param userName a String representation of the name of the user getting the certificate.
 * @return a new X509 certificate./* w w  w  .j av  a  2s .c o m*/
 * @throws GeneralSecurityException if something goes wrong.
 */
public synchronized X509Certificate makeClientCertificate(final PublicKey forCert, final KeyPair toSignWith,
        final int daysOfValidity, final boolean nonRepudiable, final String webId, final String userName)
        throws GeneralSecurityException {
    try {
        // the UID (same for issuer since this certificate confers no authority)
        final X509Name dName = new X509Name("UID=" + userName);

        this.prepareGenericCertificate(forCert, daysOfValidity, dName, dName);

        // Not a CA
        certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

        // Client cert
        certGenerator.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
                new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime));

        // Key Usage extension.
        int keyUsage = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                | KeyUsage.keyAgreement;
        if (nonRepudiable) {
            keyUsage |= KeyUsage.nonRepudiation;
        }
        certGenerator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));

        // Set the authority key identifier to be the CA key which we are using.
        certGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(toSignWith.getPublic()));

        // FOAFSSL compatibility.
        final GeneralNames subjectAltNames = new GeneralNames(
                new GeneralName(GeneralName.uniformResourceIdentifier, webId));
        certGenerator.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames);

        return this.generate(toSignWith);

    } finally {
        // Clean up after ourselves so that it is more difficult to try to extract private keys from the heap.
        this.certGenerator.reset();
    }
}