Example usage for org.bouncycastle.asn1.x509 GeneralName rfc822Name

List of usage examples for org.bouncycastle.asn1.x509 GeneralName rfc822Name

Introduction

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

Prototype

int rfc822Name

To view the source code for org.bouncycastle.asn1.x509 GeneralName rfc822Name.

Click Source Link

Usage

From source file:ClientOCSPDriver.java

License:Open Source License

/**
Generates a signed OCSP client request with the parameters specified in the constructor.
This method can only be called once./*from   w  ww  .  ja  v a  2  s .  com*/
@param signingalgorithm The algorithm, that should be used to sign the OCSP client request, default is "MD5WITHRSA".
@param provider The provider used to compute the hashes and sign the request, default is "BC" (Bouncy Castle).
@return The raw DER encoded client OCSP request. This data has to be transported over a specific protocol (such as HTTP) to the OCSP server in order to get
an OCSP server response.
*/
public byte[] getRequest(String signingalgorithm, String provider, String user)
        throws OCSPException, NoSuchProviderException, IOException {
    if (calledgenerate)
        throw new OCSPException("Request was already generated!");
    map.clear();
    OCSPReqGenerator gen = new OCSPReqGenerator();
    for (int i = 0; i < certificates.length; ++i) {
        CertificateID certid = new CertificateID(CertificateID.HASH_SHA1, mastercert,
                certificates[i].getSerialNumber());
        System.out.println("issuerNameHash: " + toHexadecimal(certid.getIssuerNameHash()));
        System.out.println("issuerKeyHash: " + toHexadecimal(certid.getIssuerKeyHash()));
        System.out.println("serialNumber: " + certid.getSerialNumber());
        map.put(certid, certificates[i]);
        gen.addRequest(certid);
    }

    ASN1Sequence seq = null;
    if (usercert != null && userkey != null && user == null) {
        X509Name subjectName = new X509Name(true, usercert.getSubjectX500Principal().getName());
        Vector oids = subjectName.getOIDs();
        Vector values = subjectName.getValues();

        //Create a ASNSequence object for the subject DN
        seq = getASNSequence(oids, values);
        gen.setRequestorName(new GeneralName(new X509Name(seq)));
    }
    if (user != null) {
        gen.setRequestorName(new GeneralName(GeneralName.rfc822Name, user));
    }

    //Include nonce extension 1.3.6.1.5.5.7.48.1.2                     
    /*
            byte[] Nonce = new byte[16];
            random.nextBytes(Nonce);                  
           ASN1EncodableVector  v = new ASN1EncodableVector();       
            ASN1EncodableVector  sVec = new ASN1EncodableVector();        
           DERObjectIdentifier  oid = new DERObjectIdentifier("1.3.6.1.5.5.7.48.1.2");
            v.add(oid);        
            v.add(new DEROctetString(Nonce));
            sVec.add(new DERSequence(v));        
            seq = new DERSequence(sVec);      
           gen.setRequestExtensions(new X509Extensions(seq));
    */
    //End   

    byte[] ocspdata = null;
    if (usercert != null && userkey != null) {
        ocspdata = gen.generate(signingalgorithm, userkey, new X509Certificate[] { usercert }, provider)
                .getEncoded();
    } else {
        ocspdata = gen.generate().getEncoded();
    }
    calledgenerate = true;
    return ocspdata;
}

From source file:br.gov.jfrj.siga.cd.CertificadoUtil.java

License:Open Source License

/**
 * Recupera as propriedades ICP/Brasil-Pessoa Fsica (email e CPF)
 * /*  w w w. j  a v  a 2s.com*/
 * @param cert
 * @return
 * @throws IOException
 * @throws CertificateParsingException
 */
public static Properties recuperarPropriedadesNomesAlteranativos(X509Certificate cert)
        throws IOException, CertificateParsingException {
    Properties props = new Properties();
    Pair<ASN1ObjectIdentifier, String> otherName;

    Iterator<?> subjectAltNamesIt = X509ExtensionUtil.getSubjectAlternativeNames(cert).iterator();
    while (subjectAltNamesIt.hasNext()) {
        List<?> altName = (List<?>) subjectAltNamesIt.next();
        int type = ((Integer) altName.get(0)).intValue();
        if (type == GeneralName.rfc822Name) {
            String email = (String) altName.get(1);
            props.put("email", email);
        } else if (type == GeneralName.otherName) {
            otherName = getOtherName((DLSequence) altName.get(1));
            props.put(otherName.first.getId(), otherName.second);
        }
    }

    //      for (List<?> subjectAlternativeName : cert.getSubjectAlternativeNames()) {
    //         String email;
    //         @SuppressWarnings("unused")
    //         int pos;
    //
    //         // O primeiro elemento  um Integer com o valor 0 = otherName, 1
    //         // =
    //         // rfc822name etc.
    //         // O segundo valor  um byte array ou uma String. Veja o javadoc
    //         // de
    //         // getSubjectAlternativeNames.
    //         switch (((Number) subjectAlternativeName.get(0)).intValue()) {
    //         case 0: // OtherName - contm CPF, CNPJ etc.
    //            // o OID fica em otherName.first
    //            Collection collection = X509ExtensionUtil.getSubjectAlternativeNames(cert);
    //            otherName = getOtherName((byte[]) subjectAlternativeName.get(1));
    //            props.put(otherName.first.getId(), otherName.second);
    //            break;
    //         case 1: // rfc822Name - usado para email
    //            email = (String) subjectAlternativeName.get(1);
    //            props.put("email", email);
    //            break;
    //         default:
    //            break;
    //         }
    //      }
    return props;
}

