Example usage for org.bouncycastle.asn1 DERGeneralString DERGeneralString

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

Introduction

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

Prototype

public DERGeneralString(String string) 

Source Link

Document

Construct a GeneralString from the passed in String.

Usage

From source file:AAModulePackage.ACHelper.java

public static X509AttributeCertificateHolder generateAttributeCertificate(X509CertificateHolder issuerCert,
        X509CertificateHolder associatedCert, PrivateKey pk, String role, String record_id,
        String record_subject, String[] record_types, String[] actions_taken) {
    //Set up the validity period.
    Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000);

    //AttributeCertificateHolder is a wrapper class for AttributeCertificates, courtesy of the Legion of Bouncy Castle.
    AttributeCertificateIssuer certIssuer = new AttributeCertificateIssuer(issuerCert.getSubject());

    /*/*  ww  w . j a  v  a  2s. c om*/
    Please note the distinction between AttributeCertificateHolder which appears to be the
    Entity in possession of the certificate, while X509AttributeCertificateHolder is a
    wrapper class for the actual certificate itself.
     */

    AttributeCertificateHolder holder = new AttributeCertificateHolder(associatedCert);
    X509v2AttributeCertificateBuilder builder = new X509v2AttributeCertificateBuilder(holder, certIssuer,
            BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate);

    builder.addAttribute(NewAttributeIdentifiers.role, new DERGeneralString(role));
    builder.addAttribute(NewAttributeIdentifiers.record_id, new DERGeneralString(record_id));
    builder.addAttribute(NewAttributeIdentifiers.record_subject, new DERGeneralString(record_subject));
    builder.addAttribute(NewAttributeIdentifiers.time_stamp, new DERGeneralizedTime(new Date()));

    //record_types
    ArrayList<ASN1Encodable> rts = new ArrayList();
    for (String s : record_types) {
        rts.add(new DERGeneralString(s));
    }
    ASN1Encodable[] recTypes = rts.toArray(new DERGeneralString[rts.size()]);

    builder.addAttribute(NewAttributeIdentifiers.record_type, recTypes);

    //actions_taken
    ArrayList<ASN1Encodable> acts = new ArrayList();
    for (String s : actions_taken) {
        acts.add(new DERGeneralString(s));
    }
    ASN1Encodable[] actionsTaken = acts.toArray(new DERGeneralString[acts.size()]);
    builder.addAttribute(NewAttributeIdentifiers.actions_taken, actionsTaken);

    //Build the certificate
    X509AttributeCertificateHolder attrCert = null;
    try {
        //builds the attribute certificate, and signs it with the owner's private key.
        attrCert = builder
                .build(new JcaContentSignerBuilder("SHA256withRSAEncryption").setProvider("BC").build(pk));
    } catch (OperatorCreationException e) {
        e.printStackTrace();
    }

    System.out.println("ATTRIBUTE CERTIFICATE Successfully generated.");

    return attrCert;
}

From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

public ArrayList<String> getVOMSFQANs() throws Exception {
    ArrayList<String> theseFQANs = new ArrayList<String>();
    try {//from w w  w . j a  v  a  2s  .c o  m
        // could have more than one AC in here...
        for (Enumeration a = this.attributes.getObjects(); a.hasMoreElements();) {

            ASN1Sequence sequence = (ASN1Sequence) a.nextElement();
            // sequence contains the OID [voms 4] (as a DERObjectIdentifier) at address 0 , and an SET at address 1

            ASN1Set set = (ASN1Set) sequence.getObjectAt(1);
            // set contains only a SEQUENCE at address 0

            ASN1Sequence sequence2 = (ASN1Sequence) set.getObjectAt(0);
            // sequence2 contains a TAGGED OBJECT ad address 0 and another SEQUENCE at address 1

            ASN1TaggedObject taggedObject = (ASN1TaggedObject) sequence2.getObjectAt(0);
            // dig down the tagged object... (undocumented?) - TagNumber value is 0

            ASN1TaggedObject taggedObject2 = (ASN1TaggedObject) taggedObject.getObject();
            // this tagged object has TagNumber value of 6 (?)
            ASN1OctetString originOctetString = (ASN1OctetString) taggedObject2.getObject();
            String origin = (new DERGeneralString(originOctetString.getOctets())).getString();

            ASN1Sequence fqanSequence = (ASN1Sequence) sequence2.getObjectAt(1);
            // this is the actual sequence of FQANs

            for (int fqan = 0; fqan < fqanSequence.size(); fqan++) {
                ASN1OctetString fqanOctetString = (ASN1OctetString) fqanSequence.getObjectAt(fqan);
                String FQAN_Value = (new DERGeneralString(fqanOctetString.getOctets())).getString();
                theseFQANs.add(FQAN_Value);
            }
        }
    } catch (Exception e) {
        throw e;
    }

    return theseFQANs;
}

