Example usage for org.bouncycastle.asn1 DERPrintableString DERPrintableString

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

Introduction

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

Prototype

public DERPrintableString(String string) 

Source Link

Document

Basic constructor - this does not validate the string

Usage

From source file:ClientOCSPDriver.java

License:Open Source License

/**
     * Apply ASN1 coversion for the given value depending on the oid
     * and the character range of the value.
     */*w w  w .j  a  v a 2s .com*/
     * This code was taken and modified from X509DefaultEntryConverter.java file 
     * of BouncyCastle. Modify this code to match the ASN1 type for your requestor subject DN
     * Refer Bouncycastle X509DefaultEntryConverter.java source for implementation of methods
     * such as convertHexEncoded, canBePrintable and canBeUTF8 
     * 
     * @param oid the object identifier for the DN entry
     * @param value the value associated with it
     * @return the ASN.1 equivalent for the string value.
     *      
     */
public DERObject getConvertedValue(DERObjectIdentifier oid, String value) {
    if (oid.equals(X509Name.O) || oid.equals(X509Name.OU)) {
        return new DERT61String(value);
    } else /*if (canBePrintable(value))  */
    {
        return new DERPrintableString(value);
    }
}

From source file:ca.trustpoint.m2m.EntityNameAttribute.java

License:Apache License

/**
 * Returns the DER encoding of this instance.
 *
 * @return The DER encoding of this instance.
 * @throws IOException if this instance cannot be encoded.
 *//* www  .  jav  a  2  s.  co  m*/
public byte[] getEncoded() throws IOException {
    if (!isValid()) {
        throw new IOException("Attribute is not valid.");
    }

    ASN1Encodable encodedValue;

    switch (id) {
    case Country:
    case DistinguishedNameQualifier:
    case SerialNumber:
        encodedValue = new DERPrintableString(value);
        break;
    case Organization:
    case OrganizationalUnit:
    case StateOrProvince:
    case Locality:
    case CommonName:
        encodedValue = new DERUTF8String(value);
        break;
    case DomainComponent:
        encodedValue = new DERIA5String(value);
        break;
    case RegisteredId:
        encodedValue = new ASN1ObjectIdentifier(value);
        break;
    case OctetsName:
        encodedValue = new DEROctetString(Hex.decode(value));
        break;
    default:
        throw new IOException("Unknown attribute type ID.");
    }

    return new DERTaggedObject(false, id.getIndexId(), encodedValue).getEncoded();
}

From source file:com.android.verity.BootSignature.java

License:Apache License

public BootSignature(String target, int length) {
    this.formatVersion = new ASN1Integer(0);
    this.target = new DERPrintableString(target);
    this.length = new ASN1Integer(length);
    this.algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption);
}

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

License:Open Source License

/** Método que genera la parte que contiene la información del
 * Usuario. Se generan los atributos que se necesitan para generar la firma.
 * @param cert Certificado del firmante//ww  w  . ja  va2s.  c o  m
 * @param datos Datos firmados
 * @param policy Política de firma
 * @param messageDigest
 * @return Los datos necesarios para generar la firma referente a los datos
 *         del usuario.
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.io.IOException
 * @throws CertificateEncodingException */
