List of usage examples for org.bouncycastle.asn1.cms AttributeTable toHashtable
public Hashtable toHashtable()
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>/* w w w . ja va 2 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:it.trento.comune.j4sign.cms.utils.CMSBuilder.java
License:Open Source License
private Date parseSigningTime(byte[] bytes, PrintWriter pw) { Date parsedSigningTime = null; try {//from w ww.ja va 2s. c om ASN1InputStream aIn = new ASN1InputStream(bytes); ASN1Set signedAttributes = (ASN1Set) aIn.readObject(); AttributeTable attr = new AttributeTable(signedAttributes); Iterator iter = attr.toHashtable().values().iterator(); pw.println("Listing authenticated attributes:"); int count = 1; while (iter.hasNext()) { Attribute a = (Attribute) iter.next(); pw.println("Attribute " + count + ":"); if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) { Time time = Time.getInstance(a.getAttrValues().getObjectAt(0)); pw.println("Authenticated time (SERVER local time): " + time.getDate()); parsedSigningTime = time.getDate(); } if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) { if (CMSObjectIdentifiers.data.getId() .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId())) pw.println("Content Type: PKCS7_DATA"); } if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) { byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); pw.println("Message Digest (hash of data content): " + formatAsString(md, " ", 16)); } pw.println("\nAttribute dump follows:"); pw.println(ASN1Dump.dumpAsString(a) + "\n"); count++; } } catch (Exception e) { pw.println(e); return null; } pw.flush(); return parsedSigningTime; }
From source file:it.trento.comune.j4sign.cms.utils.CMSVerifier.java
License:Open Source License
private void parseAuthenticatedAttributes(SignerInformation signer) { AttributeTable attr = signer.getSignedAttributes(); Iterator<Attribute> iter = attr.toHashtable().values().iterator(); if (debug)//w ww . j a v a2s .c om System.out.println("Listing authenticated attributes:"); int count = 1; while (iter.hasNext()) { Attribute a = iter.next(); if (debug) System.out.println("Attribute " + count + ":"); if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) { Time time = Time.getInstance(a.getAttrValues().getObjectAt(0)); if (debug) System.out.println("Authenticated time: " + time.getDate()); this.signingTime = time.getDate(); } if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) { if (CMSObjectIdentifiers.data.getId() .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId())) if (debug) System.out.println("Content Type: PKCS7_DATA"); } if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) { byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); if (debug) System.out.println( "Message Digest (hash of data content):\n" + CMSBuilder.formatAsString(md, " ", 16)); } if (debug) System.out.println("\nAttribute dump follows:"); if (debug) System.out.println(ASN1Dump.dumpAsString(a) + "\n"); count++; } }
From source file:it.trento.comune.j4sign.examples.CMSServlet.java
License:Open Source License
/** * A text message resulting from a dump of provided authenticated attributes * data. Shows, among other things, the embedded timestamp attribute. * /* ww w.java 2 s . c o m*/ * @param bytes * the ASN.1 DER set of authenticated attributes. * @return the attributes textual dump. */ private String getAuthenticatedAttributesPrintout(byte[] bytes) { StringWriter printout = new StringWriter(); PrintWriter pw = new PrintWriter(printout); try { ASN1StreamParser a1p = new ASN1StreamParser(bytes); System.out.println("ASN1 parser built: " + a1p); DERSetParser signedAttributesParser = (DERSetParser) a1p.readObject(); System.out.println("DERSetParser object read: " + signedAttributesParser); ASN1Set set = ASN1Set.getInstance(signedAttributesParser.getDERObject()); AttributeTable attr = new AttributeTable(set); System.out.println("Attribute table created: " + attr); Iterator iter = attr.toHashtable().values().iterator(); pw.println("Listing authenticated attributes:"); int count = 1; while (iter.hasNext()) { Attribute a = (Attribute) iter.next(); pw.println("Attribute " + count + ":"); if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) { Time time = Time.getInstance(a.getAttrValues().getObjectAt(0)); pw.println("Authenticated time (SERVER local time): " + time.getDate()); } if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) { if (CMSObjectIdentifiers.data.getId() .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId())) pw.println("Content Type: PKCS7_DATA"); } if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) { byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); pw.println("Message Digest (SHA-256 hash of data content): " + formatAsString(md, " ")); } if (a.getAttrType().getId().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2.getId())) { pw.println("Signing Certificate V2"); } pw.println("\nAttribute dump follows:"); pw.println(ASN1Dump.dumpAsString(a) + "\n"); count++; } } catch (Exception e) { System.out.println(e); pw.println(e); return null; } pw.flush(); return printout.toString(); }
From source file:it.trento.comune.j4sign.verification.VerifyResult.java
License:Open Source License
/** * Main signature verification and signature attributes correctness<br> * <br>//ww w. ja va2 s. c o m * Verifica principale della firma e di correttezza degli attributi. * * @return boolean */ public boolean checkIntegrity() { this.integrityChecked = this.messageDigestPresent = this.contentTypeDataPresent = false; if (signer == null) { log.info("No signers"); return integrityChecked; } log.info("\nSigner DN: " + cert.getSubjectDN() + "\nSigner SID: " + signer.getSID().toString() + "\n"); // ===== List authenticated attributes ========= AttributeTable attrs = signer.getSignedAttributes(); if (attrs == null) { log.info("No authenticated attributes!"); return false; } Iterator<Attribute> iter = attrs.toHashtable().values().iterator(); log.info("Listing authenticated attributes:"); int count = 1; while (iter.hasNext()) { Attribute a = iter.next(); log.info("Attribute " + count + ")"); if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) { if (CMSObjectIdentifiers.data.getId() .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId())) this.contentTypeDataPresent = true; log.info("Content Type: PKCS7_DATA"); } if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) { byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); this.messageDigestPresent = true; log.info("Message Digest:\n" + CertUtils.formatAsHexString(md)); } if (a.getAttrType().getId().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2.getId())) log.info("Reference to signing certificate (CAdES): signingCertificateV2"); if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) { Time time = Time.getInstance(a.getAttrValues().getObjectAt(0)); log.info("Signing time: " + time.getDate()); this.signingTime = time.getDate(); } log.info("\nAttribute dump follows:"); log.info(ASN1Dump.dumpAsString(a) + "\n"); count++; } signingAlgorithmName = new DefaultCMSSignatureAlgorithmNameGenerator().getSignatureName( AlgorithmIdentifier.getInstance(signer.getDigestAlgOID()), AlgorithmIdentifier.getInstance(signer.getEncryptionAlgOID())); log.info("\nSigning algorithm is : " + signingAlgorithmName + "\n"); try { // BC API version 2 /* * Note: we should test for EncryptionAlg = RSA before doing * this!!!! integrityChecked = signer .verify(new * BcRSASignerInfoVerifierBuilder( new * DefaultDigestAlgorithmIdentifierFinder(), new * BcDigestCalculatorProvider()) .build(new * X509CertificateHolder(cert.getEncoded()))); */ integrityChecked = signer.verify( new JcaSimpleSignerInfoVerifierBuilder().build(new X509CertificateHolder(cert.getEncoded()))); // Now deprecated // integrityChecked = signer.verify(cert, "BC"); } catch (CMSException ex) { System.out.println(ex.getMessage()); } catch (CertificateNotYetValidException ex) { System.out.println(ex.getMessage()); } catch (CertificateExpiredException ex) { System.out.println(ex.getMessage()); } catch (CertificateException e) { System.out.println(e.getMessage()); } catch (OperatorCreationException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } return integrityChecked; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.DemoiselleSignedAttributeTableGenerator.java
License:Open Source License
/** * Initialise with some extra attributes or overrides. * * @param attributeTable initial attribute table to use. *///from ww w. ja v a 2 s . c o m public DemoiselleSignedAttributeTableGenerator(AttributeTable attributeTable) { if (attributeTable != null) { table = attributeTable.toHashtable(); } else { table = new Hashtable(); } }
From source file:org.dihedron.crypto.operations.sign.pkcs7.PKCS7AttributeTableGenerator.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) public AttributeTable getAttributes(Map parameters) throws CMSAttributeTableGenerationException { AttributeTable result = super.getAttributes(parameters); Hashtable table = result.toHashtable(); try {//w w w. j a v a 2 s .c om if (!table.containsKey(SignedData.id_aa_signingCertificate) && !table.containsKey(SignedData.id_aa_signingCertificateV2)) { logger.debug("signed attributes table does not contain SigningCertificate[V2]: adding..."); IssuerSerial issuerSerial = Certificates.makeIssuerSerial(x509certificate); Attribute attribute = null; // create the ESSCertId[V2] objects to embed as SigningCertificate[V2] switch (digestAlgorithm) { case SHA1: logger.info("adding signing certificate v1 to signed attributes"); ESSCertID essCertId = Certificates.makeESSCertIdV1(x509certificate, issuerSerial, digestAlgorithm); attribute = new Attribute(SignedData.id_aa_signingCertificate, new DERSet(new SigningCertificate(essCertId))); break; case SHA256: case SHA384: case SHA512: logger.info("adding signing certificate v2 to signed attributes"); ESSCertIDv2 essCertIdv2s[] = Certificates.makeESSCertIdV2(x509certificate, issuerSerial, digestAlgorithm); attribute = new Attribute(SignedData.id_aa_signingCertificateV2, new DERSet(new SigningCertificateV2(essCertIdv2s))); break; default: logger.info("unsupported digest algorithm: {}", digestAlgorithm); } table.put(attribute.getAttrType(), attribute); } return new AttributeTable(table); } catch (CertificateEncodingException e) { logger.error("error reading certificate encoding", e); } catch (NoSuchAlgorithmException e) { logger.error("unsupported digest algorithm: " + digestAlgorithm, e); } catch (IOException e) { logger.error("I/O error reading certificate structure", e); } return null; }
From source file:org.votingsystem.signature.smime.SMIMEMessage.java
License:Open Source License
public void setTimeStampToken(TimeStampToken timeStampToken) throws Exception { if (timeStampToken == null) throw new Exception("timestamp token null"); DERObject derObject = new ASN1InputStream(timeStampToken.getEncoded()).readObject(); DERSet derset = new DERSet(derObject); Attribute timeStampAsAttribute = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, derset); Hashtable hashTable = new Hashtable(); hashTable.put(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, timeStampAsAttribute); AttributeTable timeStampAsAttributeTable = new AttributeTable(hashTable); byte[] timeStampTokenHash = timeStampToken.getTimeStampInfo().getMessageImprintDigest(); Iterator<SignerInformation> it = smimeSigned.getSignerInfos().getSigners().iterator(); List<SignerInformation> newSigners = new ArrayList<SignerInformation>(); while (it.hasNext()) { SignerInformation signer = it.next(); byte[] digestBytes = CMSUtils.getSignerDigest(signer); if (Arrays.equals(timeStampTokenHash, digestBytes)) { log.info("setTimeStampToken - found signer"); AttributeTable attributeTable = signer.getUnsignedAttributes(); SignerInformation updatedSigner = null; if (attributeTable != null) { log.info("setTimeStampToken - signer with UnsignedAttributes"); hashTable = attributeTable.toHashtable(); hashTable.put(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, timeStampAsAttribute); timeStampAsAttributeTable = new AttributeTable(hashTable); }/* w ww. j a va2 s . c om*/ updatedSigner = signer.replaceUnsignedAttributes(signer, timeStampAsAttributeTable); newSigners.add(updatedSigner); } else newSigners.add(signer); } SignerInformationStore newSignersStore = new SignerInformationStore(newSigners); CMSSignedData cmsdata = smimeSigned.replaceSigners(smimeSigned, newSignersStore); replaceSigners(cmsdata); }