Example usage for org.bouncycastle.asn1 DEROctetString DEROctetString

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

Introduction

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

Prototype

public DEROctetString(ASN1Encodable obj) throws IOException 

Source Link

Document

Constructor from the encoding of an ASN.1 object.

Usage

From source file:dorkbox.util.crypto.CryptoX509.java

License:Apache License

/**
 * Creates a NEW signature block that contains the pkcs7 (minus content, which is the .SF file)
 * signature of the .SF file.//from   w  w  w .  j  a va2 s  .co  m
 *
 * It contains the hash of the data, and the verification signature.
 */
public static byte[] createSignature(byte[] signatureSourceData, X509CertificateHolder x509CertificateHolder,
        AsymmetricKeyParameter privateKey) {

    try {
        CMSTypedData content = new CMSProcessableByteArray(signatureSourceData);

        ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(content.getContentType().getId());
        ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
        ASN1EncodableVector signerInfos = new ASN1EncodableVector();

        AlgorithmIdentifier sigAlgId = x509CertificateHolder.getSignatureAlgorithm();
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        // use the bouncy-castle lightweight API to generate a hash of the signature source data (usually the signature file bytes)
        BcContentSignerBuilder contentSignerBuilder;
        AlgorithmIdentifier digEncryptionAlgorithm;

        if (privateKey instanceof ECPrivateKeyParameters) {
            contentSignerBuilder = new BcECDSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1  // DSA hashID
        } else if (privateKey instanceof DSAPrivateKeyParameters) {
            contentSignerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1  // DSA hashID
        } else if (privateKey instanceof RSAPrivateCrtKeyParameters) {
            contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(RSAUtil.rsaOids[0], null); // 1.2.840.113549.1.1.1 // RSA hashID
        } else {
            throw new RuntimeException("Invalid signature type. Only ECDSA, DSA, RSA supported.");
        }

        ContentSigner hashSigner = contentSignerBuilder.build(privateKey);
        OutputStream outputStream = hashSigner.getOutputStream();
        outputStream.write(signatureSourceData, 0, signatureSourceData.length);
        outputStream.flush();
        byte[] sigBytes = hashSigner.getSignature();

        SignerIdentifier sigId = new SignerIdentifier(
                new IssuerAndSerialNumber(x509CertificateHolder.toASN1Structure()));

        SignerInfo inf = new SignerInfo(sigId, digAlgId, null, digEncryptionAlgorithm,
                new DEROctetString(sigBytes), (ASN1Set) null);

        digestAlgs.add(inf.getDigestAlgorithm());
        signerInfos.add(inf);

        ASN1EncodableVector certs = new ASN1EncodableVector();
        certs.add(x509CertificateHolder.toASN1Structure());

        ContentInfo encInfo = new ContentInfo(contentTypeOID, null);
        SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, new BERSet(certs), null,
                new DERSet(signerInfos));

        ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
        CMSSignedData cmsSignedData2 = new CMSSignedData(content, contentInfo);

        return cmsSignedData2.getEncoded();
    } catch (Throwable t) {
        logger.error("Error signing data.", t);
        throw new RuntimeException("Error trying to sign data. " + t.getMessage());
    }
}

From source file:edu.tamu.tcat.crypto.bouncycastle.ASN1SeqKeyImpl.java

License:Apache License

private static ASN1Sequence getParameters(ECParameterSpec ecParameterSpec) throws EncodingException {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(1));
    EllipticCurve curve = ecParameterSpec.getCurve();

    ASN1Sequence fieldId = getField(curve.getField());
    v.add(fieldId);/*from w  w  w. ja  v a  2 s.  co  m*/
    v.add(getCurve(curve));

    org.bouncycastle.math.ec.ECPoint g = EC5Util.convertPoint(ecParameterSpec, ecParameterSpec.getGenerator(),
            false);
    byte[] encoded = g.getEncoded();
    v.add(new DEROctetString(encoded));

    v.add(new ASN1Integer(ecParameterSpec.getOrder()));
    v.add(new ASN1Integer(ecParameterSpec.getCofactor()));

    return new DERSequence(v);
}

From source file:edu.tamu.tcat.crypto.bouncycastle.ASN1SeqKeyImpl.java

License:Apache License

private static ASN1Sequence getCurve(EllipticCurve curve) throws EncodingException {
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new DEROctetString(getInteger(curve.getA())));
    v.add(new DEROctetString(getInteger(curve.getB())));
    byte[] seed = curve.getSeed();
    if (seed != null)
        v.add(new DERBitString(seed));

    return new DERSequence(v);
}

From source file:ee.ria.xroad.common.hashchain.DigestList.java

License:Open Source License

/**
 * Encodes hash value as SingleDigest data structure.
 *//*ww  w .ja  v a 2 s  .  c  o m*/
