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:com.otterca.common.crypto.X509CertificateBuilderImpl.java

License:Apache License

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

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

License:Apache License

/**
 * @see com.otterca.common.crypto.X509CertificateBuilder#setTimestampingLocations(com.otterca.common.crypto.GeneralName...)
 *//*from   w  ww.j a v  a2s.co m*/
@Override
public X509CertificateBuilder setTimestampingLocations(com.otterca.common.crypto.GeneralName<?>... names) {
    timestamping.clear();
    for (com.otterca.common.crypto.GeneralName<?> name : names) {
        switch (name.getType()) {
        case URI:
            timestamping.add(new GeneralName(GeneralName.uniformResourceIdentifier, name.get().toString()));
            break;
        case EMAIL:
            timestamping.add(new GeneralName(GeneralName.rfc822Name, name.get().toString()));
            break;
        case DNS:
            timestamping.add(new GeneralName(GeneralName.dNSName, name.get().toString()));
            break;
        case IP_ADDRESS:
            timestamping
                    .add(new GeneralName(GeneralName.iPAddress, ((InetAddress) name.get()).getHostAddress()));
            break;
        default:
            throw new IllegalArgumentException("unexpected type for Timestamping location: " + name.getType());
        }
    }
    return this;
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

License:Apache License

private X509Certificate generateV3Certificate(KeyPair pair, String certSubjectDN, Calendar before,
        Calendar expiry) throws CryptoException {
    X509V3CertificateGenerator cert = new X509V3CertificateGenerator();

    /* Set the certificate serial number to a random number */
    Random rand = new Random();
    rand.setSeed(System.currentTimeMillis());

    /* Generates a number between 0 and 2^32 as the serial */
    BigInteger serial = BigInteger.valueOf(rand.nextInt(Integer.MAX_VALUE));
    logger.info("Setting X509 Cert Serial to: " + serial);

    cert.setSerialNumber(serial);/*from  ww  w.jav  a 2 s.  c o  m*/

    /* Set the certificate issuer */
    cert.setIssuerDN(new X500Principal(this.certIssuerDN));

    /* Set the start of valid period. */
    cert.setNotBefore(before.getTime());

    /* Set the certificate expiry date. */
    cert.setNotAfter(expiry.getTime());

    /* Set the subject */
    cert.setSubjectDN(new X500Principal(certSubjectDN));

    cert.setPublicKey(pair.getPublic());

    /* Signature algorithm, this may need to be changed if not all hosts have SHA256 and RSA implementations */
    cert.setSignatureAlgorithm("SHA512withRSA");

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

    /* Only for signing */
    cert.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
    cert.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    /* Set a contact email address for the issuer */
    cert.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, this.certIssuerEmail)));

    logger.debug("Generating X509Certificate for key pair: " + pair);

    try {
        /* Use the BouncyCastle provider to actually generate the X509Certificate now */
        return cert.generateX509Certificate(pair.getPrivate(), "BC");
    } catch (InvalidKeyException e) {
        this.logger.error("InvalidKeyException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (NoSuchProviderException e) {
        this.logger.error("NoSuchProviderException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (SecurityException e) {
        this.logger.error("SecurityException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (SignatureException e) {
        this.logger.error("SignatureException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }

}

From source file:com.rcn.service.CertificateService.java

License:Open Source License

private GeneralNames toGeneralNames(String altName, Map<String, String> generalNameMap) {

    GeneralName subjectAltName = new GeneralName(GeneralName.rfc822Name, altName);
    List<GeneralName> generalNameList = new ArrayList<GeneralName>();
    generalNameList.add(subjectAltName);
    generalNameMap.keySet().forEach(oid -> {
        String value = generalNameMap.get(oid);
        DERUTF8String derUtf8 = new DERUTF8String(value);
        ASN1Encodable oidObj = new DERObjectIdentifier(oid);
        ASN1Encodable valueObj = new DERTaggedObject(true, 0, derUtf8);
        ASN1Encodable[] asn1Seq = new ASN1Encodable[] { oidObj, valueObj };
        generalNameList.add(new GeneralName(GeneralName.otherName, new DERSequence(asn1Seq)));
    });//from  ww w .  j  a  v a  2  s.co  m

    return new GeneralNames(new DERSequence(generalNameList.toArray(new GeneralName[0])));
}

From source file:com.yacme.ext.oxsit.cust_it.security.crl.X509CertRL.java

License:Open Source License

private static String decodeAGeneralName(GeneralName genName) throws IOException {
    switch (genName.getTagNo()) {
    //only URI are used here, the other protocols are ignored
    case GeneralName.uniformResourceIdentifier:
        return ((DERString) genName.getName()).getString();
    case GeneralName.ediPartyName:
    case GeneralName.x400Address:
    case GeneralName.otherName:
    case GeneralName.directoryName:
    case GeneralName.dNSName:
    case GeneralName.rfc822Name:
    case GeneralName.registeredID:
    case GeneralName.iPAddress:
        break;//  ww  w  . ja  va  2  s. c  o  m
    default:
        throw new IOException("Bad tag number: " + genName.getTagNo());
    }
    return null;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static String extractX509CSREmail(PKCS10CertificationRequest certReq) {

    String rfc822 = null;// ww  w.  jav  a  2 s  . c  om
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == GeneralName.rfc822Name) {
                    rfc822 = (((DERIA5String) name.getName()).getString());
                    break;
                }
            }
        }
    }
    return rfc822;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static List<String> extractX509CertEmails(X509Certificate x509Cert) {
    Collection<List<?>> altNames = null;
    try {/*from   w  w  w .  java2 s  . c o m*/
        altNames = x509Cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException ex) {
        LOG.error("extractX509IPAddresses: Caught CertificateParsingException when parsing certificate: "
                + ex.getMessage());
    }

    if (altNames == null) {
        return Collections.emptyList();
    }

    List<String> emails = new ArrayList<>();
    for (@SuppressWarnings("rawtypes")
    List item : altNames) {
        Integer type = (Integer) item.get(0);

        // GeneralName ::= CHOICE {
        //     otherName                       [0]     OtherName,
        //     rfc822Name                      [1]     IA5String,
        //     dNSName                         [2]     IA5String,
        //     x400Address                     [3]     ORAddress,
        //     directoryName                   [4]     Name,
        //     ediPartyName                    [5]     EDIPartyName,
        //     uniformResourceIdentifier       [6]     IA5String,
        //     iPAddress                       [7]     OCTET STRING,
        //     registeredID                    [8]     OBJECT IDENTIFIER}

        if (type == GeneralName.rfc822Name) {
            emails.add((String) item.get(1));
        }
    }
    return emails;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq,
        PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {

    // set validity for the given number of minutes from now

    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);// www. ja  v a 2  s .  co m
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();

    // Generate self-signed certificate

    X509Certificate cert = null;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(
                certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();

        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer,
                BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(),
                publicKey)
                        .addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints))
                        .addExtension(Extension.keyUsage, true,
                                new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment))
                        .addExtension(Extension.extendedKeyUsage, true,
                                new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth,
                                        KeyPurposeId.id_kp_serverAuth }));

        // see if we have the dns/rfc822/ip address extensions specified in the csr

        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest
                .getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns == null) {
                    continue;
                }
                GeneralName[] names = gns.getNames();
                for (int i = 0; i < names.length; i++) {
                    switch (names[i].getTagNo()) {
                    case GeneralName.dNSName:
                    case GeneralName.iPAddress:
                    case GeneralName.rfc822Name:
                        altNames.add(names[i]);
                        break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false,
                        new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])));
            }
        }

        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER)
                .build(caPrivateKey);

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));

    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error(
                "generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(
                "generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: " + ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }

    return cert;
}