From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

public void setVOMSFQANs(String[] fqans) throws Exception {
    try {//from  w  w  w .j a  v  a  2s  .  c  om
        //--------------------------------------------------------------------------
        // put the FQANs into the SEQUENCE

        DEREncodableVector fqanVector = new ASN1EncodableVector();

        for (int f = 0; f < fqans.length; f++) {
            DERGeneralString fqan = new DERGeneralString(fqans[f]);
            ASN1OctetString fqanOctetString = ASN1OctetString.getInstance(new DEROctetString(fqan.getOctets()));
            fqanVector.add(fqanOctetString);
        }

        ASN1Sequence fqanSequence = ASN1Sequence.getInstance(new DERSequence(fqanVector));

        //--------------------------------------------------------------------------
        // put something into the undocumented TaggedObject

        DERGeneralString origin = new DERGeneralString("gridportal://newvoms:15000");

        ASN1OctetString originOctetString = ASN1OctetString.getInstance(new DEROctetString(origin.getOctets()));

        /*
         ASN1TaggedObject taggedObject2 = ASN1TaggedObject.getInstance( new DERTaggedObject( 6 , originOctetString ) , true ) ;
                
         ASN1TaggedObject taggedObject = ASN1TaggedObject.getInstance( new DERTaggedObject( 0 , taggedObject2 ) , true ) ;
                
         DEROctetString originOctetString = new DEROctetString( origin.getOctets() ) ;
         */

        DERTaggedObject taggedObject2 = new DERTaggedObject(6, originOctetString);

        DERTaggedObject taggedObject = new DERTaggedObject(0, taggedObject2);

        //--------------------------------------------------------------------------
        // put the taggedObject and then the fqanSequence into sequence2

        DEREncodableVector sequence2Vector = new ASN1EncodableVector();
        sequence2Vector.add(taggedObject);
        sequence2Vector.add(fqanSequence);
        ASN1Sequence sequence2 = ASN1Sequence.getInstance(new DERSequence(sequence2Vector));

        //--------------------------------------------------------------------------
        // the SET has one member - sequence2

        ASN1Set set = ASN1Set.getInstance(new DERSet(sequence2));

        //--------------------------------------------------------------------------
        // SEQUENCE sequence has an OID and the set

        DERObjectIdentifier voms4oid = new DERObjectIdentifier("1.3.6.1.4.1.8005.100.100.4");

        DEREncodableVector sequenceVector = new ASN1EncodableVector();
        sequenceVector.add(voms4oid);
        sequenceVector.add(set);
        ASN1Sequence sequence = ASN1Sequence.getInstance(new DERSequence(sequenceVector));

        //--------------------------------------------------------------------------

        this.attributes = ASN1Sequence.getInstance(new DERSequence(sequence));

    } catch (Exception e) {
        throw e;
    }

}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * From an altName string as defined in getSubjectAlternativeName
 * /* w  w w  . jav  a  2 s.com*/
 * @param altName
 * @return ASN.1 GeneralNames
 * @see #getSubjectAlternativeName
 */