private static DERSequence singleDigest(String digestMethodUri, byte[] digest) throws Exception {
    DEROctetString digestValue = new DEROctetString(digest);
    DERUTF8String digestMethod = new DERUTF8String(digestMethodUri);

    DERSequence transforms = new DERSequence();

    return new DERSequence(new ASN1Encodable[] { digestValue, digestMethod, transforms });
}

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

License:Open Source License

/** Méodo que genera una firma digital usando el sitema conocido como
 * Data y que consiste en el contenido del fichero codificado como un
 * conjunto de bytes./*  w  w w . j av  a  2  s . co m*/
 * @param parameters
 *        Parámetros necesarios para obtener los datos de
 *        SignedData.
 * @return El contenido del fichero en formato Data.
 * @throws IOException */
static byte[] genData(final P7ContentSignerParameters parameters) throws IOException {
    // construimos el Data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.data, new DEROctetString(parameters.getContent()))
            .getEncoded(ASN1Encoding.DER);
}

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

License:Open Source License

/** Método que genera la firma de tipo digestedData.
 * @param parameters/*from  www  . j a va 2  s .co m*/
 *        Parámetros necesarios para la generación de este
 *        tipo.
 * @param dataType
 *        Identifica el tipo del contenido a firmar.
 * @return Mensaje firmado en tipo Digested Data.
 * @throws java.security.NoSuchAlgorithmException
 *         Si no se soporta alguno de los algoritmos de firma o huella
 *         digital
 * @throws java.io.IOException
 *         Si ocurre algún problema leyendo o escribiendo los
 *         datos */
static byte[] genDigestedData(final P7ContentSignerParameters parameters, final String dataType)
        throws NoSuchAlgorithmException, IOException {
    if (parameters == null) {
        throw new IllegalArgumentException("Los parametros no pueden ser nulos"); //$NON-NLS-1$
    }
    // Obtenemos el algoritmo para "digestear"
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(parameters.getSignatureAlgorithm());
    final AlgorithmIdentifier digAlgId;
    try {
        digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm));
    } catch (final Exception e) {
        throw new IOException(new StringBuilder().append("Error de codificacion: ").append(e).toString(), e); //$NON-NLS-1$
    }

    // indicamos el tipo de contenido
    final ContentInfo encInfo = new ContentInfo(new ASN1ObjectIdentifier(dataType), null);

    // digest
    final DEROctetString digest = new DEROctetString(
            MessageDigest.getInstance(digestAlgorithm).digest(parameters.getContent()));

    // construimos el digestedData.
    return new ContentInfo(PKCSObjectIdentifiers.digestedData, new DigestedData(digAlgId, encInfo, digest))
            .getEncoded(ASN1Encoding.DER);
}

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

License:Open Source License

/** Realiza la firma usando los atributos del firmante.
 * @param signatureAlgorithm/* www .j  a v  a2 s .c o m*/
 *        Algoritmo para la firma
 * @param keyEntry
 *        Clave para firmar.
 * @return Firma de los atributos.
 * @throws es.map.es.map.afirma.exceptions.AOException */
private ASN1OctetString firma(final String signatureAlgorithm, final PrivateKeyEntry keyEntry)
        throws AOException {

    final Signature sig;
    try {
        sig = Signature.getInstance(signatureAlgorithm);
    } catch (final Exception e) {
        throw new AOException("Error obteniendo la clase de firma para el algoritmo " + signatureAlgorithm, e); //$NON-NLS-1$
    }

    final byte[] tmp;
    try {
        tmp = this.signedAttr2.getEncoded(ASN1Encoding.DER);
    } catch (final IOException ex) {
        throw new AOException("Error obteniendo los atributos firmados", ex); //$NON-NLS-1$
    }

    // Indicar clave privada para la firma
    try {
        sig.initSign(keyEntry.getPrivateKey());
    } catch (final Exception e) {
        throw new AOException("Error al inicializar la firma con la clave privada", e); //$NON-NLS-1$
    }

    // Actualizamos la configuracion de firma
    try {
        sig.update(tmp);
    } catch (final SignatureException e) {
        throw new AOException("Error al configurar la informacion de firma", e); //$NON-NLS-1$
    }

    // firmamos.
    final byte[] realSig;
    try {
        realSig = sig.sign();
    } catch (final Exception e) {
        throw new AOException("Error durante el proceso de firma", e); //$NON-NLS-1$
    }

    final ASN1OctetString encDigest = new DEROctetString(realSig);

    return encDigest;

}

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

License:Open Source License

/** Obtiene un <code>Info</code> que contiene los RecipientInfos y el EncryptedContentInfo.
 * @param data Datos a incluir en el sobre
 * @param config Configuraci&oacute;n de cifrado a aplicar
 * @param certDest Certificados de los destinatarios
 * @param cipherKey Clave de cifrado//  www .  j a v a  2 s .c o  m
 * @return <code>Info</code> que contiene los RecipientInfos y el EncryptedContentInfo
 * @throws IOException en caso de error de entrada / salida
 * @throws CertificateEncodingException en caso de errores de codificaci&oacute;n en los certificados
 */