From source file:com.yahoo.athenz.zts.ZTSClient.java

License:Apache License

/**
 * Generate a Role Certificate request that could be sent to ZTS
 * to obtain a X509 Certificate for the requested role.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @param roleDomainName name of the domain where role is defined
 * @param roleName name of the role to get a certificate request for
 * @param privateKey private key for the service identity for the caller
 * @param csrDn string identifying the dn for the csr without the cn component
 * @param csrDomain string identifying the dns domain for generating SAN fields
 * @param expiryTime number of seconds to request certificate to be valid for
 * @return RoleCertificateRequest object
 *///  w w  w  .ja v  a2  s.c  om
static public RoleCertificateRequest generateRoleCertificateRequest(final String principalDomain,
        final String principalService, final String roleDomainName, final String roleName,
        PrivateKey privateKey, final String csrDn, final String csrDomain, int expiryTime) {

    if (principalDomain == null || principalService == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }

    if (roleDomainName == null || roleName == null) {
        throw new IllegalArgumentException("Role DomainName and Name must be specified");
    }

    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }

    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be our role resource value

    final String domain = principalDomain.toLowerCase();
    final String service = principalService.toLowerCase();

    String dn = "cn=" + roleDomainName.toLowerCase() + ":role." + roleName.toLowerCase();
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }

    // now let's generate our dsnName and email fields which will based on
    // our principal's details

    StringBuilder hostBuilder = new StringBuilder(128);
    hostBuilder.append(service);
    hostBuilder.append('.');
    hostBuilder.append(domain.replace('.', '-'));
    hostBuilder.append('.');
    hostBuilder.append(csrDomain);
    String hostName = hostBuilder.toString();

    String email = domain + "." + service + "@" + csrDomain;

    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    sanArray[1] = new GeneralName(GeneralName.rfc822Name, new DERIA5String(email));

    String csr = null;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    RoleCertificateRequest req = new RoleCertificateRequest().setCsr(csr)
            .setExpiryTime(Long.valueOf(expiryTime));
    return req;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

String getSubjectAltNameRfc822Name() {
    Collection<List<?>> generalNames = null;
    try {//w w w.j a  v  a 2 s .  c om
        generalNames = cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "unable to get subject alternative names", e);
    }

    if (generalNames == null) {
        return null;
    }

    for (List<?> generalName : generalNames) {
        Integer tag = (Integer) generalName.get(0);
        if (GeneralName.rfc822Name == tag.intValue()) {
            String value = (String) generalName.get(1);
            return value;
        }
    }

    return null;
}