public static GeneralNames getGeneralNamesFromAltName(final String altName) {
    if (log.isTraceEnabled()) {
        log.trace(">getGeneralNamesFromAltName: " + altName);
    }
    final ASN1EncodableVector vec = new ASN1EncodableVector();

    for (final String email : CertTools.getEmailFromDN(altName)) {
        vec.add(new GeneralName(1, /*new DERIA5String(iter.next())*/email));
    }

    for (final String dns : CertTools.getPartsFromDN(altName, CertTools.DNS)) {
        vec.add(new GeneralName(2, new DERIA5String(dns)));
    }

    final String directoryName = getDirectoryStringFromAltName(altName);
    if (directoryName != null) {
        //final X500Name x500DirectoryName = new X500Name(directoryName);
        final X500Name x500DirectoryName = new X500Name(LDAPDN.unescapeRDN(directoryName));
        final GeneralName gn = new GeneralName(4, x500DirectoryName);
        vec.add(gn);
    }

    for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI)) {
        vec.add(new GeneralName(6, new DERIA5String(uri)));
    }
    for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI1)) {
        vec.add(new GeneralName(6, new DERIA5String(uri)));
    }
    for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI2)) {
        vec.add(new GeneralName(6, new DERIA5String(uri)));
    }

    for (final String addr : CertTools.getPartsFromDN(altName, CertTools.IPADDR)) {
        final byte[] ipoctets = StringTools.ipStringToOctets(addr);
        if (ipoctets.length > 0) {
            final GeneralName gn = new GeneralName(7, new DEROctetString(ipoctets));
            vec.add(gn);
        } else {
            log.error("Cannot parse/encode ip address, ignoring: " + addr);
        }
    }

    // UPN is an OtherName see method getUpn... for asn.1 definition
    for (final String upn : CertTools.getPartsFromDN(altName, CertTools.UPN)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(CertTools.UPN_OBJECTID));
        v.add(new DERTaggedObject(true, 0, new DERUTF8String(upn)));
        vec.add(GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v))));
    }

    // PermanentIdentifier is an OtherName see method getPermananentIdentifier... for asn.1 definition
    for (final String permanentIdentifier : CertTools.getPartsFromDN(altName, CertTools.PERMANENTIDENTIFIER)) {
        final String[] values = getPermanentIdentifierValues(permanentIdentifier);
        final ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName
        v.add(new ASN1ObjectIdentifier(CertTools.PERMANENTIDENTIFIER_OBJECTID));
        // First the PermanentIdentifier sequence
        final ASN1EncodableVector piSeq = new ASN1EncodableVector();
        if (values[0] != null) {
            piSeq.add(new DERUTF8String(values[0]));
        }
        if (values[1] != null) {
            piSeq.add(new ASN1ObjectIdentifier(values[1]));
        }
        v.add(new DERTaggedObject(true, 0, new DERSequence(piSeq)));
        // GeneralName gn = new GeneralName(new DERSequence(v), 0);
        final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v));
        vec.add(gn);
    }

    for (final String guid : CertTools.getPartsFromDN(altName, CertTools.GUID)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        byte[] guidbytes = Hex.decode(guid);
        if (guidbytes != null) {
            v.add(new ASN1ObjectIdentifier(CertTools.GUID_OBJECTID));
            v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes)));
            final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        } else {
            log.error("Cannot decode hexadecimal guid, ignoring: " + guid);
        }
    }

    // Krb5PrincipalName is an OtherName, see method getKrb5Principal...for ASN.1 definition
    for (final String principalString : CertTools.getPartsFromDN(altName, CertTools.KRB5PRINCIPAL)) {
        // Start by parsing the input string to separate it in different parts
        if (log.isDebugEnabled()) {
            log.debug("principalString: " + principalString);
        }
        // The realm is the last part moving back until an @
        final int index = principalString.lastIndexOf('@');
        String realm = "";
        if (index > 0) {
            realm = principalString.substring(index + 1);
        }
        if (log.isDebugEnabled()) {
            log.debug("realm: " + realm);
        }
        // Now we can have several principals separated by /
        final ArrayList<String> principalarr = new ArrayList<String>();
        int jndex = 0;
        int bindex = 0;
        while (jndex < index) {
            // Loop and add all strings separated by /
            jndex = principalString.indexOf('/', bindex);
            if (jndex == -1) {
                jndex = index;
            }
            String s = principalString.substring(bindex, jndex);
            if (log.isDebugEnabled()) {
                log.debug("adding principal name: " + s);
            }
            principalarr.add(s);
            bindex = jndex + 1;
        }

        // Now we must construct the rather complex asn.1...
        final ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName
        v.add(new ASN1ObjectIdentifier(CertTools.KRB5PRINCIPAL_OBJECTID));

        // First the Krb5PrincipalName sequence
        final ASN1EncodableVector krb5p = new ASN1EncodableVector();
        // The realm is the first tagged GeneralString
        krb5p.add(new DERTaggedObject(true, 0, new DERGeneralString(realm)));
        // Second is the sequence of principal names, which is at tagged position 1 in the krb5p
        final ASN1EncodableVector principals = new ASN1EncodableVector();
        // According to rfc4210 the type NT-UNKNOWN is 0, and according to some other rfc this type should be used...
        principals.add(new DERTaggedObject(true, 0, new ASN1Integer(0)));
        // The names themselves are yet another sequence
        final Iterator<String> i = principalarr.iterator();
        final ASN1EncodableVector names = new ASN1EncodableVector();
        while (i.hasNext()) {
            String principalName = (String) i.next();
            names.add(new DERGeneralString(principalName));
        }
        principals.add(new DERTaggedObject(true, 1, new DERSequence(names)));
        krb5p.add(new DERTaggedObject(true, 1, new DERSequence(principals)));

        v.add(new DERTaggedObject(true, 0, new DERSequence(krb5p)));
        final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v));
        vec.add(gn);
    }

    // To support custom OIDs in altNames, they must be added as an OtherName of plain type UTF8String
    for (final String oid : CertTools.getCustomOids(altName)) {
        for (final String oidValue : CertTools.getPartsFromDN(altName, oid)) {
            final ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(oid));
            v.add(new DERTaggedObject(true, 0, new DERUTF8String(oidValue)));
            final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    if (vec.size() > 0) {
        return GeneralNames.getInstance(new DERSequence(vec));
    }
    return null;
}

