Example usage for org.bouncycastle.asn1 DERIA5String DERIA5String

List of usage examples for org.bouncycastle.asn1 DERIA5String DERIA5String

Introduction

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

Prototype

public DERIA5String(String string) 

Source Link

Document

Basic constructor - without validation.

Usage

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

License:Apache License

@Test(dataProvider = "x500Principal")
public void testX509CSRrequest(String x500Principal, boolean badRequest) throws Exception {
    PublicKey publicKey = Crypto.loadPublicKey(rsaPublicKey);
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    String certRequest = null;//from ww w.  j  av  a2 s  .c  om
    GeneralName otherName1 = new GeneralName(GeneralName.otherName, new DERIA5String("role1"));
    GeneralName otherName2 = new GeneralName(GeneralName.otherName, new DERIA5String("role2"));
    GeneralName[] sanArray = new GeneralName[] { otherName1, otherName2 };
    try {
        certRequest = Crypto.generateX509CSR(privateKey, publicKey, x500Principal, sanArray);
    } catch (Exception e) {
        if (!badRequest) {
            fail("Should not have failed to create csr");
        }
    }
    if (!badRequest) {
        //Now validate the csr
        Crypto.getPKCS10CertRequest(certRequest);
    }
}

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

License:Apache License

@Test(dataProvider = "x500Principal")
public void testX509CSRrequestWithPrivateKeyOnly(String x500Principal, boolean badRequest) throws Exception {
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    String certRequest = null;//from   w  ww.  j av a  2  s.c  o  m
    GeneralName otherName1 = new GeneralName(GeneralName.otherName, new DERIA5String("role1"));
    GeneralName otherName2 = new GeneralName(GeneralName.otherName, new DERIA5String("role2"));
    GeneralName[] sanArray = new GeneralName[] { otherName1, otherName2 };
    try {
        certRequest = Crypto.generateX509CSR(privateKey, x500Principal, sanArray);
    } catch (Exception e) {
        if (!badRequest) {
            fail("Should not have failed to create csr");
        }
    }
    if (!badRequest) {
        //Now validate the csr
        Crypto.getPKCS10CertRequest(certRequest);
    }
}

From source file:com.yahoo.athenz.example.instance.InstanceClientRefresh.java

License:Apache License

public static String generateCSR(String domainName, String serviceName, String instanceId, String dnsSuffix,
        PrivateKey key) {//from w w  w.  j a  v a2s . c o  m

    final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz";

    // now let's generate our dsnName field based on our principal's details

    StringBuilder dnsName = new StringBuilder(128);
    dnsName.append(serviceName);
    dnsName.append('.');
    dnsName.append(domainName.replace('.', '-'));
    dnsName.append('.');
    dnsName.append(dnsSuffix);

    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString()));

    // next we include our instance id

    StringBuilder dnsInstance = new StringBuilder(128);
    dnsInstance.append(instanceId);
    dnsInstance.append(".instanceid.athenz.");
    dnsInstance.append(dnsSuffix);

    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString()));

    String csr = null;
    try {
        csr = Crypto.generateX509CSR(key, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        System.err.println(ex.getMessage());
    }

    return csr;
}

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
 *///  www.j av  a2s. com
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.yahoo.athenz.zts.ZTSClient.java

License:Apache License

/**
 * Generate a Instance Refresh request that could be sent to ZTS to
 * request a TLS certificate for a service.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @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 InstanceRefreshRequest object
 *///from www .java  2  s . com
static public InstanceRefreshRequest generateInstanceRefreshRequest(final String principalDomain,
        final String principalService, 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 (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 based on our service name

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

    String dn = "cn=" + cn;
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }

    // now let's generate our dsnName field 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();

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

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

    InstanceRefreshRequest req = new InstanceRefreshRequest().setCsr(csr)
            .setExpiryTime(Integer.valueOf(expiryTime));
    return req;
}

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

License:Apache License

/**
 * For AWS Lambda functions generate a new private key, request a
 * x.509 certificate based on the requested CSR and return both to
 * the client in order to establish tls connections with other
 * Athenz enabled services.//from w  ww .ja va  2s  .c  om
 * @param domainName name of the domain
 * @param serviceName name of the service
 * @param account AWS account name that the function runs in
 * @param provider name of the provider service for AWS Lambda
 * @return AWSLambdaIdentity with private key and certificate
 */