static ASN1EncodableVector generateSignerInfo(final X509Certificate cert, final String digestAlgorithmName,
        final byte[] datos, final AdESPolicy policy, final byte[] messageDigest)
        throws NoSuchAlgorithmException, IOException, CertificateEncodingException {

    // ALGORITMO DE HUELLA DIGITAL
    final AlgorithmIdentifier digestAlgorithmOID = SigUtils
            .makeAlgId(AOAlgorithmID.getOID(digestAlgorithmName));

    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = initContexExpecific(digestAlgorithmName, datos,
            PKCSObjectIdentifiers.data.getId(), messageDigest);

    // Serial Number
    // comentar lo de abajo para version del rfc 3852
    contexExpecific.add(new Attribute(RFC4519Style.serialNumber,
            new DERSet(new DERPrintableString(cert.getSerialNumber().toString()))));

    if (!"SHA1".equals(AOSignConstants.getDigestAlgorithmName(digestAlgorithmName))) { //$NON-NLS-1$

        //********************************************/
        //***** La Nueva operatividad esta comentada */
        //********************************************/
        // INICIO SINGING CERTIFICATE-V2

        /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
         * CertificateSerialNumber */

        final TBSCertificateStructure tbs = TBSCertificateStructure
                .getInstance(ASN1Primitive.fromByteArray(cert.getTBSCertificate()));

        /** ESSCertIDv2 ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier
         * DEFAULT {algorithm id-sha256}, certHash Hash, issuerSerial
         * IssuerSerial OPTIONAL }
         * Hash ::= OCTET STRING */

        final byte[] certHash = MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded());
        final ESSCertIDv2[] essCertIDv2 = { new ESSCertIDv2(digestAlgorithmOID, certHash,
                new IssuerSerial(new GeneralNames(new GeneralName(tbs.getIssuer())), tbs.getSerialNumber())) };

        /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
         * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
         * OPTIONAL }
         * CertPolicyId ::= OBJECT IDENTIFIER
         * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
         * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

        final SigningCertificateV2 scv2;
        if (policy.getPolicyIdentifier() != null) {

            /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
             * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
             * } */
            scv2 = new SigningCertificateV2(essCertIDv2, getPolicyInformation(policy)); // con
            // politica
        } else {
            scv2 = new SigningCertificateV2(essCertIDv2); // Sin politica
        }

        // Secuencia con singningCertificate
        contexExpecific.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(scv2)));

        // FIN SINGING CERTIFICATE-V2

    } else {

        // INICIO SINGNING CERTIFICATE

        /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
         * CertificateSerialNumber } */

        final TBSCertificateStructure tbs = TBSCertificateStructure
                .getInstance(ASN1Primitive.fromByteArray(cert.getTBSCertificate()));

        final IssuerSerial isuerSerial = new IssuerSerial(new GeneralNames(new GeneralName(tbs.getIssuer())),
                tbs.getSerialNumber());

        /** ESSCertID ::= SEQUENCE { certHash Hash, issuerSerial IssuerSerial
         * OPTIONAL }
         * Hash ::= OCTET STRING -- SHA1 hash of entire certificate */
        final ESSCertID essCertID = new ESSCertID(
                MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded()), isuerSerial);

        /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
         * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
         * OPTIONAL }
         * CertPolicyId ::= OBJECT IDENTIFIER
         * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
         * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

        final SigningCertificate scv;
        if (policy.getPolicyIdentifier() != null) {

            /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
             * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
             * } */
            /*
             * HAY QUE HACER UN SEQUENCE, YA QUE EL CONSTRUCTOR DE BOUNCY
             * CASTLE NO TIENE DICHO CONSTRUCTOR.
             */
            final ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERSequence(essCertID));
            v.add(new DERSequence(getPolicyInformation(policy)));
            scv = SigningCertificate.getInstance(new DERSequence(v)); // con politica
        } else {
            scv = new SigningCertificate(essCertID); // Sin politica
        }

        /** id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
         * member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16)
         * id-aa(2) 12 } */
        // Secuencia con singningCertificate
        contexExpecific.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, new DERSet(scv)));
    }

    // INICIO SIGPOLICYID ATTRIBUTE

    if (policy.getPolicyIdentifier() != null) {
        /*
         * SigPolicyId ::= OBJECT IDENTIFIER Politica de firma.
         */
        final ASN1ObjectIdentifier doiSigPolicyId = new ASN1ObjectIdentifier(
                policy.getPolicyIdentifier().toLowerCase().replace("urn:oid:", "")); //$NON-NLS-1$ //$NON-NLS-2$

        /*
         *   OtherHashAlgAndValue ::= SEQUENCE {
         *     hashAlgorithm    AlgorithmIdentifier,
         *     hashValue        OCTET STRING }
         *
         */

        // Algoritmo para el hash
        final AlgorithmIdentifier hashid;
        // si tenemos algoritmo de calculo de hash, lo ponemos
        if (policy.getPolicyIdentifierHashAlgorithm() != null) {
            hashid = SigUtils.makeAlgId(AOAlgorithmID
                    .getOID(AOSignConstants.getDigestAlgorithmName(policy.getPolicyIdentifierHashAlgorithm())));
        }
        // si no tenemos, ponemos el algoritmo de firma.
        else {
            hashid = digestAlgorithmOID;
        }
        // hash del documento, descifrado en b64
        final byte[] hashed;
        if (policy.getPolicyIdentifierHash() != null) {
            hashed = Base64.decode(policy.getPolicyIdentifierHash());
        } else {
            hashed = new byte[] { 0 };
        }

        final DigestInfo otherHashAlgAndValue = new DigestInfo(hashid, hashed);

        /*
         *   SigPolicyQualifierInfo ::= SEQUENCE {
         *       SigPolicyQualifierId  SigPolicyQualifierId,
         *       SigQualifier          ANY DEFINED BY policyQualifierId }
         */
        SigPolicyQualifierInfo spqInfo = null;
        if (policy.getPolicyQualifier() != null) {
            spqInfo = new SigPolicyQualifierInfo(policy.getPolicyQualifier().toString());
        }

        /*
         * SignaturePolicyId ::= SEQUENCE {
         *  sigPolicyId           SigPolicyId,
         *  sigPolicyHash         SigPolicyHash,
         *  sigPolicyQualifiers   SEQUENCE SIZE (1..MAX) OF
         *                          SigPolicyQualifierInfo OPTIONAL}
         *
         */
        final ASN1EncodableVector v = new ASN1EncodableVector();
        // sigPolicyId
        v.add(doiSigPolicyId);
        // sigPolicyHash
        v.add(otherHashAlgAndValue.toASN1Primitive()); // como sequence
        // sigPolicyQualifiers
        if (spqInfo != null) {
            v.add(spqInfo.toASN1Primitive());
        }

        final DERSequence ds = new DERSequence(v);

        // Secuencia con singningCertificate
        contexExpecific.add(
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId, new DERSet(ds.toASN1Primitive())));
        // FIN SIGPOLICYID ATTRIBUTE
    }

    return contexExpecific;
}

