Example usage for org.bouncycastle.asn1 ASN1EncodableVector add

List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector add

Introduction

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

Prototype

public void add(ASN1Encodable element) 

Source Link

Usage

From source file:de.tsenger.animamea.asn1.SecurityInfos.java

License:Open Source License

/**
 * The definition of SecurityInfos is/*  w  w w .j  ava  2s  . c o m*/
  * <pre>
  * SecurityInfos ::= SET OF SecurityInfo
  * 
  * SecurityInfo ::= SEQUENCE {
  *       protocol      OBJECT IDENTIFIER,
  *       requiredData   ANY DEFINED BY protocol,
  *       optionalData   ANY DEFINED BY protocol OPTIONAL
  * }
  * </pre>
 */
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    for (TerminalAuthenticationInfo item : terminalAuthenticationInfoList) {
        v.add(item);
    }
    for (ChipAuthenticationInfo item : chipAuthenticationInfoList) {
        v.add(item);
    }
    for (ChipAuthenticationDomainParameterInfo item : chipAuthenticationDomainParameterInfoList) {
        v.add(item);
    }
    for (ChipAuthenticationPublicKeyInfo item : chipAuthenticationPublicKeyInfoList) {
        v.add(item);
    }
    for (PaceInfo item : paceInfoList) {
        v.add(item);
    }
    for (PaceDomainParameterInfo item : paceDomainParameterInfoList) {
        v.add(item);
    }
    for (CardInfoLocator item : cardInfoLocatorList) {
        v.add(item);
    }
    for (PrivilegedTerminalInfo item : privilegedTerminalInfoList) {
        v.add(item);
    }

    return ASN1Set.getInstance(v);
}

From source file:de.tsenger.animamea.asn1.SubjectPublicKeyInfo.java

License:Open Source License

/** 
 * The SubjectPublicKeyInfo object.//from  w ww . j  a  v a 2s  . co m
 * <pre>
 * SubjectPublicKeyInfo ::= SEQUENCE {
 *   algorithm         AlgorithmIdentifier,
 *   subjectPublicKey   BIT STRING
 * }
 * </pre>
 * 
 */
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(algorithm);
    vec.add(subjectPublicKey);
    return ASN1Sequence.getInstance(vec);
}

From source file:de.tsenger.animamea.asn1.TerminalAuthenticationInfo.java

License:Open Source License

/**
 * The definition of TerminalAuthenticationInfo is
  * <pre>/*from  ww  w  . ja v  a2s  .  c om*/
  * TerminalAuthenticationInfo ::= SEQUENCE {
  *      protocol   OBJECT IDENTIFIER(id-TA),
  *      version      INTEGER, -- MUST be 1 or 2
  *      efCVCA      FileID OPTIONAL -- MUST NOT be used for version 2
  * }
  * </pre>
 */
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(protocol);
    v.add(version);
    if (fileID != null)
        v.add(fileID);

    return ASN1Sequence.getInstance(v);
}

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.//ww  w  .  jav a2  s  . c om
 *
 * 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  .j  a v  a  2 s .c  om*/
    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 getField(ECField field) throws EncodingException {
    ASN1EncodableVector v = new ASN1EncodableVector();
    if (field instanceof ECFieldFp) {
        ECFieldFp fpField = (ECFieldFp) field;
        v.add(new ASN1ObjectIdentifier("1.2.840.10045.1.1"));
        v.add(new ASN1Integer(fpField.getP()));
    } else/*from   w  w w.jav a2s . com*/
        throw new EncodingException("Only know how to encode prime fields");

    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:edu.vt.middleware.crypt.signature.AbstractDSASignature.java

License:Open Source License

/**
 * Produces DER-encoded byte array output from the raw DSA signature output
 * parameters, r and s.//from   www.  jav a  2s .  co  m
 *
 * @param  r  DSA signature output integer r.
 * @param  s  DSA signature output integer s.
 *
 * @return  DER-encoded concatenation of byte representations of r and s.
 *
 * @throws  edu.vt.middleware.crypt.CryptException  On cryptographic errors.
 */
private byte[] encode(final BigInteger r, final BigInteger s) throws CryptException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new DERInteger(r));
    v.add(new DERInteger(s));
    try {
        new DEROutputStream(out).writeObject(new DERSequence(v));
    } catch (IOException e) {
        throw new CryptException("Error encoding DSA signature.", e);
    }
    return out.toByteArray();
}

From source file:edu.vt.middleware.crypt.util.DERHelper.java

License:Open Source License

/**
 * Creates a DER SEQUENCE type from the given DER encodable objects in the
 * order they are listed./*from w w w .  j av  a 2s. c o  m*/
 *
 * @param  items  One or more DER encodable items.
 *
 * @return  DER SEQUENCE over given items.
 */