From source file:org.ejbca.util.CertTools.java

License:Open Source License

/**
 * From an altName string as defined in getSubjectAlternativeName 
 * @param altName//w w  w . jav  a2 s.  co  m
 * @return ASN.1 GeneralNames
 * @see #getSubjectAlternativeName
 */
public static GeneralNames getGeneralNamesFromAltName(String altName) {
    if (log.isTraceEnabled()) {
        log.trace(">getGeneralNamesFromAltName: " + altName);
    }
    ASN1EncodableVector vec = new ASN1EncodableVector();

    ArrayList<String> emails = CertTools.getEmailFromDN(altName);
    if (!emails.isEmpty()) {
        Iterator<String> iter = emails.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(1, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    ArrayList<String> dns = CertTools.getPartsFromDN(altName, CertTools.DNS);
    if (!dns.isEmpty()) {
        Iterator<String> iter = dns.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(2, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    String directoryName = getDirectoryStringFromAltName(altName);
    if (directoryName != null) {
        X509Name x509DirectoryName = new X509Name(directoryName);
        GeneralName gn = new GeneralName(4, x509DirectoryName);
        vec.add(gn);
    }

    ArrayList<String> uri = CertTools.getPartsFromDN(altName, CertTools.URI);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }
    uri = CertTools.getPartsFromDN(altName, CertTools.URI1);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }
    uri = CertTools.getPartsFromDN(altName, CertTools.URI2);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    ArrayList<String> ipstr = CertTools.getPartsFromDN(altName, CertTools.IPADDR);
    if (!ipstr.isEmpty()) {
        Iterator<String> iter = ipstr.iterator();
        while (iter.hasNext()) {
            byte[] ipoctets = StringTools.ipStringToOctets((String) iter.next());
            GeneralName gn = new GeneralName(7, new DEROctetString(ipoctets));
            vec.add(gn);
        }
    }

    // UPN is an OtherName see method getUpn... for asn.1 definition
    ArrayList<String> upn = CertTools.getPartsFromDN(altName, CertTools.UPN);
    if (!upn.isEmpty()) {
        Iterator<String> iter = upn.iterator();
        while (iter.hasNext()) {
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERObjectIdentifier(CertTools.UPN_OBJECTID));
            v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) iter.next())));
            //GeneralName gn = new GeneralName(new DERSequence(v), 0);
            DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    ArrayList<String> guid = CertTools.getPartsFromDN(altName, CertTools.GUID);
    if (!guid.isEmpty()) {
        Iterator<String> iter = guid.iterator();
        while (iter.hasNext()) {
            ASN1EncodableVector v = new ASN1EncodableVector();
            byte[] guidbytes = Hex.decode((String) iter.next());
            if (guidbytes != null) {
                v.add(new DERObjectIdentifier(CertTools.GUID_OBJECTID));
                v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes)));
                DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
                vec.add(gn);
            } else {
                log.error("Cannot decode hexadecimal guid: " + guid);
            }
        }
    }

    // Krb5PrincipalName is an OtherName, see method getKrb5Principal...for ASN.1 definition
    ArrayList<String> krb5principalname = CertTools.getPartsFromDN(altName, CertTools.KRB5PRINCIPAL);
    if (!krb5principalname.isEmpty()) {
        Iterator<String> iter = krb5principalname.iterator();
        while (iter.hasNext()) {
            // Start by parsing the input string to separate it in different parts
            String principalString = (String) iter.next();
            if (log.isDebugEnabled()) {
                log.debug("principalString: " + principalString);
            }
            // The realm is the last part moving back until an @
            int index = principalString.lastIndexOf('@');
            String realm = "";
            if (index > 0) {
                realm = principalString.substring(index + 1);
            }
            if (log.isDebugEnabled()) {
                log.debug("realm: " + realm);
            }
            // Now we can have several principals separated by /
            ArrayList<String> principalarr = new ArrayList<String>();
            int jndex = 0;
            int bindex = 0;
            while (jndex < index) {
                // Loop and add all strings separated by /
                jndex = principalString.indexOf('/', bindex);
                if (jndex == -1) {
                    jndex = index;
                }
                String s = principalString.substring(bindex, jndex);
                if (log.isDebugEnabled()) {
                    log.debug("adding principal name: " + s);
                }
                principalarr.add(s);
                bindex = jndex + 1;
            }

            // Now we must construct the rather complex asn.1...
            ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName
            v.add(new DERObjectIdentifier(CertTools.KRB5PRINCIPAL_OBJECTID));

            // First the Krb5PrincipalName sequence
            ASN1EncodableVector krb5p = new ASN1EncodableVector();
            // The realm is the first tagged GeneralString
            krb5p.add(new DERTaggedObject(true, 0, new DERGeneralString(realm)));
            // Second is the sequence of principal names, which is at tagged position 1 in the krb5p 
            ASN1EncodableVector principals = new ASN1EncodableVector();
            // According to rfc4210 the type NT-UNKNOWN is 0, and according to some other rfc this type should be used...
            principals.add(new DERTaggedObject(true, 0, new DERInteger(0)));
            // The names themselves are yet another sequence
            Iterator<String> i = principalarr.iterator();
            ASN1EncodableVector names = new ASN1EncodableVector();
            while (i.hasNext()) {
                String principalName = (String) i.next();
                names.add(new DERGeneralString(principalName));
            }
            principals.add(new DERTaggedObject(true, 1, new DERSequence(names)));
            krb5p.add(new DERTaggedObject(true, 1, new DERSequence(principals)));

            v.add(new DERTaggedObject(true, 0, new DERSequence(krb5p)));
            DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    // To support custom OIDs in altNames, they must be added as an OtherName of plain type UTF8String
    ArrayList<String> customoids = CertTools.getCustomOids(altName);
    if (!customoids.isEmpty()) {
        Iterator<String> iter = customoids.iterator();
        while (iter.hasNext()) {
            String oid = (String) iter.next();
            ArrayList<String> oidval = CertTools.getPartsFromDN(altName, oid);
            if (!oidval.isEmpty()) {
                Iterator<String> valiter = oidval.iterator();
                while (valiter.hasNext()) {
                    ASN1EncodableVector v = new ASN1EncodableVector();
                    v.add(new DERObjectIdentifier(oid));
                    v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) valiter.next())));
                    DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
                    vec.add(gn);
                }
            }
        }
    }

    GeneralNames ret = null;
    if (vec.size() > 0) {
        ret = new GeneralNames(new DERSequence(vec));
    }
    return ret;
}