From source file:es.gob.afirma.envelopers.cms.CMSAuthenticatedData.java

License:Open Source License

/** Método que genera la parte que contiene la información del
 * Usuario. Se generan los atributos que se necesitan para generar la firma.
 * @param cert/*from   w  w  w.j av a 2  s. c o m*/
 *        Certificado necesario para la firma.
 * @param digestAlgorithm
 *        Algoritmo Firmado.
 * @param datos
 *        Datos firmados.
 * @param datatype
 *        Identifica el tipo del contenido a firmar.
 * @param timestamp
 *        Introducir TimeStaming
 * @param atrib
 *        Lista de atributos firmados que se insertarán dentro
 *        del archivo de firma.
 * @return Los atributos firmados de la firma.
 * @throws java.security.NoSuchAlgorithmException
 *         Si no se encuentra un algoritmo válido. */
private static ASN1Set generateSignedAtt(final X509Certificate cert, final String digestAlgorithm,
        final byte[] datos, final String datatype, final boolean timestamp, final Map<String, byte[]> atrib)
        throws NoSuchAlgorithmException {

    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = new ASN1EncodableVector();

    // tipo de contenido
    contexExpecific
            .add(new Attribute(CMSAttributes.contentType, new DERSet(new ASN1ObjectIdentifier(datatype))));

    // fecha de firma
    if (timestamp) {
        contexExpecific.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));
    }

    // Si nos viene el hash de fuera no lo calculamos
    final byte[] md = MessageDigest.getInstance(AOSignConstants.getDigestAlgorithmName(digestAlgorithm))
            .digest(datos);

    // MessageDigest
    contexExpecific.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(md.clone()))));

    // Serial Number
    // comentar lo de abajo para version del rfc 3852
    contexExpecific.add(new Attribute(RFC4519Style.serialNumber,
            new DERSet(new DERPrintableString(cert.getSerialNumber().toString()))));

    // agregamos la lista de atributos a mayores.
    if (atrib.size() != 0) {

        final Iterator<Map.Entry<String, byte[]>> it = atrib.entrySet().iterator();
        while (it.hasNext()) {
            final Map.Entry<String, byte[]> e = it.next();
            contexExpecific.add(new Attribute(
                    // el oid
                    new ASN1ObjectIdentifier(e.getKey().toString()),
                    // el array de bytes en formato string
                    new DERSet(new DERPrintableString(new String(e.getValue())))));
        }

    }

    return SigUtils.getAttributeSet(new AttributeTable(contexExpecific));
}

From source file:es.gob.afirma.envelopers.cms.CMSAuthenticatedEnvelopedData.java

License:Open Source License

