Example usage for org.bouncycastle.asn1 DERUTCTime DERUTCTime

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

Introduction

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

Prototype

public DERUTCTime(String time) 

Source Link

Usage

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private Attribute createSigningTime(Date now) {
    final ASN1EncodableVector setEV = new ASN1EncodableVector();
    setEV.add(new DERUTCTime(now));

    DERSet set = new DERSet(setEV);
    Attribute seq1 = new Attribute(new ASN1ObjectIdentifier(ID_SIGNING_TIME), set);
    return seq1;// w ww  .ja  v  a2s .c  om
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.attribute.BCSigningTime.java

License:Open Source License

@Override
public ASN1Set getValue() {
    SigningTime attribute = (SigningTime) super.getAttribute();
    Date date = attribute.getValue();
    return new DERSet(new DERUTCTime(date));
}

From source file:com.goodvikings.cryptim.api.KeyRing.java

License:BEER-WARE LICENSE

private byte[] ASN1EncodeKeys() throws IOException, PGPException {
    JcaPGPKeyConverter converter = new JcaPGPKeyConverter();

    PrivateKey priv = converter.getPrivateKey(kp.getPrivateKey());
    PublicKey pub = converter.getPublicKey(kp.getPublicKey());

    ASN1EncodableVector pubSeq = new ASN1EncodableVector();

    for (String jid : keys.keySet()) {
        pubSeq.add(new DERSequence(new ASN1Encodable[] { new DERUTF8String(jid),
                new DERUTF8String(nicks.get(jid)), new DERUTCTime(keys.get(jid).getCreationTime()),
                new DEROctetString(converter.getPublicKey(keys.get(jid)).getEncoded()) }));
    }/*from ww w. j a  v  a 2s.  c om*/

    DERSequence seq = new DERSequence(new ASN1Encodable[] {
            new DERSequence(new ASN1Encodable[] { new DERUTCTime(kp.getPublicKey().getCreationTime()),
                    new DEROctetString(pub.getEncoded()) }),
            new DEROctetString(priv.getEncoded()), new DERSequence(pubSeq) });

    return seq.getEncoded();
}

From source file:com.itextpdf.text.pdf.PdfPKCS7.java

License:Open Source License

private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp) {
    try {//from w  ww .  j  ava2  s  .  c o m
        ASN1EncodableVector attribute = new ASN1EncodableVector();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_CONTENT_TYPE));
        v.add(new DERSet(new DERObjectIdentifier(ID_PKCS7_DATA)));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_SIGNING_TIME));
        v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_MESSAGE_DIGEST));
        v.add(new DERSet(new DEROctetString(secondDigest)));
        attribute.add(new DERSequence(v));
        if (ocsp != null || !crls.isEmpty()) {
            v = new ASN1EncodableVector();
            v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION));

            ASN1EncodableVector revocationV = new ASN1EncodableVector();

            if (!crls.isEmpty()) {
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                for (Object element : crls) {
                    ASN1InputStream t = new ASN1InputStream(
                            new ByteArrayInputStream(((X509CRL) element).getEncoded()));
                    v2.add(t.readObject());
                }
                revocationV.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
            }

            if (ocsp != null) {
                DEROctetString doctet = new DEROctetString(ocsp);
                ASN1EncodableVector vo1 = new ASN1EncodableVector();
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
                v2.add(doctet);
                DEREnumerated den = new DEREnumerated(0);
                ASN1EncodableVector v3 = new ASN1EncodableVector();
                v3.add(den);
                v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
                vo1.add(new DERSequence(v3));
                revocationV.add(new DERTaggedObject(true, 1, new DERSequence(vo1)));
            }

            v.add(new DERSet(new DERSequence(revocationV)));
            attribute.add(new DERSequence(v));
        }

        return new DERSet(attribute);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source License

/**
 * This method provides that encoding and the parameters must be
 * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}.
 * /*from   w  w  w  .j  a  va 2s  .  c o  m*/
 * @param secondDigest the content digest
 * @param signingTime the signing time
 * @return the byte array representation of the authenticatedAttributes ready to be signed
 */