From source file:chapter6.PKCS10ExtensionExample.java

public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception {
    // Create a SubjectAlternativeName extension value
    GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"));

    // Create the extensions object and add it as an attribute
    Vector oids = new Vector();
    Vector values = new Vector();

    oids.add(X509Extensions.SubjectAlternativeName);
    values.add(new X509Extension(false, new DEROctetString(subjectAltName)));

    X509Extensions extensions = new X509Extensions(oids, values);

    Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            new DERSet(extensions));

    return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"),
            pair.getPublic(), new DERSet(attribute), pair.getPrivate());
}

From source file:chapter6.X509V3CreateExample.java

public static X509Certificate generateV3Certificate(KeyPair pair) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    // Extension ::= SEQUENCE {
    //  extnID      OBJECT IDENTIFIER,
    //  critical    BOOLEAN DEFAULT FALSE
    //  extnValue   OCTET STRING }
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

    return certGen.generateX509Certificate(pair.getPrivate(), CryptoDefs.Provider.BC.getName());
}

From source file:com.aqnote.shared.cryptology.cert.gen.SingleX509V3Creator.java

License:Open Source License

public static X509Certificate generate(CertObject certObject, KeyPair keyPair) throws CertException {

    try {//from  w w w. ja  va2 s.c om
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                new X500Name(certObject.getIssuer()), BigInteger.valueOf(System.currentTimeMillis()),
                certObject.getNotBefore(), certObject.getNotAfter(), new X500Name(certObject.getSubject()),
                keyPair.getPublic());

        certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certBuilder.addExtension(Extension.subjectAlternativeName, false,
                new GeneralNames(new GeneralName(GeneralName.rfc822Name, "trust_device")));
        ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
                .build(keyPair.getPrivate());
        return new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
                .getCertificate(certBuilder.build(signer));
    } catch (CertificateEncodingException e) {
        throw new CertException(e);
    } catch (IllegalStateException e) {
        throw new CertException(e);
    } catch (CertIOException e) {
        throw new CertException(e);
    } catch (OperatorCreationException e) {
        throw new CertException(e);
    } catch (CertificateException e) {
        throw new CertException(e);
    }
}

From source file:com.aqnote.shared.encrypt.cert.gen.SingleX509V3Creator.java

License:Open Source License

public static X509Certificate generate(MadCertificateObject certObject, KeyPair keyPair) throws CertException {

    try {/*  w w w  .  j a v  a 2 s  .co  m*/
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                new X500Name(certObject.getIssuer()), BigInteger.valueOf(System.currentTimeMillis()),
                certObject.getNotBefore(), certObject.getNotAfter(), new X500Name(certObject.getSubject()),
                keyPair.getPublic());

        certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certBuilder.addExtension(Extension.subjectAlternativeName, false,
                new GeneralNames(new GeneralName(GeneralName.rfc822Name, "trust_device")));
        ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
                .build(keyPair.getPrivate());
        return new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
                .getCertificate(certBuilder.build(signer));
    } catch (CertificateEncodingException e) {
        throw new CertException(e);
    } catch (IllegalStateException e) {
        throw new CertException(e);
    } catch (CertIOException e) {
        throw new CertException(e);
    } catch (OperatorCreationException e) {
        throw new CertException(e);
    } catch (CertificateException e) {
        throw new CertException(e);
    }
}

From source file:com.example.androidtest.SslUtil.java

License:Open Source License

/**
 * Generates a new, self-signed X509 V3 certificate for a KeyPair.
 * //w ww  .  j ava 2 s.co m
 * @param  pair                      the {@link KeyPair} to be used
 * @param  name                      X.500 distinguished name
 * @param  notBefore                 not valid before this date
 * @param  notAfter                  not valid after this date
 * @param  serialNumber              serial number
 * @return                           the new certificate
 * @throws GeneralSecurityException  on error generating the certificate
 */