/** M&eacute;todo que genera la parte que contiene la informaci&oacute;n del
 * Usuario. Se generan los atributos que se necesitan para generar la firma.
 * @param datatype/*from   w  w  w  .  java 2 s .  com*/
 *        Identifica el tipo del contenido a firmar.
 * @param signingTime
 *        Introducir la hora de firma (tomada del sistema)
 * @param atrib
 *        Lista de atributos firmados que se insertar&aacute;n dentro
 *        del archivo de firma.
 * @return Los atributos firmados de la firma. */
private static ASN1Set generateSignedAtt(final String datatype, final boolean signingTime,
        final Map<String, byte[]> atrib) {

    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = new ASN1EncodableVector();

    // tipo de contenido
    contexExpecific
            .add(new Attribute(CMSAttributes.contentType, new DERSet(new ASN1ObjectIdentifier(datatype))));

    // fecha de firma
    if (signingTime) {
        contexExpecific.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));
    }

    // agregamos la lista de atributos a mayores.
    if (atrib.size() != 0) {

        final Iterator<Map.Entry<String, byte[]>> it = atrib.entrySet().iterator();
        while (it.hasNext()) {
            final Map.Entry<String, byte[]> e = it.next();
            contexExpecific.add(new Attribute(
                    // el oid
                    new ASN1ObjectIdentifier(e.getKey().toString()),
                    // el array de bytes en formato string
                    new DERSet(new DERPrintableString(new String(e.getValue())))));
        }

    }

    return SigUtils.getAttributeSet(new AttributeTable(contexExpecific));
}

From source file:es.gob.afirma.envelopers.cms.CMSSignedAndEnvelopedData.java

License:Open Source License

/** M&eacute;todo que genera la parte que contiene la informaci&oacute;n del
 * firmante. Se generan los atributos que se necesitan para generar la firma.
 * @param cert Certificado del firmante.
 * @param digestAlgorithm Algoritmo Firmado.
 * @param datos Datos firmados.//from  w  w w .j a  v a 2 s.  co  m
 * @param dataType Identifica el tipo del contenido a firmar.
 * @param atrib Conjunto de atributos firmados.
 * @return Los datos necesarios para generar la firma referente a los datos
 *         del usuario.
 * @throws java.security.NoSuchAlgorithmException Si el JRE no soporta alg&uacute;n algoritmo necesario */
private ASN1Set generateSignerInfo(final X509Certificate cert, final String digestAlgorithm, final byte[] datos,
        final String dataType, final Map<String, byte[]> atrib) throws NoSuchAlgorithmException {
    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = Utils.initContexExpecific(digestAlgorithm, datos, dataType,
            null);

    // Serial Number
    // comentar lo de abajo para version del rfc 3852
    contexExpecific.add(new Attribute(RFC4519Style.serialNumber,
            new DERSet(new DERPrintableString(cert.getSerialNumber().toString()))));

    // agregamos la lista de atributos a mayores.
    if (atrib.size() != 0) {
        final Iterator<Map.Entry<String, byte[]>> it = atrib.entrySet().iterator();
        while (it.hasNext()) {
            final Map.Entry<String, byte[]> e = it.next();
            contexExpecific.add(new Attribute(
                    // el oid
                    new ASN1ObjectIdentifier(e.getKey().toString()),
                    // el array de bytes en formato string
                    new DERSet(new DERPrintableString(new String(e.getValue())))));
        }
    }

    this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contexExpecific));

    return SigUtils.getAttributeSet(new AttributeTable(contexExpecific));
}

From source file:es.gob.afirma.envelopers.cms.CMSSignedAndEnvelopedData.java

License:Open Source License

/** M&eacute;todo que genera la parte que contiene la informaci&oacute;n del
 * Usuario. Se generan los atributos no firmados.
 * @param uatrib/*from  www . ja va 2  s.c  o m*/
 *        Lista de atributos no firmados que se insertar&aacute;n dentro
 *        del archivo de firma.
 * @return Los atributos no firmados de la firma. */
private static ASN1Set generateUnsignerInfo(final Map<String, byte[]> uatrib) {

    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = new ASN1EncodableVector();

    // agregamos la lista de atributos a mayores.
    if (uatrib.size() != 0) {
        final Iterator<Map.Entry<String, byte[]>> it = uatrib.entrySet().iterator();
        while (it.hasNext()) {
            final Map.Entry<String, byte[]> e = it.next();
            contexExpecific.add(new Attribute(
                    // el oid
                    new ASN1ObjectIdentifier(e.getKey().toString()),
                    // el array de bytes en formato string
                    new DERSet(new DERPrintableString(new String(e.getValue())))));
        }
    } else {
        return null;
    }

    return SigUtils.getAttributeSet(new AttributeTable(contexExpecific));

}