From source file:org.sinekartads.core.pdf.PDFTools.java

License:Open Source License

public static FinalizedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> sign(
        SignedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> signedSignature,
        //                                   X509Certificate certificate, 
        InputStream is, OutputStream os) throws SignatureException {
    ////      signAndMark(doc, certificate, is, os, null, null, null, null, null);
    //      signAndMark(signatureInfo, certificate, is, os, null, null, null);
    //   }//from w w w  .  jav a  2  s .  c  o m
    //
    //   public static void signAndMark(PDFSignatureInfo doc,
    //         X509Certificate certificate, InputStream is, OutputStream os,
    //         String tsaUrl, String tsaUser, String tsaPassword) {
    ////      signAndMark(doc, certificate, is, os, tsaUrl, tsaUser, tsaPassword, null, null);
    ////   }
    ////   
    ////   public static void signAndMark(DigitalSignatureDocument doc,
    ////         X509Certificate certificate, InputStream is, OutputStream os,
    ////         String tsaUrl, String tsaUser, String tsaPassword, Collection<CrlClient> crlList, OcspClient ocspClient) {
    try {
        PDFSignatureInfo signature = (PDFSignatureInfo) signedSignature;
        TSAClient tsaClient = null;

        TsRequestInfo tsRequest = signature.getTsRequest();
        if (tsRequest != null && StringUtils.isNotBlank(tsRequest.getTsUrl())) {
            tsaClient = new TSAClientBouncyCastle(tsRequest.getTsUrl(), tsRequest.getTsUsername(),
                    tsRequest.getTsPassword());
        }
        //         if (tsaUrl!=null) {
        //            tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPassword);
        //         }

        int estimatedSize = 0;
        CryptoStandard sigtype = CryptoStandard.CMS;

        // creo il reader del pdf
        PdfReader reader = new PdfReader(is);

        // creo lo stamper (se il pdf e' gia' firmato, controfirma,
        // altrimenti firma
        PdfStamper stamper = null;
        if (isPdfSigned(reader)) {
            if (tracer.isDebugEnabled())
                tracer.debug("document already signed, i will apply another sign");
            stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
        } else {
            if (tracer.isDebugEnabled())
                tracer.debug("document never signed before, this is first");
            stamper = PdfStamper.createSignature(reader, os, '\0');
        }

        // questo e' il certificato su cui lavorare
        Certificate[] chain = signature.getRawX509Certificates();
        //         Certificate[] chain = new Certificate[1];
        //         chain[0] = certificate;

        // creo la signature apparence
        PdfSignatureAppearance sap = stamper.getSignatureAppearance();
        ExternalDigest externalDigest = new BouncyCastleDigest();

        // inizio codice copiato da MakeSignature

        //         Collection<byte[]> crlBytes = null;
        //           int i = 0;
        //           while (crlBytes == null && i < chain.length)
        //              crlBytes = MakeSignature.processCrl(chain[i++], crlList);
        if (estimatedSize == 0) {
            estimatedSize = 8192;
            //               if (crlBytes != null) {
            //                   for (byte[] element : crlBytes) {
            //                       estimatedSize += element.length + 10;
            //                   }
            //               }
            //               if (ocspClient != null)
            estimatedSize += 4192;
            //               if (tsaClient != null)
            estimatedSize += 4192;
        }
        sap.setCertificate(chain[0]);
        sap.setReason(signature.getReason());
        sap.setLocation(signature.getLocation());

        Calendar cal = Calendar.getInstance();
        cal.setTime(signature.getSigningTime());
        sap.setSignDate(cal);
        sap.getStamper().setUnicodeModDate(signature.getUnicodeModDate());
        sap.getStamper().setFileId(signature.getFileId());

        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(new PdfDate(sap.getSignDate())); // time-stamp will over-rule this
        sap.setCryptoDictionary(dic);

        HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
        exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));
        sap.preClose(exc);

        String hashAlgorithm = signature.getDigestAlgorithm().getName();
        PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, BouncyCastleProvider.PROVIDER_NAME,
                externalDigest, false);
        InputStream data = sap.getRangeStream();
        byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm));
        //           byte[] ocsp = null;
        //           if (chain.length >= 2 && ocspClient != null) {
        //               ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null);
        //           }
        sgn.setExternalDigest(signature.getDigitalSignature(), null, "RSA");

        //           byte[] encodedSig = sgn.getEncodedPKCS7(hash, _getSignDate(doc.getSignDate()), tsaClient, ocsp, crlBytes, sigtype);
        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsaClient, null, null, sigtype);

        if (estimatedSize + 2 < encodedSig.length)
            throw new IOException("Not enough space");

        ASN1EncodableVector extraDataVectorEncoding = new ASN1EncodableVector();
        // 
        extraDataVectorEncoding.add(new DERObjectIdentifier("1.2.840.114283")); // encoding attribute 
        extraDataVectorEncoding.add(new DERGeneralString("115.105.110.101.107.97.114.116.97"));

        // applico la firma al PDF
        byte[] extraDataVectorEncodingBytes = new DERSequence(new DERSequence(extraDataVectorEncoding))
                .getEncoded();

        byte[] paddedSig = new byte[estimatedSize];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
        System.arraycopy(extraDataVectorEncodingBytes, 0, paddedSig, encodedSig.length,
                extraDataVectorEncodingBytes.length); // encoding attribute

        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
        sap.close(dic2);

        // this should be already done, but ...
        // closing streams
        try {
            is.close();
        } catch (IOException e) {
            tracer.error("error on input stream", e);
        }
        try {
            os.flush();
        } catch (IOException e) {
            tracer.error("error on output stream", e);
        }
        try {
            os.close();
        } catch (IOException e) {
            tracer.error("error on output stream", e);
        }
        return signature.finalizeSignature();
        //      } catch (MarkFailedException e) {
        //         throw e;
    } catch (Exception e) {
        tracer.error("Unable to sign PDF.", e);
        throw new SignatureException("Unable to sign PDF.", e);
    }
}