@SuppressWarnings("deprecation")
public static X509Certificate generateX509V3Certificate(KeyPair pair, String name, Date notBefore,
        Date notAfter, BigInteger serialNumber) throws GeneralSecurityException {
    java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X509Name dnName = new X509Name(name);

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setSubjectDN(dnName); // note: same as issuer
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    // For self-signed certificates, OpenSSL 0.9.6 has specific requirements
    // about certificate and extension content.  Quoting the `man verify`:
    //
    //   In OpenSSL 0.9.6 and later all certificates whose subject name matches
    //   the issuer name of the current certificate are subject to further
    //   tests. The relevant authority key identifier components of the current
    //   certificate (if present) must match the subject key identifier (if
    //   present) and issuer and serial number of the candidate issuer, in
    //   addition the keyUsage extension of the candidate issuer (if present)
    //   must permit certificate signing.
    //
    // In the code that follows,
    //   - the KeyUsage extension permits cert signing (KeyUsage.keyCertSign);
    //   - the Authority Key Identifier extension is added, matching the
    //     subject key identifier, and using the issuer, and serial number.

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    AuthorityKeyIdentifier authIdentifier = createAuthorityKeyIdentifier(pair.getPublic(), dnName,
            serialNumber);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, true, authIdentifier);
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
            new SubjectKeyIdentifierStructure(pair.getPublic()));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "googletv@test.test")));

    // This method is deprecated, but Android Eclair does not provide the 
    // generate() methods.
    X509Certificate cert = certGen.generateX509Certificate(pair.getPrivate(), "BC");
    return cert;
}

From source file:com.gitblit.utils.X509Utils.java

License:Apache License

/**
 * Creates a new client certificate PKCS#12 and PEM store.  Any existing
 * stores are destroyed.//from  w w w .ja v a2  s .  c  o m
 *
 * @param clientMetadata a container for dynamic parameters needed for generation
 * @param caKeystoreFile
 * @param caKeystorePassword
 * @param targetFolder
 * @return
 */
public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey,
        X509Certificate caCert, File targetFolder) {
    try {
        KeyPair pair = newKeyPair();

        X500Name userDN = buildDistinguishedName(clientMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

        // create a new certificate signed by the Gitblit CA certificate
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN,
                BigInteger.valueOf(System.currentTimeMillis()), clientMetadata.notBefore,
                clientMetadata.notAfter, userDN, pair.getPublic());

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
                extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        certBuilder.addExtension(X509Extension.keyUsage, true,
                new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        if (!StringUtils.isEmpty(clientMetadata.emailAddress)) {
            GeneralNames subjectAltName = new GeneralNames(
                    new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }

        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC)
                .build(caPrivateKey);

        X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC)
                .getCertificate(certBuilder.build(signer));
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                extUtils.createSubjectKeyIdentifier(pair.getPublic()));

        // confirm the validity of the user certificate
        userCert.checkValidity();
        userCert.verify(caCert.getPublicKey());
        userCert.getIssuerDN().equals(caCert.getSubjectDN());

        // verify user certificate chain
        verifyChain(userCert, caCert);

        targetFolder.mkdirs();

        // save certificate, stamped with unique name
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String id = date;
        File certFile = new File(targetFolder, id + ".cer");
        int count = 0;
        while (certFile.exists()) {
            id = date + "_" + Character.toString((char) (0x61 + count));
            certFile = new File(targetFolder, id + ".cer");
            count++;
        }

        // save user private key, user certificate and CA certificate to a PKCS#12 store
        File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
        if (p12File.exists()) {
            p12File.delete();
        }
        KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
        userStore.setKeyEntry(
                MessageFormat.format("Gitblit ({0}) {1} {2}", clientMetadata.serverHostname,
                        clientMetadata.userDisplayname, id),
                pair.getPrivate(), null, new Certificate[] { userCert });
        userStore.setCertificateEntry(
                MessageFormat.format("Gitblit ({0}) Certificate Authority", clientMetadata.serverHostname),
                caCert);
        saveKeyStore(p12File, userStore, clientMetadata.password);

        // save user private key, user certificate, and CA certificate to a PEM store
        File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
        if (pemFile.exists()) {
            pemFile.delete();
        }
        JcePEMEncryptorBuilder builder = new JcePEMEncryptorBuilder("DES-EDE3-CBC");
        builder.setSecureRandom(new SecureRandom());
        PEMEncryptor pemEncryptor = builder.build(clientMetadata.password.toCharArray());
        JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(pemFile));
        pemWriter.writeObject(pair.getPrivate(), pemEncryptor);
        pemWriter.writeObject(userCert);
        pemWriter.writeObject(caCert);
        pemWriter.flush();
        pemWriter.close();

        // save certificate after successfully creating the key stores
        saveCertificate(userCert, certFile);

        // update serial number in metadata object
        clientMetadata.serialNumber = userCert.getSerialNumber().toString();

        return userCert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate client certificate!", t);
    }
}

From source file:com.intirix.cloudpasswordmanager.services.ssl.CertPinningServiceImplUnitSpec.java

License:Apache License

public static X509Certificate generateV3Certificate(KeyPair pair)
        throws InvalidKeyException, NoSuchProviderException, SignatureException {

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}

From source file:com.otterca.common.crypto.X509CertificateBuilderImpl.java

License:Apache License

/**
 * @see com.otterca.repository.util.X509CertificateBuilder#setEmailAddresses(java.lang.String)
 *///from  ww w. j  a  v  a  2 s.  com
@Override
public X509CertificateBuilder setEmailAddresses(String... emailAddresses) {
    for (String address : emailAddresses) {
        subjectNames.add(new GeneralName(GeneralName.rfc822Name, address));
    }
    return this;
}