From source file:es.gob.afirma.envelopers.cms.CoSignerEnveloped.java

License:Open Source License

/** M&eacute;todo que genera la parte que contiene la informaci&oacute;n del
 * Usuario. Se generan los atributos que se necesitan para generar la firma.
 * @param digestAlgorithm/*from   ww w  . j ava2s .c o m*/
 *        Algoritmo Firmado.
 * @param datos
 *        Datos firmados.
 * @param dataType
 *        Identifica el tipo del contenido a firmar.
 * @param atrib
 *        Lista de atributos firmados que se insertar&aacute;n dentro
 *        del archivo de firma.
 * @return Los atributos firmados de la firma.
 * @throws java.security.NoSuchAlgorithmException Si el JRE no soporta alg&uacute;n algoritmo necesario */
private ASN1Set generateSignerInfo(final String digestAlgorithm, final byte[] datos, final String dataType,
        final Map<String, byte[]> atrib) throws NoSuchAlgorithmException {

    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = new ASN1EncodableVector();

    // tipo de contenido
    contexExpecific
            .add(new Attribute(CMSAttributes.contentType, new DERSet(new ASN1ObjectIdentifier(dataType))));

    // fecha de firma
    contexExpecific.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));

    // Si nos viene el hash de fuera no lo calculamos
    final byte[] md = MessageDigest.getInstance(AOSignConstants.getDigestAlgorithmName(digestAlgorithm))
            .digest(datos);

    // MessageDigest
    contexExpecific.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(md.clone()))));

    // agregamos la lista de atributos a mayores.
    if (atrib.size() != 0) {
        final Iterator<Map.Entry<String, byte[]>> it = atrib.entrySet().iterator();
        while (it.hasNext()) {
            final Map.Entry<String, byte[]> e = it.next();
            contexExpecific.add(new Attribute(
                    // el oid
                    new ASN1ObjectIdentifier(e.getKey().toString()),
                    // el array de bytes en formato string
                    new DERSet(new DERPrintableString(new String(e.getValue())))));
        }
    }

    this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contexExpecific));

    return SigUtils.getAttributeSet(new AttributeTable(contexExpecific));

}

From source file:es.gob.afirma.envelopers.cms.CoSignerEnveloped.java

License:Open Source License

/** M&eacute;todo que genera la parte que contiene la informaci&oacute;n del
 * Usuario. Se generan los atributos que se necesitan para generar la firma.
 * En este caso se introduce el hash directamente.
 * @param cert Certificado necesario para la firma.
 * @param datos Datos firmados./*from   w  w w . java 2 s  .  co  m*/
 * @param dataType Identifica el tipo del contenido a firmar.
 * @param atrib Lista de atributos firmados que se insertar&aacute;n dentro
 *              del archivo de firma.
 * @return Los atributos firmados de la firma. */
private ASN1Set generateSignerInfoFromHash(final X509Certificate cert, final byte[] datos,
        final String dataType, final Map<String, byte[]> atrib) {

    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = new ASN1EncodableVector();

    // tipo de contenido
    contexExpecific
            .add(new Attribute(CMSAttributes.contentType, new DERSet(new ASN1ObjectIdentifier(dataType))));

    // fecha de firma
    contexExpecific.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));

    // MessageDigest
    contexExpecific.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(datos))));

    // Serial Number
    contexExpecific.add(new Attribute(RFC4519Style.serialNumber,
            new DERSet(new DERPrintableString(cert.getSerialNumber().toString()))));

    // agregamos la lista de atributos a mayores.
    if (atrib.size() != 0) {
        final Iterator<Map.Entry<String, byte[]>> it = atrib.entrySet().iterator();
        while (it.hasNext()) {
            final Map.Entry<String, byte[]> e = it.next();
            contexExpecific.add(new Attribute(
                    // el oid
                    new ASN1ObjectIdentifier(e.getKey().toString()),
                    // el array de bytes en formato string
                    new DERSet(new DERPrintableString(new String(e.getValue())))));
        }
    }

    this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contexExpecific));

    return SigUtils.getAttributeSet(new AttributeTable(contexExpecific));

}