Example usage for org.bouncycastle.asn1.x509 DigestInfo DigestInfo

List of usage examples for org.bouncycastle.asn1.x509 DigestInfo DigestInfo

Introduction

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

Prototype

public DigestInfo(AlgorithmIdentifier algId, byte[] digest) 

Source Link

Usage

From source file:bluecrystal.service.service.SignVerifyService.java

License:Open Source License

private byte[] derEncode(byte[] contentHash, AlgorithmIdentifier algId) throws Exception {
    DigestInfo dInfo = new DigestInfo(algId, contentHash);
    byte[] encoded = encodeDigest(dInfo);
    return encoded;
}

From source file:ch.bfh.unicert.certimport.CertificateIssuer.java

License:GNU General Public License

public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity,
        String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL,
        String section) throws CertificateCreationException {

    X509Certificate caCert;//w w w  . j  av  a2 s  .co  m
    RSAPrivateCrtKey privKey;
    try {
        caCert = this.readIssuerCertificate(this.issuerId);
        privKey = this.readPrivateKey(this.issuerId, this.privKeyPass);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        logger.log(Level.SEVERE, null, ex);
        throw new CertificateCreationException("230 Could not create client certificate. Key error");
    }

    RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey);

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(getExpiryDate(validity).getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(),
            id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(),
            id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles,
            id.getIdentityProvider(), extensionMap);

    //post message on UniBoard if corresponding JNDI parameter is defined
    postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(),
            privKey);

    return cert;

}

From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java

License:GNU General Public License

/**
 * Actually creates the requestor certificate.
 *
 * @param id requestor identity data//from  w ww.  j  a  v a2  s  . c om
 * @param caCert certificate of the certification authority
 * @param cipherParams issuer private key parameters used for signing
 * @param pk public key of the requestor to certify
 * @param expiry the expiry date
 * @param applicationIdentifier the application identifier for which te certificate is issued
 * @param role role for which the certificate is issued
 * @return the certificate object containing the X509 certificate
 * @throws CertificateCreationException if an error occurs
 */
private Certificate createClientCertificate(IdentityData id, X509Certificate caCert,
        CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier,
        String[] roles) throws CertificateCreationException {

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(expiry.getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException
            | NoSuchProviderException | InvalidCipherTextException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(),
            id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(),
            id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap);

}

From source file:com.yacme.ext.oxsit.cust_it.comp.security.DocumentSigner_IT.java

License:Open Source License

private byte[] encapsulateInDigestInfo(String digestAlg, byte[] digestBytes) throws IOException {

    byte[] bcDigestInfoBytes = null;
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);

    DERObjectIdentifier digestObjId = new DERObjectIdentifier(digestAlg);
    AlgorithmIdentifier algId = new AlgorithmIdentifier(digestObjId, null);
    DigestInfo dInfo = new DigestInfo(algId, digestBytes);

    dOut.writeObject(dInfo);/*from  w  ww . java2 s .  c o  m*/
    return bOut.toByteArray();

}

From source file:es.gob.afirma.envelopers.cades.CAdESUtils.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 cert Certificado del firmante/* ww w .  j  av  a 2s . c  o m*/
 * @param datos Datos firmados
 * @param policy Pol&iacute;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.signers.cades.CAdESUtils.java

License:Open Source License

private static Attribute getSigPolicyId(final String digestAlgorithmName, final AdESPolicy policy)
        throws IOException {

    /** SigPolicyId ::= OBJECT IDENTIFIER Politica de firma. */

    final ASN1ObjectIdentifier doiSigPolicyId = new ASN1ObjectIdentifier(
            policy.getPolicyIdentifier().toLowerCase(Locale.US).replace("urn:oid:", "") //$NON-NLS-1$ //$NON-NLS-2$
    );// w  w  w. ja  va 2s  .co  m

    /**  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 = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithmName));
    }

    // Huella del documento
    final byte[] hashed;
    if (policy.getPolicyIdentifierHash() != null) {
        hashed = Base64.decode(policy.getPolicyIdentifierHash());
    } else {
        hashed = new byte[] { 0 };
    }

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

    /** AOSigPolicyQualifierInfo ::= SEQUENCE {
     *       SigPolicyQualifierId  SigPolicyQualifierId,
     *       SigQualifier          ANY DEFINED BY policyQualifierId
     *  } */

    AOSigPolicyQualifierInfo spqInfo = null;
    if (policy.getPolicyQualifier() != null) {
        spqInfo = new AOSigPolicyQualifierInfo(policy.getPolicyQualifier().toString());
    }

    /** SignaturePolicyId ::= SEQUENCE {
     *    sigPolicyId           SigPolicyId,
     *    sigPolicyHash         SigPolicyHash,
     *    sigPolicyQualifiers   SEQUENCE SIZE (1..MAX) OF AOSigPolicyQualifierInfo OPTIONAL
     *  } */

    final ASN1EncodableVector v = new ASN1EncodableVector();
    // sigPolicyId
    v.add(doiSigPolicyId);
    // sigPolicyHash
    v.add(otherHashAlgAndValue.toASN1Primitive()); // como sequence
    // sigPolicyQualifiers
    if (spqInfo != null) {
        v.add(new DERSequence(spqInfo.toASN1Primitive()));
    }

    final DERSequence ds = new DERSequence(v);

    return new Attribute(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId, new DERSet(ds.toASN1Primitive()));

}