public static DERSequence sequence(final DEREncodable... items) {
    final ASN1EncodableVector v = new ASN1EncodableVector();
    for (DEREncodable item : items) {
        v.add(item);
    }
    return new DERSequence(v);
}

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

License:Open Source License

/** M&eacute;todo que genera la firma de tipo SignedAndEnvelopedData.
 * @param parameters//  w  w w .  ja  v  a 2  s  . com
 *        Par&aacute;metros necesarios para la generaci&oacute;n de este
 *        tipo.
 * @param config
 *        Configuraci&oacute;n del algoritmo para firmar
 * @param policy
 *        Pol&iacute;tica del certificado.
 * @param certDest
 *        Certificado del destino al cual va dirigido la firma.
 * @param dataType
 *        Identifica el tipo del contenido a firmar.
 * @param keyEntry
 *        Entrada a la clave de firma
 * @return Firma de tipo SignedAndEnvelopedData.
 * @throws java.io.IOException
 *         Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *         datos
 * @throws java.security.cert.CertificateEncodingException
 *         Si se produce alguna excepci&oacute;n con los certificados de
 *         firma.
 * @throws java.security.NoSuchAlgorithmException
 *         Si no se encuentra un algoritmo v&aacute;lido. */
byte[] genCADESEPESSignedAndEnvelopedData(final P7ContentSignerParameters parameters,
        final X509Certificate[] signerCertificateChain, final AOCipherConfig config, final AdESPolicy policy,
        final X509Certificate[] certDest, final String dataType, final PrivateKeyEntry keyEntry)
        throws IOException, CertificateEncodingException, NoSuchAlgorithmException {

    final SecretKey cipherKey = CAdESUtils.initEnvelopedData(config, certDest);

    // 1. VERSION
    // la version se mete en el constructor del signedAndEnvelopedData y es
    // 1

    // 2. DIGESTALGORITM
    // buscamos que timo de algoritmo es y lo codificamos con su OID

    final String signatureAlgorithm;
    final String digestAlgorithm;
    final ASN1EncodableVector digestAlgs = new ASN1EncodableVector();

    try {
        signatureAlgorithm = parameters.getSignatureAlgorithm();
        digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm);

        final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm));
        digestAlgs.add(digAlgId);
    } catch (final Exception e) {
        throw new IOException("Error de codificacion: " + e, e); //$NON-NLS-1$
    }

    // LISTA DE CERTIFICADOS: obtenemos la lista de certificados
    ASN1Set certificates = null;

    certificates = CAdESUtils.fetchCertificatesList(signerCertificateChain);

    // 2. RECIPIENTINFOS
    final Info infos = CAdESUtils.getEnvelopeInfo(parameters.getContent(), config, certDest, cipherKey);

    // 4. SIGNERINFO
    // raiz de la secuencia de SignerInfo
    final ASN1EncodableVector signerInfos = new ASN1EncodableVector();

    final TBSCertificateStructure tbs2 = TBSCertificateStructure
            .getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate()));

    final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs2.getIssuer()),
            tbs2.getSerialNumber().getValue());

    final SignerIdentifier identifier = new SignerIdentifier(encSid);

    // AlgorithmIdentifier
    final AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(
            new ASN1ObjectIdentifier(AOAlgorithmID.getOID(digestAlgorithm)), new DERNull());

    // // ATRIBUTOS
    final ASN1EncodableVector contextExpecific = CAdESUtils.generateSignerInfo(signerCertificateChain[0],
            digestAlgorithm, parameters.getContent(), policy, null);
    this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));
    final ASN1Set signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));

    // digEncryptionAlgorithm
    final AlgorithmIdentifier encAlgId;
    try {
        encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$
    } catch (final Exception e) {
        throw new IOException("Error de codificacion: " + e, e); //$NON-NLS-1$
    }

    final ASN1OctetString sign2;
    try {
        sign2 = firma(signatureAlgorithm, keyEntry);
    } catch (final AOException ex) {
        throw new IOException("Error en la firma electronica: " + ex, ex); //$NON-NLS-1$
    }

    signerInfos.add(new SignerInfo(identifier, digAlgId, signedAttr, encAlgId, sign2, null // unsignedAttr
    ));

    final ASN1Set certrevlist = null;

    // construimos el Signed And Enveloped Data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData,
            new SignedAndEnvelopedData(new DERSet(infos.getRecipientInfos()), new DERSet(digestAlgs),
                    infos.getEncInfo(), certificates, certrevlist, new DERSet(signerInfos)))
                            .getEncoded(ASN1Encoding.DER);
}