Example usage for org.bouncycastle.asn1 ASN1EncodableVector ASN1EncodableVector

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

Introduction

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

Prototype

public ASN1EncodableVector() 

Source Link

Usage

From source file:it.scoppelletti.spaceship.security.FakeCertificateFactory.java

License:Apache License

@SuppressWarnings({ "deprecation", "TryFinallyCanBeTryWithResources" })
public static X509Certificate create(PublicKey publicKey, FakeKeyPairGeneratorSpec spec)
        throws IOException, CertificateParsingException {
    ASN1ObjectIdentifier sigAlgOid;/*ww w .  jav  a  2  s .c  o  m*/
    AlgorithmIdentifier sigAlgId;
    org.bouncycastle.jce.X509Principal subject;
    ASN1EncodableVector result;
    Certificate cert;
    org.bouncycastle.jce.provider.X509CertificateObject x509Cert;
    TBSCertificate tbsCertificate;
    ASN1InputStream publicKeyInfoIn = null;
    V3TBSCertificateGenerator tbsGenerator;
    byte[] signature;

    sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
    sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
    signature = new byte[1];

    tbsGenerator = new V3TBSCertificateGenerator();
    try {
        publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded());
        tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
    } finally {
        if (publicKeyInfoIn != null) {
            publicKeyInfoIn.close();
        }
    }

    subject = new org.bouncycastle.jce.X509Principal(spec.getSubject().getEncoded());

    tbsGenerator.setSerialNumber(new ASN1Integer(spec.getSerialNumber()));
    tbsGenerator.setSubject(subject);
    tbsGenerator.setIssuer(subject);
    tbsGenerator.setStartDate(new Time(spec.getStartDate()));
    tbsGenerator.setEndDate(new Time(spec.getEndDate()));
    tbsGenerator.setSignature(sigAlgId);

    tbsCertificate = tbsGenerator.generateTBSCertificate();

    result = new ASN1EncodableVector();
    result.add(tbsCertificate);
    result.add(sigAlgId);
    result.add(new DERBitString(signature));

    cert = Certificate.getInstance(new DERSequence(result));
    x509Cert = new org.bouncycastle.jce.provider.X509CertificateObject(cert);
    return x509Cert;
}

From source file:it.trento.comune.j4sign.cms.ExternalSignatureCMSSignedDataGenerator.java

License:Open Source License

/**
 * generate a CMS Signed Data object using the previously passed {@link ExternalSignatureSignerInfoGenerator}
 * objects; if encapsulate is true a copy of the message will be
 * included in the signature.//from w  w w. j  a va2s .  co  m
 */
public CMSSignedData generate(CMSProcessable content, boolean encapsulate)

        throws NoSuchAlgorithmException, NoSuchProviderException, CMSException,
        InvalidAlgorithmParameterException, CertStoreException {

    //DEREncodableVector signerInfos = new DEREncodableVector();
    //DEREncodableVector digestAlgs = new DEREncodableVector();

    ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();

    ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(CMSSignedDataGenerator.DATA);

    //
    // add the SignerInfo objects
    //
    Iterator it = signerInfs.iterator();

    //raccoglier i certificati dei firmatari
    //ArrayList certList = new ArrayList();

    while (it.hasNext()) {
        AlgorithmIdentifier digAlgId, encAlgId;
        ExternalSignatureSignerInfoGenerator externalSigner = (ExternalSignatureSignerInfoGenerator) it.next();
        try {
            digAlgId = makeAlgId(externalSigner.getDigestAlgOID(), externalSigner.getDigestAlgParams());

            digestAlgs.add(digAlgId);

            signerInfos.add(externalSigner.generate());

            //certList.add(externalSigner.getCertificate());
        } catch (IOException e) {
            throw new CMSException("encoding error.", e);
        } catch (CertificateEncodingException e) {
            throw new CMSException("error creating sid.", e);
        }
    }

    ASN1Set certificates = null;

    if (certs.size() != 0) {
        certificates = createBerSetFromList(certs);
    }
    /*
            if (certs.size() != 0) {
    DEREncodableVector v = new DEREncodableVector();
            
    it = certs.iterator();
    while (it.hasNext()) {
        v.add((DEREncodable) it.next());
    }
            
    certificates = new DERSet(v);
            }
    */
    ASN1Set certrevlist = null;

    if (crls.size() != 0) {
        certrevlist = createBerSetFromList(crls);
    }
    /*        
            if (crls.size() != 0) {
    DEREncodableVector v = new DEREncodableVector();
            
    it = crls.iterator();
    while (it.hasNext()) {
        v.add((DEREncodable) it.next());
    }
            
    certrevlist = new DERSet(v);
            }
    */

    ASN1OctetString octs = null;
    if (encapsulate) {

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        try {
            content.write(bOut);
        } catch (IOException e) {
            throw new CMSException("encapsulation error.", e);
        }

        octs = new BERConstructedOctetString(bOut.toByteArray());

    }

    ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);

    SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist,
            new DERSet(signerInfos));

    ContentInfo contentInfo = new ContentInfo(PKCSObjectIdentifiers.signedData, sd);

    return new CMSSignedData(content, contentInfo);
}