From source file:uk.ac.ox.webauth.asn1.Authenticator.java

License:Open Source License

/**
 * Instantiate an Authenticator./*w ww.  java 2s. c o m*/
 * @param   princ   The KerberosPrincipal of the ticket.
 */
public Authenticator(KerberosPrincipal princ) {
    authenticator_vno = new DERInteger(5);
    crealm = new DERGeneralString(princ.getRealm());
    String name = princ.getName().split("@")[0];
    cname = new PrincipalName(princ.getNameType(), name.split("/"));
    Calendar cal = Calendar.getInstance();
    cusec = new DERInteger(cal.get(MILLISECOND) * 1000);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
    sdf.setTimeZone(UTC);
    ctime = new DERGeneralizedTime(sdf.format(cal.getTime()));
    // have left seq-number out for now...
}

From source file:uk.ac.ox.webauth.asn1.PrincipalName.java

License:Open Source License

/**
 * Instantiate a PrincipalName.//w  ww.j a v  a 2  s  . c o m
 * @param   type    The type of this principal name.
 * @param   name    An array of strings making up the name.
 */
public PrincipalName(int type, String[] name) {
    name_type = new DERInteger(type);
    DEREncodableVector v = new DEREncodableVector();
    for (String component : name) {
        v.add(new DERGeneralString(component));
    }
    name_string = new DERSequence(v);
}