private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp,
        Collection<byte[]> crlBytes, CryptoStandard sigtype) {
    try {
        ASN1EncodableVector attribute = new ASN1EncodableVector();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE));
        v.add(new DERSet(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_SIGNING_TIME));
        v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST));
        v.add(new DERSet(new DEROctetString(secondDigest)));
        attribute.add(new DERSequence(v));
        boolean haveCrl = false;
        if (crlBytes != null) {
            for (byte[] bCrl : crlBytes) {
                if (bCrl != null) {
                    haveCrl = true;
                    break;
                }
            }
        }
        if (ocsp != null || haveCrl) {
            v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION));

            ASN1EncodableVector revocationV = new ASN1EncodableVector();

            if (haveCrl) {
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                for (byte[] bCrl : crlBytes) {
                    if (bCrl == null)
                        continue;
                    ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(bCrl));
                    v2.add(t.readObject());
                }
                revocationV.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
            }

            if (ocsp != null) {
                DEROctetString doctet = new DEROctetString(ocsp);
                ASN1EncodableVector vo1 = new ASN1EncodableVector();
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
                v2.add(doctet);
                ASN1Enumerated den = new ASN1Enumerated(0);
                ASN1EncodableVector v3 = new ASN1EncodableVector();
                v3.add(den);
                v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
                vo1.add(new DERSequence(v3));
                revocationV.add(new DERTaggedObject(true, 1, new DERSequence(vo1)));
            }

            v.add(new DERSet(new DERSequence(revocationV)));
            attribute.add(new DERSequence(v));
        }
        if (sigtype == CryptoStandard.CADES) {
            v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2));

            ASN1EncodableVector aaV2 = new ASN1EncodableVector();
            AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithmOid),
                    null);
            aaV2.add(algoId);
            MessageDigest md = interfaceDigest.getMessageDigest(getHashAlgorithm());
            byte[] dig = md.digest(signCert.getEncoded());
            aaV2.add(new DEROctetString(dig));

            v.add(new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2)))));
            attribute.add(new DERSequence(v));
        }

        return new DERSet(attribute);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:de.brendamour.jpasskit.signing.PKAbstractSIgningUtil.java

License:Apache License

protected byte[] signManifestUsingContent(PKSigningInformation signingInformation, CMSTypedData content)
        throws PKSigningException {
    if (signingInformation == null || !signingInformation.isValid()) {
        throw new IllegalArgumentException("Signing information not valid");
    }// w ww. ja  v a2s. c om

    try {
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .build(signingInformation.getSigningPrivateKey());

        final ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
        final Attribute signingAttribute = new Attribute(CMSAttributes.signingTime,
                new DERSet(new DERUTCTime(new Date())));
        signedAttributes.add(signingAttribute);

        // Create the signing table
        final AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
        // Create the table table generator that will added to the Signer builder
        final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributesTable);

        generator.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                                .setSignedAttributeGenerator(signedAttributeGenerator)
                                .build(sha1Signer, signingInformation.getSigningCert()));

        List<X509Certificate> certList = new ArrayList<X509Certificate>();
        certList.add(signingInformation.getAppleWWDRCACert());
        certList.add(signingInformation.getSigningCert());

        JcaCertStore certs = new JcaCertStore(certList);

        generator.addCertificates(certs);

        CMSSignedData sigData = generator.generate(content, false);
        return sigData.getEncoded();
    } catch (Exception e) {
        throw new PKSigningException("Error when signing manifest", e);
    }
}

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/*  w ww.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;
}

From source file:es.gob.afirma.envelopers.cms.CMSAuthenticatedData.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//w  ww  .j av a 2  s . c om
 *        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&aacute;n dentro
 *        del archivo de firma.
 * @return Los atributos firmados de la firma.
 * @throws java.security.NoSuchAlgorithmException
 *         Si no se encuentra un algoritmo v&aacute;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// w w  w  . ja va2 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.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   w w w. jav  a2  s .c om*/
 *        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));

}