static Info getEnvelopeInfo(final byte[] data, final AOCipherConfig config, final X509Certificate[] certDest,
        final SecretKey cipherKey) throws IOException, CertificateEncodingException {

    // Reiniciamos las dos variables
    final Info infos = new Info();

    final ASN1EncodableVector recipientInfos = new ASN1EncodableVector();
    X509Certificate cert;
    TBSCertificateStructure tbs;
    IssuerAndSerialNumber isse;
    RecipientIdentifier rid;
    PublicKey pubKey;
    AlgorithmIdentifier keyEncAlg;
    SubjectPublicKeyInfo info;
    // Cifrado de la clave
    byte[] encryptedKey = null;
    // generamos el contenedor de cifrado

    RecipientInfo recipient = null;

    for (final X509Certificate element : certDest) {
        cert = element;
        tbs = TBSCertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getTBSCertificate()));
        // Obtenemos el Isuer & serial number
        isse = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()),
                tbs.getSerialNumber().getValue());
        // Creamos el recipientInfo
        rid = new RecipientIdentifier(isse);
        // Obtenemos la clave publica
        pubKey = cert.getPublicKey();
        // obtenemos la informacion de la clave publica
        info = tbs.getSubjectPublicKeyInfo();
        // obtenemos el algoritmo de cifrado.
        keyEncAlg = info.getAlgorithm();

        try {
            // ciframos la clave
            encryptedKey = cipherKey(pubKey, cipherKey);
        } catch (final Exception e) {
            LOGGER.severe("Error durante el proceso cifrado de la clave: " + e); //$NON-NLS-1$
        }
        // creamos el recipiente con los datos del destinatario.
        final KeyTransRecipientInfo keyTransRecipientInfo = new KeyTransRecipientInfo(rid, keyEncAlg,
                new DEROctetString(encryptedKey));

        recipient = new RecipientInfo(keyTransRecipientInfo);
        // Lo a&ntilde;adimos al recipiente de destinatarios.
        recipientInfos.add(recipient);
    }

    // 3. ENCRIPTEDCONTENTINFO
    try {
        infos.setEncInfo(getEncryptedContentInfo(data, config, cipherKey));
    } catch (final Exception e) {
        LOGGER.severe("Error durante el proceso cifrado de la clave: " + e); //$NON-NLS-1$
    }

    infos.setRecipientInfos(recipientInfos);

    return infos;
}

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

License:Open Source License

/** Obtiene el contenido de un archivo encriptado
 * @param file Archivo con los datos/*from  w  ww  . j a va 2  s  . c  o  m*/
 * @param config Configuracion de cifrado
 * @param params Parametros
 * @param cipher Encriptador */
private static EncryptedContentInfo getEncryptedContentInfo(final byte[] file, final AOCipherConfig config,
        final AlgorithmParameterSpec params, final Cipher cipher) throws IOException {
    final byte[] ciphered;
    try {
        ciphered = cipher.doFinal(file);
    } catch (final Exception e) {
        LOGGER.severe("No se ha podido completar el cifrado, se devolvera null: " + e); //$NON-NLS-1$
        return null;
    }

    ASN1Encodable asn1Params;
    if (params != null) {
        final ASN1InputStream aIn = new ASN1InputStream(cipher.getParameters().getEncoded("ASN.1")); //$NON-NLS-1$
        asn1Params = aIn.readObject();
        aIn.close();
    } else {
        asn1Params = new DERNull();
    }

    // obtenemos el OID del algoritmo de cifrado
    final AlgorithmIdentifier encAlgId = new AlgorithmIdentifier(
            new ASN1ObjectIdentifier(config.getAlgorithm().getOid()), asn1Params);

    // Obtenemos el identificador
    final ASN1ObjectIdentifier contentType = PKCSObjectIdentifiers.encryptedData;
    return new EncryptedContentInfo(contentType, encAlgId, new DEROctetString(ciphered));
}

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

License:Open Source License

/** Inicializa el contexto. */
static ASN1EncodableVector initContexExpecific(final String digestAlgorithm, final byte[] datos,
        final String dataType, final byte[] messageDigest) throws NoSuchAlgorithmException {
    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = new ASN1EncodableVector();

    // tipo de contenido
    if (dataType != null) {
        contexExpecific/*from w w  w . jav  a  2s  .co m*/
                .add(new Attribute(CMSAttributes.contentType, new DERSet(new DERObjectIdentifier(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(messageDigest != null ? messageDigest
                    : MessageDigest.getInstance(digestAlgorithm).digest(datos)))));

    return contexExpecific;
}