public AWSLambdaIdentity getAWSLambdaServiceCertificate(String domainName, String serviceName, String account,
        String provider) {

    if (domainName == null || serviceName == null) {
        throw new IllegalArgumentException("Domain and Service must be specified");
    }

    if (account == null || provider == null) {
        throw new IllegalArgumentException("AWS Account and Provider must be specified");
    }

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

    // first we're going to generate a private key for the request

    AWSLambdaIdentity lambdaIdentity = new AWSLambdaIdentity();
    try {
        lambdaIdentity.setPrivateKey(Crypto.generateRSAPrivateKey(2048));
    } catch (CryptoException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    // we need to generate an csr with an instance register object

    InstanceRegisterInformation info = new InstanceRegisterInformation();
    info.setDomain(domainName.toLowerCase());
    info.setService(serviceName.toLowerCase());
    info.setProvider(provider.toLowerCase());

    final String athenzService = info.getDomain() + "." + info.getService();

    // generate our dn which will be based on our service name

    StringBuilder dnBuilder = new StringBuilder(128);
    dnBuilder.append("cn=");
    dnBuilder.append(athenzService);
    if (x509CsrDn != null) {
        dnBuilder.append(',');
        dnBuilder.append(x509CsrDn);
    }

    // now let's generate our dsnName field based on our principal's details

    StringBuilder hostBuilder = new StringBuilder(128);
    hostBuilder.append(info.getService());
    hostBuilder.append('.');
    hostBuilder.append(info.getDomain().replace('.', '-'));
    hostBuilder.append('.');
    hostBuilder.append(x509CsrDomain);

    StringBuilder instanceHostBuilder = new StringBuilder(128);
    instanceHostBuilder.append("lambda-");
    instanceHostBuilder.append(account);
    instanceHostBuilder.append('-');
    instanceHostBuilder.append(info.getService());
    instanceHostBuilder.append(".instanceid.athenz.");
    instanceHostBuilder.append(x509CsrDomain);

    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostBuilder.toString()));
    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(instanceHostBuilder.toString()));

    // next generate the csr based on our private key and data

    try {
        info.setCsr(Crypto.generateX509CSR(lambdaIdentity.getPrivateKey(), dnBuilder.toString(), sanArray));
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    // finally obtain attestation data for lambda

    info.setAttestationData(getAWSLambdaAttestationData(athenzService, account));

    // request the x.509 certificate from zts server

    Map<String, List<String>> responseHeaders = new HashMap<>();
    InstanceIdentity identity = postInstanceRegisterInformation(info, responseHeaders);

    try {
        lambdaIdentity.setX509Certificate(Crypto.loadX509Certificate(identity.getX509Certificate()));
    } catch (CryptoException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    return lambdaIdentity;
}

From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastleASN1Encoder.java

License:Open Source License

@Override
public void asn1EncodeAsciiString(String s) {
    asn1Encode(new DERIA5String(s));
}

From source file:es.gob.afirma.envelopers.cades.CAdESUtils.java

License:Open Source License

/**
 * Obtiene un PolicyInformation a partir de los datos de la pol&iacute;tica.
 * Sirve para los datos de SigningCertificate y SigningCertificateV2. Tiene que llevar algunos
 * datos de la pol&iacute;tica./*from  www  . j a  v  a  2  s  .  c  o  m*/
 * <pre>
 * PolicyInformation ::= SEQUENCE {
 * policyIdentifier   CertPolicyId,
 * policyQualifiers   SEQUENCE SIZE (1..MAX) OF
 *                          PolicyQualifierInfo OPTIONAL }
 *
 *
 * CertPolicyId ::= OBJECT IDENTIFIER
 *
 * PolicyQualifierInfo ::= SEQUENCE {
 *      policyQualifierId  PolicyQualifierId,
 *      qualifier          ANY DEFINED BY policyQualifierId }
 *
 * -- policyQualifierIds for Internet policy qualifiers
 *
 * id-qt          OBJECT IDENTIFIER ::=  { id-pkix 2 }
 * id-qt-cps      OBJECT IDENTIFIER ::=  { id-qt 1 }
 * id-qt-unotice  OBJECT IDENTIFIER ::=  { id-qt 2 }
 *
 * PolicyQualifierId ::=
 *      OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice )
 *
 * Qualifier ::= CHOICE {
 *      cPSuri           CPSuri,
 *      userNotice       UserNotice }
 *
 * CPSuri ::= IA5String
 *
 * UserNotice ::= SEQUENCE {
 *      noticeRef        NoticeReference OPTIONAL,
 *      explicitText     DisplayText OPTIONAL}
 *
 * NoticeReference ::= SEQUENCE {
 *      organization     DisplayText,
 *      noticeNumbers    SEQUENCE OF INTEGER }
 *
 * DisplayText ::= CHOICE {
 *      ia5String        IA5String      (SIZE (1..200)),
 *      visibleString    VisibleString  (SIZE (1..200)),
 *      bmpString        BMPString      (SIZE (1..200)),
 *      utf8String       UTF8String     (SIZE (1..200)) }
 * </pre>
 *
 * @param policy    Pol&iacute;tica de la firma.
 * @return          Estructura con la pol&iacute;tica preparada para insertarla en la firma.
 */