From source file:it.trento.comune.j4sign.cms.ExternalSignatureCMSSignedDataGenerator.java

License:Open Source License

static ASN1Set createBerSetFromList(List derObjects) {
    ASN1EncodableVector v = new ASN1EncodableVector();

    for (Iterator it = derObjects.iterator(); it.hasNext();) {
        v.add((DEREncodable) it.next());
    }// www. jav a2 s. co m

    return new BERSet(v);
}

From source file:it.trento.comune.j4sign.cms.ExternalSignatureSignerInfoGenerator.java

License:Open Source License

/**
 * Calculates the bytes to be externally signed (digested and encrypted with
 * signer private key).<br>/*from w  w  w. java2  s. c o m*/
 * The bytes are the DER encoding of authenticated attributes; the current
 * implementation includes this attributes:
 * <ul>
 * <li><b>content Type</b></li> of the provided content.
 * <li><b>message Digest</b></li> of the content, calculated in this method
 * with the algorithm specified in the class constructor.
 * <li><b>signing Time</b>. Note that time (internally stored as UTC) should
 * be presented to the signer BEFORE applying the external signature
 * procedure.<br>
 * This time has not to be confused with a thirdy part (Certification
 * Authority) certified timestamp ("Marcatura Temporale" in italian
 * terminology); for the italian digital signature law this attribute is not
 * mandatory and could be omitted. Nevertheless, the italian law states also
 * that the signature is valid if the certificate is not expired nor
 * suspended at the time of signature. So an indication of signing time is
 * (in my opinion) however useful.</li>
 * </ul>
 * 
 * 
 * @param contentType
 *            the <code>org.bouncycastle.asn1.DERObjectIdentifier</code> of
 *            the content.
 * @param hash
 *            the content hash.
 * @param sigProvider
 *            the cryptographic provider to use for calculating the digest
 *            of the content.
 * @return a <code>byte[]</code> containing the raw bytes to be signed.
 * @throws IOException
 * @throws SignatureException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 * @throws CMSException
 */

public byte[] getBytesToSign(DERObjectIdentifier contentType, byte[] hash, Date signingDate, String sigProvider)
        throws IOException, SignatureException, InvalidKeyException, NoSuchProviderException,
        NoSuchAlgorithmException, CertificateEncodingException, CMSException {

    if (signingDate == null)
        signingDate = new Date();

    AttributeTable attr = this.getSignedAttributes();

    if (attr != null) {
        ASN1EncodableVector v = new ASN1EncodableVector();

        if (attr.get(CMSAttributes.contentType) == null) {
            v.add(new Attribute(CMSAttributes.contentType, new DERSet(contentType)));
        } else {
            v.add(attr.get(CMSAttributes.contentType));
        }

        if (attr.get(CMSAttributes.signingTime) == null) {
            v.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(signingDate))));
        } else {
            v.add(attr.get(CMSAttributes.signingTime));
        }

        v.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(hash))));

        // CAdES!
        v.add(buildSigningCertificateV2Attribute(sigProvider));

        Hashtable ats = attr.toHashtable();

        ats.remove(CMSAttributes.contentType);
        ats.remove(CMSAttributes.signingTime);
        ats.remove(CMSAttributes.messageDigest);
        ats.remove(PKCSObjectIdentifiers.id_aa_signingCertificateV2);

        Iterator it = ats.values().iterator();

        while (it.hasNext()) {
            v.add(Attribute.getInstance(it.next()));
        }

        signedAttr = new DERSet(v);

    } else {
        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(new Attribute(CMSAttributes.contentType, new DERSet(contentType)));

        v.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(signingDate))));

        v.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(hash))));

        // CAdES!
        v.add(buildSigningCertificateV2Attribute(sigProvider));

        signedAttr = new DERSet(v);

    }

    attr = this.getUnsignedAttributes();

    if (attr != null) {
        Hashtable ats = attr.toHashtable();
        Iterator it = ats.values().iterator();
        ASN1EncodableVector v = new ASN1EncodableVector();

        while (it.hasNext()) {
            v.add(Attribute.getInstance(it.next()));
        }

        unsignedAttr = new DERSet(v);
    }

    //
    // sig must be composed from the DER encoding.
    //
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);

    dOut.writeObject(signedAttr);

    return bOut.toByteArray();

}

From source file:jcifs.spnego.NegTokenInit.java

License:Open Source License

@Override
public byte[] toByteArray() {
    try {//from  w w w  .  ja v  a 2 s  .  c o m
        ASN1EncodableVector fields = new ASN1EncodableVector();
        Oid[] mechs = getMechanisms();
        if (mechs != null) {
            ASN1EncodableVector vector = new ASN1EncodableVector();
            for (int i = 0; i < mechs.length; i++) {
                vector.add(ASN1ObjectIdentifier.getInstance(mechs[i].getDER()));
            }
            fields.add(new DERTaggedObject(true, 0, new DERSequence(vector)));
        }
        int ctxFlags = getContextFlags();
        if (ctxFlags != 0) {
            fields.add(new DERTaggedObject(true, 1, new DERBitString(ctxFlags)));
        }
        byte[] mechanismToken = getMechanismToken();
        if (mechanismToken != null) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if (mechanismListMIC != null) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }

        ASN1EncodableVector ev = new ASN1EncodableVector();
        ev.add(SPNEGO_OID);
        ev.add(new DERTaggedObject(true, 0, new DERSequence(fields)));
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        DERApplicationSpecific derApplicationSpecific = new DERApplicationSpecific(0, ev);
        der.writeObject(derApplicationSpecific);
        return collector.toByteArray();
    } catch (IOException | GSSException ex) {
        throw new IllegalStateException(ex.getMessage());
    }
}