From source file:eu.europa.ec.markt.dss.signature.token.JKSSignatureToken.java

License:Open Source License

@Override
public byte[] encryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo, DSSPrivateKeyEntry keyEntry)
        throws NoSuchAlgorithmException {

    try {/*from  w  w  w.  j av  a2  s. co m*/

        final DigestInfo digestInfo = new DigestInfo(digestAlgo.getAlgorithmIdentifier(), digestValue);
        final Cipher cipher = Cipher.getInstance(keyEntry.getEncryptionAlgorithm().getPadding());
        cipher.init(Cipher.ENCRYPT_MODE, ((KSPrivateKeyEntry) keyEntry).getPrivateKey());
        return cipher.doFinal(digestInfo.getDEREncoded());
    } catch (BadPaddingException e) {
        throw new BadPasswordException(MSG.JAVA_KEYSTORE_BAD_PASSWORD, e);
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.ec.markt.dss.signature.token.Pkcs11SignatureToken.java

License:Open Source License

@Override
public byte[] encryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo, DSSPrivateKeyEntry keyEntry)
        throws NoSuchAlgorithmException {

    try {/*from  ww w.  ja  va  2 s . c  o m*/
        DigestInfo digestInfo = new DigestInfo(digestAlgo.getAlgorithmIdentifier(), digestValue);
        Cipher cipher = Cipher.getInstance(keyEntry.getSignatureAlgorithm().getPadding());
        cipher.init(Cipher.ENCRYPT_MODE, ((KSPrivateKeyEntry) keyEntry).getPrivateKey());
        return cipher.doFinal(digestInfo.getDEREncoded());
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (IllegalBlockSizeException e) {
        throw new RuntimeException(e);
    } catch (BadPaddingException e) {
        // More likely bad password
        throw new BadPasswordException(MSG.PKCS11_BAD_PASSWORD);
    }
}

From source file:eu.europa.ec.markt.dss.signature.token.Pkcs12SignatureToken.java

License:Open Source License

@Override
public byte[] encryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo, DSSPrivateKeyEntry keyEntry)
        throws NoSuchAlgorithmException {

    try {//from  w w  w .  ja v  a  2s. c  o m
        DigestInfo digestInfo = new DigestInfo(digestAlgo.getAlgorithmIdentifier(), digestValue);
        Cipher cipher = Cipher.getInstance(keyEntry.getSignatureAlgorithm().getPadding());
        cipher.init(Cipher.ENCRYPT_MODE, ((KSPrivateKeyEntry) keyEntry).getPrivateKey());
        return cipher.doFinal(digestInfo.getDEREncoded());
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (IllegalBlockSizeException e) {
        throw new RuntimeException(e);
    } catch (BadPaddingException e) {
        // More likely the password is not good.
        throw new BadPasswordException(MSG.PKCS12_BAD_PASSWORD);
    }

}

From source file:it.trento.comune.j4sign.cms.utils.CMSBuilder.java

License:Open Source License

private byte[] encapsulateInDigestInfo(String digestAlg, byte[] digestBytes) throws IOException {

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);

    DERObjectIdentifier digestObjId = new DERObjectIdentifier(digestAlg);
    AlgorithmIdentifier algId = new AlgorithmIdentifier(digestObjId, null);
    DigestInfo dInfo = new DigestInfo(algId, digestBytes);

    dOut.writeObject(dInfo);//from w w  w .  ja  v a  2 s . c  o m

    return bOut.toByteArray();

}