private static PolicyInformation[] getPolicyInformation(final AdESPolicy policy) {

    if (policy == null) {
        throw new IllegalArgumentException("La politica de firma no puede ser nula en este punto"); //$NON-NLS-1$
    }

    /*
     * PolicyQualifierInfo ::= SEQUENCE {
     *          policyQualifierId  PolicyQualifierId,
     *          qualifier          ANY DEFINED BY policyQualifierId }
     */

    final PolicyQualifierId pqid = PolicyQualifierId.id_qt_cps;
    DERIA5String uri = null;

    if (policy.getPolicyQualifier() != null && !policy.getPolicyQualifier().equals("")) { //$NON-NLS-1$
        uri = new DERIA5String(policy.getPolicyQualifier().toString());
    }

    final ASN1EncodableVector v = new ASN1EncodableVector();
    PolicyQualifierInfo pqi = null;
    if (uri != null) {
        v.add(pqid);
        v.add(uri);
        pqi = new PolicyQualifierInfo(new DERSequence(v));
    }

    /*
     * PolicyInformation ::= SEQUENCE {
     *     policyIdentifier   CertPolicyId,
     *     policyQualifiers   SEQUENCE SIZE (1..MAX) OF
     *                          PolicyQualifierInfo OPTIONAL }
     */

    if (policy.getPolicyQualifier() == null || pqi == null) {
        return new PolicyInformation[] { new PolicyInformation(
                new ASN1ObjectIdentifier(policy.getPolicyIdentifier().toLowerCase().replace("urn:oid:", ""))) //$NON-NLS-1$ //$NON-NLS-2$
        };
    }

    return new PolicyInformation[] { new PolicyInformation(
            new ASN1ObjectIdentifier(policy.getPolicyIdentifier().toLowerCase().replace("urn:oid:", "")), //$NON-NLS-1$//$NON-NLS-2$
            new DERSequence(pqi)) };

}

From source file:es.gob.afirma.envelopers.cades.SigPolicyQualifierInfo.java

License:Open Source License

/** Crea un nuevo <code>SigPolicyQualifierInfo</code> con su calificador
 * cPSuri./*from  w  w  w  .  j a  v  a2s. com*/
 * @param cps
 *        El CPS (certification practice statement) uri como <code>String</code>. */
SigPolicyQualifierInfo(final String cps) {
    this.sigPolicyQualifierId = PKCSObjectIdentifiers.id_spq_ets_uri;
    this.sigQualifier = new DERIA5String(cps);
}

From source file:es.gob.afirma.signers.cades.AOSigPolicyQualifierInfo.java

License:Open Source License

/** Crea un nuevo <code>AOSigPolicyQualifierInfo</code> con su calificador
 * cPSuri./*from  w  w w  .  jav  a  2  s. co  m*/
 * @param cps
 *        El CPS (certification practice statement) uri como <code>String</code>. */
AOSigPolicyQualifierInfo(final String cps) {
    this.sigPolicyQualifierId = PKCSObjectIdentifiers.id_spq_ets_uri;
    this.sigQualifier = new DERIA5String(cps);
}