From source file:jcifs.spnego.NegTokenTarg.java

License:Open Source License

@Override
public byte[] toByteArray() {
    try {/*from  w ww.j ava  2 s.c  o  m*/
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        ASN1EncodableVector fields = new ASN1EncodableVector();
        int res = getResult();
        if (res != UNSPECIFIED_RESULT) {
            fields.add(new DERTaggedObject(true, 0, ASN1Enumerated.getInstance(res)));
        }
        Oid mech = getMechanism();
        if (mech != null) {
            fields.add(new DERTaggedObject(true, 1, ASN1ObjectIdentifier.getInstance(mech.getDER())));
        }
        byte[] mechanismToken = getMechanismToken();
        if (mechanismToken != null) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if (mechanismListMIC != null) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }
        der.writeObject(new DERTaggedObject(true, 1, new DERSequence(fields)));
        return collector.toByteArray();
    } catch (IOException | GSSException ex) {
        throw new IllegalStateException(ex.getMessage());
    }
}

From source file:me.it_result.ca.bouncycastle.StandardProfile.java

License:Open Source License

@Override
public PKCS10CertificationRequest generateCsr(KeyPair keyPair, CertificateParameters certificateParameters,
        String signatureAlgorithm) throws Exception {
    if (!isCompatible(certificateParameters))
        throw new CAException("Certificate parameters are not compatible with profile");
    CertificateParametersBase params = (CertificateParametersBase) certificateParameters;
    ASN1EncodableVector attributeVector = new ASN1EncodableVector();
    // challengePassword
    if (params.getChallengePassword() != null) {
        Attribute passwordAttribute = Utils.generateChallengePasswordAttribute(params.getChallengePassword());
        attributeVector.add(passwordAttribute);
    }//from   ww  w.  j av a2  s.  co  m
    String profileId = certificateParameters instanceof ServerCertificateParameters ? SERVER_PROFILE
            : CLIENT_PROFILE;
    Attribute profileIdAttribute = Utils.generateProfileIdAttribute(profileId);
    attributeVector.add(profileIdAttribute);
    DERSet attributes = new DERSet(attributeVector);
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm,
            new X509Name(certificateParameters.getSubjectDN()), keyPair.getPublic(), attributes,
            keyPair.getPrivate());
    return csr;
}

From source file:me.it_result.ca.bouncycastle.Utils.java

License:Open Source License

public static Attribute generateChallengePasswordAttribute(String challengePassword) {
    ASN1EncodableVector passwordVector = new ASN1EncodableVector();
    passwordVector.add(new DERPrintableString(challengePassword));
    Attribute passwordAttribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
            new DERSet(passwordVector));
    return passwordAttribute;
}

From source file:mitm.common.security.asn1.ASN1Utils.java

License:Open Source License

public static ASN1EncodableVector toASN1EncodableVector(X500Principal principal) throws IOException {
    final ASN1InputStream stream = new ASN1InputStream(principal.getEncoded());
    final ASN1Object der = stream.readObject();

    Enumeration<?> e = ASN1Sequence.getInstance(der).getObjects();

    ASN1EncodableVector v = new ASN1EncodableVector();

    while (e.hasMoreElements()) {
        Object o = e.nextElement();

        if (o instanceof ASN1Encodable) {
            v.add((ASN1Encodable) o);//from  ww  w .  ja v  a  2s  .c  o m
        }
    }

    stream.close();
    return v;
}

From source file:mitm.common.security.asn1.DERUtils.java

License:Open Source License

/**
 * Bouncycastle DERSet sorts the entries in the set (required by DER encoding) but uses a slow
 * sort method. You can use this method to do a pre-sort using a faster method before creating
 * the DERSet.//from   w  ww  . j a va2s  .  c  o  m
 * @param asn1Certificates
 * @return
 * @throws IOException
 */
public static ASN1EncodableVector sortASN1EncodableVector(ASN1EncodableVector asn1Certificates)
        throws IOException {
    ASN1EncodableVector sorted = new ASN1EncodableVector();

    List<DEREntry> sortingList = new Vector<DEREntry>(asn1Certificates.size());

    for (int i = 0; i < asn1Certificates.size(); i++) {
        DEREntry entry = new DEREntry(asn1Certificates.get(i));
        sortingList.add(entry);
    }

    Collections.sort(sortingList);

    for (DEREntry entry : sortingList) {
        sorted.add(entry.derEncodable);
    }

    return sorted;
}