Browse Source

DEC-19773 refactor: itext适配新bouncycastle

feature/10.0
lidongy 3 years ago
parent
commit
ebe0f9fdef
  1. 305
      fine-itext-old/src/main/java/com/fr/third/com/lowagie/text/pdf/PdfPKCS7.java
  2. 50
      fine-itext-old/src/main/java/com/fr/third/com/lowagie/text/pdf/PdfPublicKeySecurityHandler.java
  3. 307
      fine-itext/src/main/java/com/fr/third/v2/lowagie/text/pdf/PdfPKCS7.java
  4. 134
      fine-itext/src/main/java/com/fr/third/v2/lowagie/text/pdf/PdfPublicKeySecurityHandler.java

305
fine-itext-old/src/main/java/com/fr/third/com/lowagie/text/pdf/PdfPKCS7.java

@ -46,8 +46,11 @@
*/ */
package com.fr.third.com.lowagie.text.pdf; package com.fr.third.com.lowagie.text.pdf;
import com.fr.third.org.bouncycastle.asn1.ASN1Integer;
import com.fr.third.org.bouncycastle.asn1.ASN1Object; import com.fr.third.org.bouncycastle.asn1.ASN1Object;
import com.fr.third.org.bouncycastle.asn1.ASN1ObjectIdentifier;
import com.fr.third.org.bouncycastle.asn1.ASN1String; import com.fr.third.org.bouncycastle.asn1.ASN1String;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -77,19 +80,15 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Set; import java.util.Set;
import com.fr.third.org.bouncycastle.asn1.ASN1Encodable;
import com.fr.third.org.bouncycastle.asn1.ASN1EncodableVector; import com.fr.third.org.bouncycastle.asn1.ASN1EncodableVector;
import com.fr.third.org.bouncycastle.asn1.ASN1InputStream; import com.fr.third.org.bouncycastle.asn1.ASN1InputStream;
import com.fr.third.org.bouncycastle.asn1.ASN1OutputStream; import com.fr.third.org.bouncycastle.asn1.ASN1OutputStream;
import com.fr.third.org.bouncycastle.asn1.ASN1Sequence; import com.fr.third.org.bouncycastle.asn1.ASN1Sequence;
import com.fr.third.org.bouncycastle.asn1.ASN1Set; import com.fr.third.org.bouncycastle.asn1.ASN1Set;
import com.fr.third.org.bouncycastle.asn1.ASN1TaggedObject; import com.fr.third.org.bouncycastle.asn1.ASN1TaggedObject;
import com.fr.third.org.bouncycastle.asn1.DEREnumerated; import com.fr.third.org.bouncycastle.asn1.ASN1Enumerated;
import com.fr.third.org.bouncycastle.asn1.DERInteger;
import com.fr.third.org.bouncycastle.asn1.DERNull; import com.fr.third.org.bouncycastle.asn1.DERNull;
import com.fr.third.org.bouncycastle.asn1.DERObjectIdentifier;
import com.fr.third.org.bouncycastle.asn1.DEROctetString; import com.fr.third.org.bouncycastle.asn1.DEROctetString;
import com.fr.third.org.bouncycastle.asn1.DEROutputStream;
import com.fr.third.org.bouncycastle.asn1.DERSequence; import com.fr.third.org.bouncycastle.asn1.DERSequence;
import com.fr.third.org.bouncycastle.asn1.DERSet; import com.fr.third.org.bouncycastle.asn1.DERSet;
import com.fr.third.org.bouncycastle.asn1.DERTaggedObject; import com.fr.third.org.bouncycastle.asn1.DERTaggedObject;
@ -101,12 +100,12 @@ import com.fr.third.org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
import com.fr.third.org.bouncycastle.jce.provider.X509CRLParser; import com.fr.third.org.bouncycastle.jce.provider.X509CRLParser;
import com.fr.third.org.bouncycastle.jce.provider.X509CertParser; import com.fr.third.org.bouncycastle.jce.provider.X509CertParser;
import com.fr.third.com.lowagie.text.ExceptionConverter; import com.fr.third.com.lowagie.text.ExceptionConverter;
import java.security.cert.CertificateParsingException; import java.security.cert.CertificateParsingException;
import java.util.Date;
import com.fr.third.org.bouncycastle.asn1.ASN1OctetString; import com.fr.third.org.bouncycastle.asn1.ASN1OctetString;
import com.fr.third.org.bouncycastle.asn1.cms.ContentInfo; import com.fr.third.org.bouncycastle.asn1.cms.ContentInfo;
import com.fr.third.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import com.fr.third.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import com.fr.third.org.bouncycastle.asn1.tsp.MessageImprint;
import com.fr.third.org.bouncycastle.asn1.x509.X509Extensions; import com.fr.third.org.bouncycastle.asn1.x509.X509Extensions;
//import org.bouncycastle.ocsp.BasicOCSPResp; //import org.bouncycastle.ocsp.BasicOCSPResp;
//import org.bouncycastle.ocsp.CertificateID; //import org.bouncycastle.ocsp.CertificateID;
@ -242,6 +241,7 @@ public class PdfPKCS7 {
/** /**
* Gets the digest name for a certain id * Gets the digest name for a certain id
*
* @param oid an id (for instance "1.2.840.113549.2.5") * @param oid an id (for instance "1.2.840.113549.2.5")
* @return a digest name (for instance "MD5") * @return a digest name (for instance "MD5")
* @since 2.1.6 * @since 2.1.6
@ -256,6 +256,7 @@ public class PdfPKCS7 {
/** /**
* Gets the algorithm name for a certain id. * Gets the algorithm name for a certain id.
*
* @param oid an id (for instance "1.2.840.113549.1.1.1") * @param oid an id (for instance "1.2.840.113549.1.1.1")
* @return an algorithm name (for instance "RSA") * @return an algorithm name (for instance "RSA")
* @since 2.1.6 * @since 2.1.6
@ -293,6 +294,7 @@ public class PdfPKCS7 {
/** /**
* Verifies a signature using the sub-filter adbe.x509.rsa_sha1. * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
*
* @param contentsKey the /Contents key * @param contentsKey the /Contents key
* @param certsKey the /Cert key * @param certsKey the /Cert key
* @param provider the provider or <code>null</code> for the default provider * @param provider the provider or <code>null</code> for the default provider
@ -313,8 +315,7 @@ public class PdfPKCS7 {
else else
sig = Signature.getInstance("SHA1withRSA", provider); sig = Signature.getInstance("SHA1withRSA", provider);
sig.initVerify(signCert.getPublicKey()); sig.initVerify(signCert.getPublicKey());
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
@ -323,19 +324,19 @@ public class PdfPKCS7 {
/** /**
* Gets the OCSP basic response if there is one. * Gets the OCSP basic response if there is one.
*
* @return the OCSP basic response or null * @return the OCSP basic response or null
* @since 2.1.6 * @since 2.1.6
*/ */
// public BasicOCSPResp getOcsp() { // public BasicOCSPResp getOcsp() {
// return basicResp; // return basicResp;
// } // }
private void findOcsp(ASN1Sequence seq) throws IOException { private void findOcsp(ASN1Sequence seq) throws IOException {
// basicResp = null; // basicResp = null;
boolean ret = false; boolean ret = false;
while (true) { while (true) {
if ((seq.getObjectAt(0) instanceof DERObjectIdentifier) if ((seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
&& ((DERObjectIdentifier)seq.getObjectAt(0)).getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) { && ((ASN1ObjectIdentifier) seq.getObjectAt(0)).getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) {
break; break;
} }
ret = true; ret = true;
@ -351,8 +352,7 @@ public class PdfPKCS7 {
seq = (ASN1Sequence) tag.getObject(); seq = (ASN1Sequence) tag.getObject();
ret = false; ret = false;
break; break;
} } else
else
return; return;
} }
} }
@ -368,6 +368,7 @@ public class PdfPKCS7 {
/** /**
* Verifies a signature using the sub-filter adbe.pkcs7.detached or * Verifies a signature using the sub-filter adbe.pkcs7.detached or
* adbe.pkcs7.sha1. * adbe.pkcs7.sha1.
*
* @param contentsKey the /Contents key * @param contentsKey the /Contents key
* @param provider the provider or <code>null</code> for the default provider * @param provider the provider or <code>null</code> for the default provider
*/ */
@ -383,15 +384,14 @@ public class PdfPKCS7 {
try { try {
pkcs = din.readObject(); pkcs = din.readObject();
} } catch (IOException e) {
catch (IOException e) {
throw new IllegalArgumentException("can't decode PKCS7SignedData object"); throw new IllegalArgumentException("can't decode PKCS7SignedData object");
} }
if (!(pkcs instanceof ASN1Sequence)) { if (!(pkcs instanceof ASN1Sequence)) {
throw new IllegalArgumentException("Not a valid PKCS#7 object - not a sequence"); throw new IllegalArgumentException("Not a valid PKCS#7 object - not a sequence");
} }
ASN1Sequence signedData = (ASN1Sequence) pkcs; ASN1Sequence signedData = (ASN1Sequence) pkcs;
DERObjectIdentifier objId = (DERObjectIdentifier)signedData.getObjectAt(0); ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0);
if (!objId.getId().equals(ID_PKCS7_SIGNED_DATA)) if (!objId.getId().equals(ID_PKCS7_SIGNED_DATA))
throw new IllegalArgumentException("Not a valid PKCS#7 object - not signed data"); throw new IllegalArgumentException("Not a valid PKCS#7 object - not signed data");
ASN1Sequence content = (ASN1Sequence) ((DERTaggedObject) signedData.getObjectAt(1)).getObject(); ASN1Sequence content = (ASN1Sequence) ((DERTaggedObject) signedData.getObjectAt(1)).getObject();
@ -403,15 +403,14 @@ public class PdfPKCS7 {
// last - signerInfos // last - signerInfos
// the version // the version
version = ((DERInteger)content.getObjectAt(0)).getValue().intValue(); version = ((ASN1Integer) content.getObjectAt(0)).getValue().intValue();
// the digestAlgorithms // the digestAlgorithms
digestalgos = new HashSet(); digestalgos = new HashSet();
Enumeration e = ((ASN1Set) content.getObjectAt(1)).getObjects(); Enumeration e = ((ASN1Set) content.getObjectAt(1)).getObjects();
while (e.hasMoreElements()) while (e.hasMoreElements()) {
{
ASN1Sequence s = (ASN1Sequence) e.nextElement(); ASN1Sequence s = (ASN1Sequence) e.nextElement();
DERObjectIdentifier o = (DERObjectIdentifier)s.getObjectAt(0); ASN1ObjectIdentifier o = (ASN1ObjectIdentifier) s.getObjectAt(0);
digestalgos.add(o.getId()); digestalgos.add(o.getId());
} }
@ -444,10 +443,10 @@ public class PdfPKCS7 {
// 2 - the digest algorithm // 2 - the digest algorithm
// 3 or 4 - digestEncryptionAlgorithm // 3 or 4 - digestEncryptionAlgorithm
// 4 or 5 - encryptedDigest // 4 or 5 - encryptedDigest
signerversion = ((DERInteger)signerInfo.getObjectAt(0)).getValue().intValue(); signerversion = ((ASN1Integer) signerInfo.getObjectAt(0)).getValue().intValue();
// Get the signing certificate // Get the signing certificate
ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1); ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1);
BigInteger serialNumber = ((DERInteger)issuerAndSerialNumber.getObjectAt(1)).getValue(); BigInteger serialNumber = ((ASN1Integer) issuerAndSerialNumber.getObjectAt(1)).getValue();
for (Iterator i = certs.iterator(); i.hasNext(); ) { for (Iterator i = certs.iterator(); i.hasNext(); ) {
X509Certificate cert = (X509Certificate) i.next(); X509Certificate cert = (X509Certificate) i.next();
if (serialNumber.equals(cert.getSerialNumber())) { if (serialNumber.equals(cert.getSerialNumber())) {
@ -459,7 +458,7 @@ public class PdfPKCS7 {
throw new IllegalArgumentException("Can't find signing certificate with serial " + serialNumber.toString(16)); throw new IllegalArgumentException("Can't find signing certificate with serial " + serialNumber.toString(16));
} }
signCertificateChain(); signCertificateChain();
digestAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(2)).getObjectAt(0)).getId(); digestAlgorithm = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0)).getId();
next = 3; next = 3;
if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) { if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) {
ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next); ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next);
@ -468,11 +467,10 @@ public class PdfPKCS7 {
for (int k = 0; k < sseq.size(); ++k) { for (int k = 0; k < sseq.size(); ++k) {
ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k); ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k);
if (((DERObjectIdentifier)seq2.getObjectAt(0)).getId().equals(ID_MESSAGE_DIGEST)) { if (((ASN1ObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_MESSAGE_DIGEST)) {
ASN1Set set = (ASN1Set) seq2.getObjectAt(1); ASN1Set set = (ASN1Set) seq2.getObjectAt(1);
digestAttr = ((DEROctetString) set.getObjectAt(0)).getOctets(); digestAttr = ((DEROctetString) set.getObjectAt(0)).getOctets();
} } else if (((ASN1ObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_ADBE_REVOCATION)) {
else if (((DERObjectIdentifier)seq2.getObjectAt(0)).getId().equals(ID_ADBE_REVOCATION)) {
ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
for (int j = 0; j < seqout.size(); ++j) { for (int j = 0; j < seqout.size(); ++j) {
@ -488,7 +486,7 @@ public class PdfPKCS7 {
throw new IllegalArgumentException("Authenticated attribute is missing the digest."); throw new IllegalArgumentException("Authenticated attribute is missing the digest.");
++next; ++next;
} }
digestEncryptionAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(next++)).getObjectAt(0)).getId(); digestEncryptionAlgorithm = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++)).getObjectAt(0)).getId();
digest = ((DEROctetString) signerInfo.getObjectAt(next++)).getOctets(); digest = ((DEROctetString) signerInfo.getObjectAt(next++)).getOctets();
if (next < signerInfo.size() && (signerInfo.getObjectAt(next) instanceof DERTaggedObject)) { if (next < signerInfo.size() && (signerInfo.getObjectAt(next) instanceof DERTaggedObject)) {
DERTaggedObject taggedObject = (DERTaggedObject) signerInfo.getObjectAt(next); DERTaggedObject taggedObject = (DERTaggedObject) signerInfo.getObjectAt(next);
@ -513,14 +511,14 @@ public class PdfPKCS7 {
else else
sig = Signature.getInstance(getDigestAlgorithm(), provider); sig = Signature.getInstance(getDigestAlgorithm(), provider);
sig.initVerify(signCert.getPublicKey()); sig.initVerify(signCert.getPublicKey());
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Generates a signature. * Generates a signature.
*
* @param privKey the private key * @param privKey the private key
* @param certChain the certificate chain * @param certChain the certificate chain
* @param crlList the certificate revocation list * @param crlList the certificate revocation list
@ -534,8 +532,7 @@ public class PdfPKCS7 {
public PdfPKCS7(PrivateKey privKey, Certificate[] certChain, CRL[] crlList, public PdfPKCS7(PrivateKey privKey, Certificate[] certChain, CRL[] crlList,
String hashAlgorithm, String provider, boolean hasRSAdata) String hashAlgorithm, String provider, boolean hasRSAdata)
throws InvalidKeyException, NoSuchProviderException, throws InvalidKeyException, NoSuchProviderException,
NoSuchAlgorithmException NoSuchAlgorithmException {
{
this.privKey = privKey; this.privKey = privKey;
this.provider = provider; this.provider = provider;
@ -570,11 +567,9 @@ public class PdfPKCS7 {
digestEncryptionAlgorithm = privKey.getAlgorithm(); digestEncryptionAlgorithm = privKey.getAlgorithm();
if (digestEncryptionAlgorithm.equals("RSA")) { if (digestEncryptionAlgorithm.equals("RSA")) {
digestEncryptionAlgorithm = ID_RSA; digestEncryptionAlgorithm = ID_RSA;
} } else if (digestEncryptionAlgorithm.equals("DSA")) {
else if (digestEncryptionAlgorithm.equals("DSA")) {
digestEncryptionAlgorithm = ID_DSA; digestEncryptionAlgorithm = ID_DSA;
} } else {
else {
throw new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm); throw new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm);
} }
} }
@ -598,6 +593,7 @@ public class PdfPKCS7 {
/** /**
* Update the digest with the specified bytes. This method is used both for signing and verifying * Update the digest with the specified bytes. This method is used both for signing and verifying
*
* @param buf the data buffer * @param buf the data buffer
* @param off the offset in the data buffer * @param off the offset in the data buffer
* @param len the data length * @param len the data length
@ -612,8 +608,9 @@ public class PdfPKCS7 {
/** /**
* Verify the digest. * Verify the digest.
* @throws SignatureException on error *
* @return <CODE>true</CODE> if the signature checks out, <CODE>false</CODE> otherwise * @return <CODE>true</CODE> if the signature checks out, <CODE>false</CODE> otherwise
* @throws SignatureException on error
*/ */
public boolean verify() throws SignatureException { public boolean verify() throws SignatureException {
if (verified) if (verified)
@ -625,8 +622,7 @@ public class PdfPKCS7 {
messageDigest.update(msd); messageDigest.update(msd);
} }
verifyResult = (Arrays.equals(messageDigest.digest(), digestAttr) && sig.verify(digest)); verifyResult = (Arrays.equals(messageDigest.digest(), digestAttr) && sig.verify(digest));
} } else {
else {
if (RSAdata != null) if (RSAdata != null)
sig.update(messageDigest.digest()); sig.update(messageDigest.digest());
verifyResult = sig.verify(digest); verifyResult = sig.verify(digest);
@ -654,6 +650,7 @@ public class PdfPKCS7 {
/** /**
* Get all the X.509 certificates associated with this PKCS#7 object in no particular order. * Get all the X.509 certificates associated with this PKCS#7 object in no particular order.
* Other certificates, from OCSP for example, will also be included. * Other certificates, from OCSP for example, will also be included.
*
* @return the X.509 certificates associated with this PKCS#7 object * @return the X.509 certificates associated with this PKCS#7 object
*/ */
public Certificate[] getCertificates() { public Certificate[] getCertificates() {
@ -664,6 +661,7 @@ public class PdfPKCS7 {
* Get the X.509 sign certificate chain associated with this PKCS#7 object. * Get the X.509 sign certificate chain associated with this PKCS#7 object.
* Only the certificates used for the main signature will be returned, with * Only the certificates used for the main signature will be returned, with
* the signing certificate first. * the signing certificate first.
*
* @return the X.509 certificates associated with this PKCS#7 object * @return the X.509 certificates associated with this PKCS#7 object
* @since 2.1.6 * @since 2.1.6
*/ */
@ -696,8 +694,7 @@ public class PdfPKCS7 {
cc.add(oc.get(k)); cc.add(oc.get(k));
oc.remove(k); oc.remove(k);
break; break;
} } catch (Exception e) {
catch (Exception e) {
} }
} }
} }
@ -706,6 +703,7 @@ public class PdfPKCS7 {
/** /**
* Get the X.509 certificate revocation lists associated with this PKCS#7 object * Get the X.509 certificate revocation lists associated with this PKCS#7 object
*
* @return the X.509 certificate revocation lists associated with this PKCS#7 object * @return the X.509 certificate revocation lists associated with this PKCS#7 object
*/ */
public Collection getCRLs() { public Collection getCRLs() {
@ -714,6 +712,7 @@ public class PdfPKCS7 {
/** /**
* Get the X.509 certificate actually used to sign the digest. * Get the X.509 certificate actually used to sign the digest.
*
* @return the X.509 certificate actually used to sign the digest * @return the X.509 certificate actually used to sign the digest
*/ */
public X509Certificate getSigningCertificate() { public X509Certificate getSigningCertificate() {
@ -722,6 +721,7 @@ public class PdfPKCS7 {
/** /**
* Get the version of the PKCS#7 object. Always 1 * Get the version of the PKCS#7 object. Always 1
*
* @return the version of the PKCS#7 object. Always 1 * @return the version of the PKCS#7 object. Always 1
*/ */
public int getVersion() { public int getVersion() {
@ -730,6 +730,7 @@ public class PdfPKCS7 {
/** /**
* Get the version of the PKCS#7 "SignerInfo" object. Always 1 * Get the version of the PKCS#7 "SignerInfo" object. Always 1
*
* @return the version of the PKCS#7 "SignerInfo" object. Always 1 * @return the version of the PKCS#7 "SignerInfo" object. Always 1
*/ */
public int getSigningInfoVersion() { public int getSigningInfoVersion() {
@ -738,6 +739,7 @@ public class PdfPKCS7 {
/** /**
* Get the algorithm used to calculate the message digest * Get the algorithm used to calculate the message digest
*
* @return the algorithm used to calculate the message digest * @return the algorithm used to calculate the message digest
*/ */
public String getDigestAlgorithm() { public String getDigestAlgorithm() {
@ -750,6 +752,7 @@ public class PdfPKCS7 {
/** /**
* Returns the algorithm. * Returns the algorithm.
*
* @return the digest algorithm * @return the digest algorithm
*/ */
public String getHashAlgorithm() { public String getHashAlgorithm() {
@ -759,6 +762,7 @@ public class PdfPKCS7 {
/** /**
* Loads the default root certificates at &lt;java.home&gt;/lib/security/cacerts * Loads the default root certificates at &lt;java.home&gt;/lib/security/cacerts
* with the default provider. * with the default provider.
*
* @return a <CODE>KeyStore</CODE> * @return a <CODE>KeyStore</CODE>
*/ */
public static KeyStore loadCacertsKeyStore() { public static KeyStore loadCacertsKeyStore() {
@ -767,6 +771,7 @@ public class PdfPKCS7 {
/** /**
* Loads the default root certificates at &lt;java.home&gt;/lib/security/cacerts. * Loads the default root certificates at &lt;java.home&gt;/lib/security/cacerts.
*
* @param provider the provider or <code>null</code> for the default provider * @param provider the provider or <code>null</code> for the default provider
* @return a <CODE>KeyStore</CODE> * @return a <CODE>KeyStore</CODE>
*/ */
@ -784,17 +789,21 @@ public class PdfPKCS7 {
k = KeyStore.getInstance("JKS", provider); k = KeyStore.getInstance("JKS", provider);
k.load(fin, null); k.load(fin, null);
return k; return k;
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (Exception ex) {
} }
finally {
try{if (fin != null) {fin.close();}}catch(Exception ex){}
} }
} }
/** /**
* Verifies a single certificate. * Verifies a single certificate.
*
* @param cert the certificate to verify * @param cert the certificate to verify
* @param crls the certificate revocation list or <CODE>null</CODE> * @param crls the certificate revocation list or <CODE>null</CODE>
* @param calendar the date or <CODE>null</CODE> for the current date * @param calendar the date or <CODE>null</CODE> for the current date
@ -808,8 +817,7 @@ public class PdfPKCS7 {
return "Has unsupported critical extension"; return "Has unsupported critical extension";
try { try {
cert.checkValidity(calendar.getTime()); cert.checkValidity(calendar.getTime());
} } catch (Exception e) {
catch (Exception e) {
return e.getMessage(); return e.getMessage();
} }
if (crls != null) { if (crls != null) {
@ -823,6 +831,7 @@ public class PdfPKCS7 {
/** /**
* Verifies a certificate chain against a KeyStore. * Verifies a certificate chain against a KeyStore.
*
* @param certs the certificate chain * @param certs the certificate chain
* @param keystore the <CODE>KeyStore</CODE> * @param keystore the <CODE>KeyStore</CODE>
* @param crls the certificate revocation list or <CODE>null</CODE> * @param crls the certificate revocation list or <CODE>null</CODE>
@ -851,16 +860,13 @@ public class PdfPKCS7 {
try { try {
cert.verify(certStoreX509.getPublicKey()); cert.verify(certStoreX509.getPublicKey());
return null; return null;
} } catch (Exception e) {
catch (Exception e) {
continue; continue;
} }
} } catch (Exception ex) {
catch (Exception ex) {
} }
} }
} } catch (Exception e) {
catch (Exception e) {
} }
int j; int j;
for (j = 0; j < certs.length; ++j) { for (j = 0; j < certs.length; ++j) {
@ -870,8 +876,7 @@ public class PdfPKCS7 {
try { try {
cert.verify(certNext.getPublicKey()); cert.verify(certNext.getPublicKey());
break; break;
} } catch (Exception e) {
catch (Exception e) {
} }
} }
if (j == certs.length) if (j == certs.length)
@ -942,6 +947,7 @@ public class PdfPKCS7 {
/** /**
* Retrieves the OCSP URL from the given certificate. * Retrieves the OCSP URL from the given certificate.
*
* @param certificate the certificate * @param certificate the certificate
* @return the URL or null * @return the URL or null
* @throws CertificateParsingException on error * @throws CertificateParsingException on error
@ -960,7 +966,7 @@ public class PdfPKCS7 {
if (AccessDescription.size() != 2) { if (AccessDescription.size() != 2) {
continue; continue;
} else { } else {
if ((AccessDescription.getObjectAt(0) instanceof DERObjectIdentifier) && ((DERObjectIdentifier)AccessDescription.getObjectAt(0)).getId().equals("1.3.6.1.5.5.7.48.1")) { if ((AccessDescription.getObjectAt(0) instanceof ASN1ObjectIdentifier) && ((ASN1ObjectIdentifier) AccessDescription.getObjectAt(0)).getId().equals("1.3.6.1.5.5.7.48.1")) {
String AccessLocation = getStringFromGeneralName((ASN1Object) AccessDescription.getObjectAt(1)); String AccessLocation = getStringFromGeneralName((ASN1Object) AccessDescription.getObjectAt(1));
if (AccessLocation == null) { if (AccessLocation == null) {
return ""; return "";
@ -977,6 +983,7 @@ public class PdfPKCS7 {
/** /**
* Checks if OCSP revocation refers to the document signing certificate. * Checks if OCSP revocation refers to the document signing certificate.
*
* @return true if it checks false otherwise * @return true if it checks false otherwise
* @since 2.1.6 * @since 2.1.6
*/ */
@ -998,7 +1005,6 @@ public class PdfPKCS7 {
// } // }
// return false; // return false;
// } // }
private static ASN1Object getExtensionValue(X509Certificate cert, String oid) throws IOException { private static ASN1Object getExtensionValue(X509Certificate cert, String oid) throws IOException {
byte[] bytes = cert.getExtensionValue(oid); byte[] bytes = cert.getExtensionValue(oid);
if (bytes == null) { if (bytes == null) {
@ -1017,6 +1023,7 @@ public class PdfPKCS7 {
/** /**
* Get the "issuer" from the TBSCertificate bytes that are passed in * Get the "issuer" from the TBSCertificate bytes that are passed in
*
* @param enc a TBSCertificate in a byte array * @param enc a TBSCertificate in a byte array
* @return a DERObject * @return a DERObject
*/ */
@ -1025,14 +1032,14 @@ public class PdfPKCS7 {
ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc)); ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
ASN1Sequence seq = (ASN1Sequence) in.readObject(); ASN1Sequence seq = (ASN1Sequence) in.readObject();
return (ASN1Object) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 3 : 2); return (ASN1Object) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 3 : 2);
} } catch (IOException e) {
catch (IOException e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Get the "subject" from the TBSCertificate bytes that are passed in * Get the "subject" from the TBSCertificate bytes that are passed in
*
* @param enc A TBSCertificate in a byte array * @param enc A TBSCertificate in a byte array
* @return a DERObject * @return a DERObject
*/ */
@ -1041,42 +1048,42 @@ public class PdfPKCS7 {
ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc)); ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
ASN1Sequence seq = (ASN1Sequence) in.readObject(); ASN1Sequence seq = (ASN1Sequence) in.readObject();
return (ASN1Object) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 5 : 4); return (ASN1Object) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 5 : 4);
} } catch (IOException e) {
catch (IOException e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Get the issuer fields from an X509 Certificate * Get the issuer fields from an X509 Certificate
*
* @param cert an X509Certificate * @param cert an X509Certificate
* @return an X509Name * @return an X509Name
*/ */
public static X509Name getIssuerFields(X509Certificate cert) { public static X509Name getIssuerFields(X509Certificate cert) {
try { try {
return new X509Name((ASN1Sequence) getIssuer(cert.getTBSCertificate())); return new X509Name((ASN1Sequence) getIssuer(cert.getTBSCertificate()));
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Get the subject fields from an X509 Certificate * Get the subject fields from an X509 Certificate
*
* @param cert an X509Certificate * @param cert an X509Certificate
* @return an X509Name * @return an X509Name
*/ */
public static X509Name getSubjectFields(X509Certificate cert) { public static X509Name getSubjectFields(X509Certificate cert) {
try { try {
return new X509Name((ASN1Sequence) getSubject(cert.getTBSCertificate())); return new X509Name((ASN1Sequence) getSubject(cert.getTBSCertificate()));
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Gets the bytes for the PKCS#1 object. * Gets the bytes for the PKCS#1 object.
*
* @return a byte array * @return a byte array
*/ */
public byte[] getEncodedPKCS1() { public byte[] getEncodedPKCS1() {
@ -1092,14 +1099,14 @@ public class PdfPKCS7 {
dout.close(); dout.close();
return bOut.toByteArray(); return bOut.toByteArray();
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Sets the digest/signature to an external calculated value. * Sets the digest/signature to an external calculated value.
*
* @param digest the digest. This is the actual signature * @param digest the digest. This is the actual signature
* @param RSAdata the extra data that goes into the data tag in PKCS#7 * @param RSAdata the extra data that goes into the data tag in PKCS#7
* @param digestEncryptionAlgorithm the encryption algorithm. It may must be <CODE>null</CODE> if the <CODE>digest</CODE> * @param digestEncryptionAlgorithm the encryption algorithm. It may must be <CODE>null</CODE> if the <CODE>digest</CODE>
@ -1112,17 +1119,16 @@ public class PdfPKCS7 {
if (digestEncryptionAlgorithm != null) { if (digestEncryptionAlgorithm != null) {
if (digestEncryptionAlgorithm.equals("RSA")) { if (digestEncryptionAlgorithm.equals("RSA")) {
this.digestEncryptionAlgorithm = ID_RSA; this.digestEncryptionAlgorithm = ID_RSA;
} } else if (digestEncryptionAlgorithm.equals("DSA")) {
else if (digestEncryptionAlgorithm.equals("DSA")) {
this.digestEncryptionAlgorithm = ID_DSA; this.digestEncryptionAlgorithm = ID_DSA;
} } else
else
throw new ExceptionConverter(new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm)); throw new ExceptionConverter(new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm));
} }
} }
/** /**
* Gets the bytes for the PKCS7SignedData object. * Gets the bytes for the PKCS7SignedData object.
*
* @return the bytes for the PKCS7SignedData object * @return the bytes for the PKCS7SignedData object
*/ */
public byte[] getEncodedPKCS7() { public byte[] getEncodedPKCS7() {
@ -1132,6 +1138,7 @@ public class PdfPKCS7 {
/** /**
* Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
* in the signerInfo can also be set. If either of the parameters is <CODE>null</CODE>, none will be used. * in the signerInfo can also be set. If either of the parameters is <CODE>null</CODE>, none will be used.
*
* @param secondDigest the digest in the authenticatedAttributes * @param secondDigest the digest in the authenticatedAttributes
* @param signingTime the signing time in the authenticatedAttributes * @param signingTime the signing time in the authenticatedAttributes
* @return the bytes for the PKCS7SignedData object * @return the bytes for the PKCS7SignedData object
@ -1144,6 +1151,7 @@ public class PdfPKCS7 {
* Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
* in the signerInfo can also be set, OR a time-stamp-authority client * in the signerInfo can also be set, OR a time-stamp-authority client
* may be provided. * may be provided.
*
* @param secondDigest the digest in the authenticatedAttributes * @param secondDigest the digest in the authenticatedAttributes
* @param signingTime the signing time in the authenticatedAttributes * @param signingTime the signing time in the authenticatedAttributes
* @param tsaClient TSAClient - null or an optional time stamp authority client * @param tsaClient TSAClient - null or an optional time stamp authority client
@ -1156,13 +1164,11 @@ public class PdfPKCS7 {
digest = externalDigest; digest = externalDigest;
if (RSAdata != null) if (RSAdata != null)
RSAdata = externalRSAdata; RSAdata = externalRSAdata;
} } else if (externalRSAdata != null && RSAdata != null) {
else if (externalRSAdata != null && RSAdata != null) {
RSAdata = externalRSAdata; RSAdata = externalRSAdata;
sig.update(RSAdata); sig.update(RSAdata);
digest = sig.sign(); digest = sig.sign();
} } else {
else {
if (RSAdata != null) { if (RSAdata != null) {
RSAdata = messageDigest.digest(); RSAdata = messageDigest.digest();
sig.update(RSAdata); sig.update(RSAdata);
@ -1174,14 +1180,14 @@ public class PdfPKCS7 {
ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector(); ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector();
for (Iterator it = digestalgos.iterator(); it.hasNext(); ) { for (Iterator it = digestalgos.iterator(); it.hasNext(); ) {
ASN1EncodableVector algos = new ASN1EncodableVector(); ASN1EncodableVector algos = new ASN1EncodableVector();
algos.add(new DERObjectIdentifier((String)it.next())); algos.add(new ASN1ObjectIdentifier((String) it.next()));
algos.add(DERNull.INSTANCE); algos.add(DERNull.INSTANCE);
digestAlgorithms.add(new DERSequence(algos)); digestAlgorithms.add(new DERSequence(algos));
} }
// Create the contentInfo. // Create the contentInfo.
ASN1EncodableVector v = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_PKCS7_DATA)); v.add(new ASN1ObjectIdentifier(ID_PKCS7_DATA));
if (RSAdata != null) if (RSAdata != null)
v.add(new DERTaggedObject(0, new DEROctetString(RSAdata))); v.add(new DERTaggedObject(0, new DEROctetString(RSAdata)));
DERSequence contentinfo = new DERSequence(v); DERSequence contentinfo = new DERSequence(v);
@ -1202,17 +1208,17 @@ public class PdfPKCS7 {
// Add the signerInfo version // Add the signerInfo version
// //
signerinfo.add(new DERInteger(signerversion)); signerinfo.add(new ASN1Integer(signerversion));
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(getIssuer(signCert.getTBSCertificate())); v.add(getIssuer(signCert.getTBSCertificate()));
v.add(new DERInteger(signCert.getSerialNumber())); v.add(new ASN1Integer(signCert.getSerialNumber()));
signerinfo.add(new DERSequence(v)); signerinfo.add(new DERSequence(v));
// Add the digestAlgorithm // Add the digestAlgorithm
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(digestAlgorithm)); v.add(new ASN1ObjectIdentifier(digestAlgorithm));
v.add(new DERNull()); v.add(DERNull.INSTANCE);
signerinfo.add(new DERSequence(v)); signerinfo.add(new DERSequence(v));
// add the authenticated attribute if present // add the authenticated attribute if present
@ -1221,8 +1227,8 @@ public class PdfPKCS7 {
} }
// Add the digestEncryptionAlgorithm // Add the digestEncryptionAlgorithm
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(digestEncryptionAlgorithm)); v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithm));
v.add(new DERNull()); v.add(DERNull.INSTANCE);
signerinfo.add(new DERSequence(v)); signerinfo.add(new DERSequence(v));
// Add the digest // Add the digest
@ -1244,7 +1250,7 @@ public class PdfPKCS7 {
// Finally build the body out of all the components above // Finally build the body out of all the components above
ASN1EncodableVector body = new ASN1EncodableVector(); ASN1EncodableVector body = new ASN1EncodableVector();
body.add(new DERInteger(version)); body.add(new ASN1Integer(version));
body.add(new DERSet(digestAlgorithms)); body.add(new DERSet(digestAlgorithms));
body.add(contentinfo); body.add(contentinfo);
body.add(new DERTaggedObject(false, 0, dercertificates)); body.add(new DERTaggedObject(false, 0, dercertificates));
@ -1266,7 +1272,7 @@ public class PdfPKCS7 {
// and return it // and return it
// //
ASN1EncodableVector whole = new ASN1EncodableVector(); ASN1EncodableVector whole = new ASN1EncodableVector();
whole.add(new DERObjectIdentifier(ID_PKCS7_SIGNED_DATA)); whole.add(new ASN1ObjectIdentifier(ID_PKCS7_SIGNED_DATA));
whole.add(new DERTaggedObject(0, new DERSequence(body))); whole.add(new DERTaggedObject(0, new DERSequence(body)));
ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayOutputStream bOut = new ByteArrayOutputStream();
@ -1276,8 +1282,7 @@ public class PdfPKCS7 {
dout.close(); dout.close();
return bOut.toByteArray(); return bOut.toByteArray();
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
@ -1287,6 +1292,7 @@ public class PdfPKCS7 {
* to start with the timeStampToken (signedData 1.2.840.113549.1.7.2). * to start with the timeStampToken (signedData 1.2.840.113549.1.7.2).
* Token is the TSA response without response status, which is usually * Token is the TSA response without response status, which is usually
* handled by the (vendor supplied) TSA request/response interface). * handled by the (vendor supplied) TSA request/response interface).
*
* @param timeStampToken byte[] - time stamp token, DER encoded signedData * @param timeStampToken byte[] - time stamp token, DER encoded signedData
* @return ASN1EncodableVector * @return ASN1EncodableVector
* @throws IOException * @throws IOException
@ -1302,7 +1308,7 @@ public class PdfPKCS7 {
ASN1EncodableVector unauthAttributes = new ASN1EncodableVector(); ASN1EncodableVector unauthAttributes = new ASN1EncodableVector();
ASN1EncodableVector v = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken v.add(new ASN1ObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken
ASN1Sequence seq = (ASN1Sequence) tempstream.readObject(); ASN1Sequence seq = (ASN1Sequence) tempstream.readObject();
v.add(new DERSet(seq)); v.add(new DERSet(seq));
@ -1334,6 +1340,7 @@ public class PdfPKCS7 {
* pk7.update(sh, 0, sh.length); * pk7.update(sh, 0, sh.length);
* byte sg[] = pk7.getEncodedPKCS7(hash, cal); * byte sg[] = pk7.getEncodedPKCS7(hash, cal);
* </pre> * </pre>
*
* @param secondDigest the content digest * @param secondDigest the content digest
* @param signingTime the signing time * @param signingTime the signing time
* @return the byte array representation of the authenticatedAttributes ready to be signed * @return the byte array representation of the authenticatedAttributes ready to be signed
@ -1341,8 +1348,7 @@ public class PdfPKCS7 {
public byte[] getAuthenticatedAttributeBytes(byte secondDigest[], Calendar signingTime, byte[] ocsp) { public byte[] getAuthenticatedAttributeBytes(byte secondDigest[], Calendar signingTime, byte[] ocsp) {
try { try {
return getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp).getEncoded("DER"); return getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp).getEncoded("DER");
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
@ -1351,36 +1357,35 @@ public class PdfPKCS7 {
try { try {
ASN1EncodableVector attribute = new ASN1EncodableVector(); ASN1EncodableVector attribute = new ASN1EncodableVector();
ASN1EncodableVector v = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_CONTENT_TYPE)); v.add(new ASN1ObjectIdentifier(ID_CONTENT_TYPE));
v.add(new DERSet(new DERObjectIdentifier(ID_PKCS7_DATA))); v.add(new DERSet(new ASN1ObjectIdentifier(ID_PKCS7_DATA)));
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_SIGNING_TIME)); v.add(new ASN1ObjectIdentifier(ID_SIGNING_TIME));
v.add(new DERSet(new DERUTCTime(signingTime.getTime()))); v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_MESSAGE_DIGEST)); v.add(new ASN1ObjectIdentifier(ID_MESSAGE_DIGEST));
v.add(new DERSet(new DEROctetString(secondDigest))); v.add(new DERSet(new DEROctetString(secondDigest)));
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
if (ocsp != null) { if (ocsp != null) {
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION)); v.add(new ASN1ObjectIdentifier(ID_ADBE_REVOCATION));
DEROctetString doctet = new DEROctetString(ocsp); DEROctetString doctet = new DEROctetString(ocsp);
ASN1EncodableVector vo1 = new ASN1EncodableVector(); ASN1EncodableVector vo1 = new ASN1EncodableVector();
ASN1EncodableVector v2 = new ASN1EncodableVector(); ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic); v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
v2.add(doctet); v2.add(doctet);
DEREnumerated den = new DEREnumerated(0); ASN1Enumerated den = new ASN1Enumerated(0);
ASN1EncodableVector v3 = new ASN1EncodableVector(); ASN1EncodableVector v3 = new ASN1EncodableVector();
v3.add(den); v3.add(den);
v3.add(new DERTaggedObject(true, 0, new DERSequence(v2))); v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
vo1.add(new DERSequence(v3)); vo1.add(new DERSequence(v3));
v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 1, new DERSequence(vo1))))); v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 1, new DERSequence(vo1)))));
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
} } else if (!crls.isEmpty()) {
else if (!crls.isEmpty()) {
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION)); v.add(new ASN1ObjectIdentifier(ID_ADBE_REVOCATION));
ASN1EncodableVector v2 = new ASN1EncodableVector(); ASN1EncodableVector v2 = new ASN1EncodableVector();
for (Iterator i = crls.iterator(); i.hasNext(); ) { for (Iterator i = crls.iterator(); i.hasNext(); ) {
ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(((X509CRL) i.next()).getEncoded())); ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(((X509CRL) i.next()).getEncoded()));
@ -1390,14 +1395,14 @@ public class PdfPKCS7 {
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
} }
return new DERSet(attribute); return new DERSet(attribute);
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Getter for property reason. * Getter for property reason.
*
* @return Value of property reason. * @return Value of property reason.
*/ */
public String getReason() { public String getReason() {
@ -1406,6 +1411,7 @@ public class PdfPKCS7 {
/** /**
* Setter for property reason. * Setter for property reason.
*
* @param reason New value of property reason. * @param reason New value of property reason.
*/ */
public void setReason(String reason) { public void setReason(String reason) {
@ -1414,6 +1420,7 @@ public class PdfPKCS7 {
/** /**
* Getter for property location. * Getter for property location.
*
* @return Value of property location. * @return Value of property location.
*/ */
public String getLocation() { public String getLocation() {
@ -1422,6 +1429,7 @@ public class PdfPKCS7 {
/** /**
* Setter for property location. * Setter for property location.
*
* @param location New value of property location. * @param location New value of property location.
*/ */
public void setLocation(String location) { public void setLocation(String location) {
@ -1430,6 +1438,7 @@ public class PdfPKCS7 {
/** /**
* Getter for property signDate. * Getter for property signDate.
*
* @return Value of property signDate. * @return Value of property signDate.
*/ */
public Calendar getSignDate() { public Calendar getSignDate() {
@ -1438,6 +1447,7 @@ public class PdfPKCS7 {
/** /**
* Setter for property signDate. * Setter for property signDate.
*
* @param signDate New value of property signDate. * @param signDate New value of property signDate.
*/ */
public void setSignDate(Calendar signDate) { public void setSignDate(Calendar signDate) {
@ -1446,6 +1456,7 @@ public class PdfPKCS7 {
/** /**
* Getter for property sigName. * Getter for property sigName.
*
* @return Value of property sigName. * @return Value of property sigName.
*/ */
public String getSignName() { public String getSignName() {
@ -1454,6 +1465,7 @@ public class PdfPKCS7 {
/** /**
* Setter for property sigName. * Setter for property sigName.
*
* @param signName New value of property sigName. * @param signName New value of property sigName.
*/ */
public void setSignName(String signName) { public void setSignName(String signName) {
@ -1467,72 +1479,88 @@ public class PdfPKCS7 {
/** /**
* country code - StringType(SIZE(2)) * country code - StringType(SIZE(2))
*/ */
public static final DERObjectIdentifier C = new DERObjectIdentifier("2.5.4.6"); public static final ASN1ObjectIdentifier C = new ASN1ObjectIdentifier("2.5.4.6");
/** /**
* organization - StringType(SIZE(1..64)) * organization - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier O = new DERObjectIdentifier("2.5.4.10"); public static final ASN1ObjectIdentifier O = new ASN1ObjectIdentifier("2.5.4.10");
/** /**
* organizational unit name - StringType(SIZE(1..64)) * organizational unit name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier OU = new DERObjectIdentifier("2.5.4.11"); public static final ASN1ObjectIdentifier OU = new ASN1ObjectIdentifier("2.5.4.11");
/** /**
* Title * Title
*/ */
public static final DERObjectIdentifier T = new DERObjectIdentifier("2.5.4.12"); public static final ASN1ObjectIdentifier T = new ASN1ObjectIdentifier("2.5.4.12");
/** /**
* common name - StringType(SIZE(1..64)) * common name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier CN = new DERObjectIdentifier("2.5.4.3"); public static final ASN1ObjectIdentifier CN = new ASN1ObjectIdentifier("2.5.4.3");
/** /**
* device serial number name - StringType(SIZE(1..64)) * device serial number name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier SN = new DERObjectIdentifier("2.5.4.5"); public static final ASN1ObjectIdentifier SN = new ASN1ObjectIdentifier("2.5.4.5");
/** /**
* locality name - StringType(SIZE(1..64)) * locality name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier L = new DERObjectIdentifier("2.5.4.7"); public static final ASN1ObjectIdentifier L = new ASN1ObjectIdentifier("2.5.4.7");
/** /**
* state, or province name - StringType(SIZE(1..64)) * state, or province name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier ST = new DERObjectIdentifier("2.5.4.8"); public static final ASN1ObjectIdentifier ST = new ASN1ObjectIdentifier("2.5.4.8");
/** Naming attribute of type X520name */ /**
public static final DERObjectIdentifier SURNAME = new DERObjectIdentifier("2.5.4.4"); * Naming attribute of type X520name
/** Naming attribute of type X520name */ */
public static final DERObjectIdentifier GIVENNAME = new DERObjectIdentifier("2.5.4.42"); public static final ASN1ObjectIdentifier SURNAME = new ASN1ObjectIdentifier("2.5.4.4");
/** Naming attribute of type X520name */ /**
public static final DERObjectIdentifier INITIALS = new DERObjectIdentifier("2.5.4.43"); * Naming attribute of type X520name
/** Naming attribute of type X520name */ */
public static final DERObjectIdentifier GENERATION = new DERObjectIdentifier("2.5.4.44"); public static final ASN1ObjectIdentifier GIVENNAME = new ASN1ObjectIdentifier("2.5.4.42");
/** Naming attribute of type X520name */ /**
public static final DERObjectIdentifier UNIQUE_IDENTIFIER = new DERObjectIdentifier("2.5.4.45"); * Naming attribute of type X520name
*/
public static final ASN1ObjectIdentifier INITIALS = new ASN1ObjectIdentifier("2.5.4.43");
/**
* Naming attribute of type X520name
*/
public static final ASN1ObjectIdentifier GENERATION = new ASN1ObjectIdentifier("2.5.4.44");
/**
* Naming attribute of type X520name
*/
public static final ASN1ObjectIdentifier UNIQUE_IDENTIFIER = new ASN1ObjectIdentifier("2.5.4.45");
/** /**
* Email address (RSA PKCS#9 extension) - IA5String. * Email address (RSA PKCS#9 extension) - IA5String.
* <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here. * <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.
*/ */
public static final DERObjectIdentifier EmailAddress = new DERObjectIdentifier("1.2.840.113549.1.9.1"); public static final ASN1ObjectIdentifier EmailAddress = new ASN1ObjectIdentifier("1.2.840.113549.1.9.1");
/** /**
* email address in Verisign certificates * email address in Verisign certificates
*/ */
public static final DERObjectIdentifier E = EmailAddress; public static final ASN1ObjectIdentifier E = EmailAddress;
/** object identifier */ /**
public static final DERObjectIdentifier DC = new DERObjectIdentifier("0.9.2342.19200300.100.1.25"); * object identifier
*/
public static final ASN1ObjectIdentifier DC = new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.25");
/** LDAP User id. */ /**
public static final DERObjectIdentifier UID = new DERObjectIdentifier("0.9.2342.19200300.100.1.1"); * LDAP User id.
*/
public static final ASN1ObjectIdentifier UID = new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.1");
/** A HashMap with default symbols */ /**
* A HashMap with default symbols
*/
public static HashMap DefaultSymbols = new HashMap(); public static HashMap DefaultSymbols = new HashMap();
static { static {
@ -1552,11 +1580,15 @@ public class PdfPKCS7 {
DefaultSymbols.put(INITIALS, "INITIALS"); DefaultSymbols.put(INITIALS, "INITIALS");
DefaultSymbols.put(GENERATION, "GENERATION"); DefaultSymbols.put(GENERATION, "GENERATION");
} }
/** A HashMap with values */
/**
* A HashMap with values
*/
public HashMap values = new HashMap(); public HashMap values = new HashMap();
/** /**
* Constructs an X509 name * Constructs an X509 name
*
* @param seq an ASN1 Sequence * @param seq an ASN1 Sequence
*/ */
public X509Name(ASN1Sequence seq) { public X509Name(ASN1Sequence seq) {
@ -1579,8 +1611,10 @@ public class PdfPKCS7 {
} }
} }
} }
/** /**
* Constructs an X509 name * Constructs an X509 name
*
* @param dirName a directory name * @param dirName a directory name
*/ */
public X509Name(String dirName) { public X509Name(String dirName) {
@ -1613,6 +1647,7 @@ public class PdfPKCS7 {
/** /**
* gets a field array from the values Hashmap * gets a field array from the values Hashmap
*
* @param name * @param name
* @return an ArrayList * @return an ArrayList
*/ */
@ -1623,6 +1658,7 @@ public class PdfPKCS7 {
/** /**
* getter for values * getter for values
*
* @return a HashMap with the fields of the X509 name * @return a HashMap with the fields of the X509 name
*/ */
public HashMap getFields() { public HashMap getFields() {
@ -1675,24 +1711,19 @@ public class PdfPKCS7 {
if (c == '"') { if (c == '"') {
if (!escaped) { if (!escaped) {
quoted = !quoted; quoted = !quoted;
} } else {
else {
buf.append(c); buf.append(c);
} }
escaped = false; escaped = false;
} } else {
else {
if (escaped || quoted) { if (escaped || quoted) {
buf.append(c); buf.append(c);
escaped = false; escaped = false;
} } else if (c == '\\') {
else if (c == '\\') {
escaped = true; escaped = true;
} } else if (c == ',') {
else if (c == ',') {
break; break;
} } else {
else {
buf.append(c); buf.append(c);
} }
} }

50
fine-itext-old/src/main/java/com/fr/third/com/lowagie/text/pdf/PdfPublicKeySecurityHandler.java

@ -49,11 +49,39 @@
/** /**
* The below 2 methods are from pdfbox. * The below 2 methods are from pdfbox.
* * <p>
* private DERObject createDERForRecipient(byte[] in, X509Certificate cert) ; * private DERObject createDERForRecipient(byte[] in, X509Certificate cert) ;
* private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0); * private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0);
* * <p>
* 2006-11-22 Aiken Sam. * 2006-11-22 Aiken Sam.
* <p>
* Copyright (c) 2003-2006, www.pdfbox.org
* All rights reserved.
* <p>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* <p>
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of pdfbox; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
* <p>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* <p>
* http://www.pdfbox.org
*/ */
/** /**
@ -90,7 +118,9 @@
package com.fr.third.com.lowagie.text.pdf; package com.fr.third.com.lowagie.text.pdf;
import com.fr.third.org.bouncycastle.asn1.ASN1Object; import com.fr.third.org.bouncycastle.asn1.ASN1Object;
import com.fr.third.org.bouncycastle.asn1.ASN1OutputStream;
import com.fr.third.org.bouncycastle.asn1.ASN1Set; import com.fr.third.org.bouncycastle.asn1.ASN1Set;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@ -110,9 +140,8 @@ import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import com.fr.third.org.bouncycastle.asn1.ASN1InputStream; import com.fr.third.org.bouncycastle.asn1.ASN1InputStream;
import com.fr.third.org.bouncycastle.asn1.DERObjectIdentifier; import com.fr.third.org.bouncycastle.asn1.ASN1ObjectIdentifier;
import com.fr.third.org.bouncycastle.asn1.DEROctetString; import com.fr.third.org.bouncycastle.asn1.DEROctetString;
import com.fr.third.org.bouncycastle.asn1.DEROutputStream;
import com.fr.third.org.bouncycastle.asn1.DERSet; import com.fr.third.org.bouncycastle.asn1.DERSet;
import com.fr.third.org.bouncycastle.asn1.cms.ContentInfo; import com.fr.third.org.bouncycastle.asn1.cms.ContentInfo;
import com.fr.third.org.bouncycastle.asn1.cms.EncryptedContentInfo; import com.fr.third.org.bouncycastle.asn1.cms.EncryptedContentInfo;
@ -161,7 +190,8 @@ public class PdfPublicKeySecurityHandler {
int index = 0; int index = 0;
if (bytes[0] != '(' && bytes[bytes.length-1] != ')') throw new BadPdfFormatException("Expect '(' and ')' at begin and end of the string."); if (bytes[0] != '(' && bytes[bytes.length - 1] != ')')
throw new BadPdfFormatException("Expect '(' and ')' at begin and end of the string.");
while (index < bytes.length) { while (index < bytes.length) {
if (bytes[index] == '\\') { if (bytes[index] == '\\') {
@ -249,7 +279,7 @@ public class PdfPublicKeySecurityHandler {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
DEROutputStream k = new DEROutputStream(baos); ASN1OutputStream k = ASN1OutputStream.create(baos);
k.writeObject(obj); k.writeObject(obj);
@ -279,8 +309,7 @@ public class PdfPublicKeySecurityHandler {
private ASN1Object createDERForRecipient(byte[] in, X509Certificate cert) private ASN1Object createDERForRecipient(byte[] in, X509Certificate cert)
throws IOException, throws IOException,
GeneralSecurityException GeneralSecurityException {
{
String s = "1.2.840.113549.3.2"; String s = "1.2.840.113549.3.2";
@ -298,7 +327,7 @@ public class PdfPublicKeySecurityHandler {
DEROctetString deroctetstring = new DEROctetString(abyte1); DEROctetString deroctetstring = new DEROctetString(abyte1);
KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded()); KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo)); DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
EncryptedContentInfo encryptedcontentinfo = EncryptedContentInfo encryptedcontentinfo =
new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring); new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (ASN1Set) null); EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (ASN1Set) null);
@ -308,8 +337,7 @@ public class PdfPublicKeySecurityHandler {
} }
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
throws GeneralSecurityException, IOException throws GeneralSecurityException, IOException {
{
ASN1InputStream asn1inputstream = ASN1InputStream asn1inputstream =
new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate())); new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure tbscertificatestructure =

307
fine-itext/src/main/java/com/fr/third/v2/lowagie/text/pdf/PdfPKCS7.java

@ -48,6 +48,7 @@ package com.fr.third.v2.lowagie.text.pdf;
import com.fr.third.org.bouncycastle.asn1.ASN1Object; import com.fr.third.org.bouncycastle.asn1.ASN1Object;
import com.fr.third.org.bouncycastle.asn1.ASN1String; import com.fr.third.org.bouncycastle.asn1.ASN1String;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -78,17 +79,16 @@ import java.util.Iterator;
import java.util.Set; import java.util.Set;
import com.fr.third.v2.lowagie.text.ExceptionConverter; import com.fr.third.v2.lowagie.text.ExceptionConverter;
import com.fr.third.org.bouncycastle.asn1.ASN1Encodable;
import com.fr.third.org.bouncycastle.asn1.ASN1EncodableVector; import com.fr.third.org.bouncycastle.asn1.ASN1EncodableVector;
import com.fr.third.org.bouncycastle.asn1.ASN1InputStream; import com.fr.third.org.bouncycastle.asn1.ASN1InputStream;
import com.fr.third.org.bouncycastle.asn1.ASN1OutputStream; import com.fr.third.org.bouncycastle.asn1.ASN1OutputStream;
import com.fr.third.org.bouncycastle.asn1.ASN1Sequence; import com.fr.third.org.bouncycastle.asn1.ASN1Sequence;
import com.fr.third.org.bouncycastle.asn1.ASN1Set; import com.fr.third.org.bouncycastle.asn1.ASN1Set;
import com.fr.third.org.bouncycastle.asn1.ASN1TaggedObject; import com.fr.third.org.bouncycastle.asn1.ASN1TaggedObject;
import com.fr.third.org.bouncycastle.asn1.DEREnumerated; import com.fr.third.org.bouncycastle.asn1.ASN1Enumerated;
import com.fr.third.org.bouncycastle.asn1.DERInteger; import com.fr.third.org.bouncycastle.asn1.ASN1Integer;
import com.fr.third.org.bouncycastle.asn1.DERNull; import com.fr.third.org.bouncycastle.asn1.DERNull;
import com.fr.third.org.bouncycastle.asn1.DERObjectIdentifier; import com.fr.third.org.bouncycastle.asn1.ASN1ObjectIdentifier;
import com.fr.third.org.bouncycastle.asn1.DEROctetString; import com.fr.third.org.bouncycastle.asn1.DEROctetString;
import com.fr.third.org.bouncycastle.asn1.DERSequence; import com.fr.third.org.bouncycastle.asn1.DERSequence;
import com.fr.third.org.bouncycastle.asn1.DERSet; import com.fr.third.org.bouncycastle.asn1.DERSet;
@ -102,16 +102,11 @@ import com.fr.third.org.bouncycastle.jce.provider.X509CRLParser;
import com.fr.third.org.bouncycastle.jce.provider.X509CertParser; import com.fr.third.org.bouncycastle.jce.provider.X509CertParser;
import java.security.cert.CertificateParsingException; import java.security.cert.CertificateParsingException;
import java.util.Date;
import com.fr.third.org.bouncycastle.asn1.ASN1OctetString; import com.fr.third.org.bouncycastle.asn1.ASN1OctetString;
import com.fr.third.org.bouncycastle.asn1.cms.ContentInfo; import com.fr.third.org.bouncycastle.asn1.cms.ContentInfo;
import com.fr.third.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import com.fr.third.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import com.fr.third.org.bouncycastle.asn1.tsp.MessageImprint;
import com.fr.third.org.bouncycastle.asn1.x509.X509Extensions; import com.fr.third.org.bouncycastle.asn1.x509.X509Extensions;
//import org.bouncycastle.ocsp.BasicOCSPResp;
//import org.bouncycastle.ocsp.CertificateID;
//import org.bouncycastle.ocsp.SingleResp;
//import org.bouncycastle.tsp.TimeStampToken;
/** /**
* This class does all the processing related to signing and verifying a PKCS#7 * This class does all the processing related to signing and verifying a PKCS#7
@ -242,6 +237,7 @@ public class PdfPKCS7 {
/** /**
* Gets the digest name for a certain id * Gets the digest name for a certain id
*
* @param oid an id (for instance "1.2.840.113549.2.5") * @param oid an id (for instance "1.2.840.113549.2.5")
* @return a digest name (for instance "MD5") * @return a digest name (for instance "MD5")
* @since 2.1.6 * @since 2.1.6
@ -256,6 +252,7 @@ public class PdfPKCS7 {
/** /**
* Gets the algorithm name for a certain id. * Gets the algorithm name for a certain id.
*
* @param oid an id (for instance "1.2.840.113549.1.1.1") * @param oid an id (for instance "1.2.840.113549.1.1.1")
* @return an algorithm name (for instance "RSA") * @return an algorithm name (for instance "RSA")
* @since 2.1.6 * @since 2.1.6
@ -293,6 +290,7 @@ public class PdfPKCS7 {
/** /**
* Verifies a signature using the sub-filter adbe.x509.rsa_sha1. * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
*
* @param contentsKey the /Contents key * @param contentsKey the /Contents key
* @param certsKey the /Cert key * @param certsKey the /Cert key
* @param provider the provider or <code>null</code> for the default provider * @param provider the provider or <code>null</code> for the default provider
@ -313,8 +311,7 @@ public class PdfPKCS7 {
else else
sig = Signature.getInstance("SHA1withRSA", provider); sig = Signature.getInstance("SHA1withRSA", provider);
sig.initVerify(signCert.getPublicKey()); sig.initVerify(signCert.getPublicKey());
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
@ -323,19 +320,19 @@ public class PdfPKCS7 {
/** /**
* Gets the OCSP basic response if there is one. * Gets the OCSP basic response if there is one.
*
* @return the OCSP basic response or null * @return the OCSP basic response or null
* @since 2.1.6 * @since 2.1.6
*/ */
// public BasicOCSPResp getOcsp() { // public BasicOCSPResp getOcsp() {
// return basicResp; // return basicResp;
// } // }
private void findOcsp(ASN1Sequence seq) throws IOException { private void findOcsp(ASN1Sequence seq) throws IOException {
// basicResp = null; // basicResp = null;
boolean ret = false; boolean ret = false;
while (true) { while (true) {
if ((seq.getObjectAt(0) instanceof DERObjectIdentifier) if ((seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
&& ((DERObjectIdentifier)seq.getObjectAt(0)).getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) { && ((ASN1ObjectIdentifier) seq.getObjectAt(0)).getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) {
break; break;
} }
ret = true; ret = true;
@ -351,8 +348,7 @@ public class PdfPKCS7 {
seq = (ASN1Sequence) tag.getObject(); seq = (ASN1Sequence) tag.getObject();
ret = false; ret = false;
break; break;
} } else
else
return; return;
} }
} }
@ -368,6 +364,7 @@ public class PdfPKCS7 {
/** /**
* Verifies a signature using the sub-filter adbe.pkcs7.detached or * Verifies a signature using the sub-filter adbe.pkcs7.detached or
* adbe.pkcs7.sha1. * adbe.pkcs7.sha1.
*
* @param contentsKey the /Contents key * @param contentsKey the /Contents key
* @param provider the provider or <code>null</code> for the default provider * @param provider the provider or <code>null</code> for the default provider
*/ */
@ -383,15 +380,14 @@ public class PdfPKCS7 {
try { try {
pkcs = din.readObject(); pkcs = din.readObject();
} } catch (IOException e) {
catch (IOException e) {
throw new IllegalArgumentException("can't decode PKCS7SignedData object"); throw new IllegalArgumentException("can't decode PKCS7SignedData object");
} }
if (!(pkcs instanceof ASN1Sequence)) { if (!(pkcs instanceof ASN1Sequence)) {
throw new IllegalArgumentException("Not a valid PKCS#7 object - not a sequence"); throw new IllegalArgumentException("Not a valid PKCS#7 object - not a sequence");
} }
ASN1Sequence signedData = (ASN1Sequence) pkcs; ASN1Sequence signedData = (ASN1Sequence) pkcs;
DERObjectIdentifier objId = (DERObjectIdentifier)signedData.getObjectAt(0); ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0);
if (!objId.getId().equals(ID_PKCS7_SIGNED_DATA)) if (!objId.getId().equals(ID_PKCS7_SIGNED_DATA))
throw new IllegalArgumentException("Not a valid PKCS#7 object - not signed data"); throw new IllegalArgumentException("Not a valid PKCS#7 object - not signed data");
ASN1Sequence content = (ASN1Sequence) ((DERTaggedObject) signedData.getObjectAt(1)).getObject(); ASN1Sequence content = (ASN1Sequence) ((DERTaggedObject) signedData.getObjectAt(1)).getObject();
@ -403,15 +399,14 @@ public class PdfPKCS7 {
// last - signerInfos // last - signerInfos
// the version // the version
version = ((DERInteger)content.getObjectAt(0)).getValue().intValue(); version = ((ASN1Integer) content.getObjectAt(0)).getValue().intValue();
// the digestAlgorithms // the digestAlgorithms
digestalgos = new HashSet(); digestalgos = new HashSet();
Enumeration e = ((ASN1Set) content.getObjectAt(1)).getObjects(); Enumeration e = ((ASN1Set) content.getObjectAt(1)).getObjects();
while (e.hasMoreElements()) while (e.hasMoreElements()) {
{
ASN1Sequence s = (ASN1Sequence) e.nextElement(); ASN1Sequence s = (ASN1Sequence) e.nextElement();
DERObjectIdentifier o = (DERObjectIdentifier)s.getObjectAt(0); ASN1ObjectIdentifier o = (ASN1ObjectIdentifier) s.getObjectAt(0);
digestalgos.add(o.getId()); digestalgos.add(o.getId());
} }
@ -444,10 +439,10 @@ public class PdfPKCS7 {
// 2 - the digest algorithm // 2 - the digest algorithm
// 3 or 4 - digestEncryptionAlgorithm // 3 or 4 - digestEncryptionAlgorithm
// 4 or 5 - encryptedDigest // 4 or 5 - encryptedDigest
signerversion = ((DERInteger)signerInfo.getObjectAt(0)).getValue().intValue(); signerversion = ((ASN1Integer) signerInfo.getObjectAt(0)).getValue().intValue();
// Get the signing certificate // Get the signing certificate
ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1); ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1);
BigInteger serialNumber = ((DERInteger)issuerAndSerialNumber.getObjectAt(1)).getValue(); BigInteger serialNumber = ((ASN1Integer) issuerAndSerialNumber.getObjectAt(1)).getValue();
for (Iterator i = certs.iterator(); i.hasNext(); ) { for (Iterator i = certs.iterator(); i.hasNext(); ) {
X509Certificate cert = (X509Certificate) i.next(); X509Certificate cert = (X509Certificate) i.next();
if (serialNumber.equals(cert.getSerialNumber())) { if (serialNumber.equals(cert.getSerialNumber())) {
@ -459,7 +454,7 @@ public class PdfPKCS7 {
throw new IllegalArgumentException("Can't find signing certificate with serial " + serialNumber.toString(16)); throw new IllegalArgumentException("Can't find signing certificate with serial " + serialNumber.toString(16));
} }
signCertificateChain(); signCertificateChain();
digestAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(2)).getObjectAt(0)).getId(); digestAlgorithm = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0)).getId();
next = 3; next = 3;
if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) { if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) {
ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next); ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next);
@ -468,11 +463,10 @@ public class PdfPKCS7 {
for (int k = 0; k < sseq.size(); ++k) { for (int k = 0; k < sseq.size(); ++k) {
ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k); ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k);
if (((DERObjectIdentifier)seq2.getObjectAt(0)).getId().equals(ID_MESSAGE_DIGEST)) { if (((ASN1ObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_MESSAGE_DIGEST)) {
ASN1Set set = (ASN1Set) seq2.getObjectAt(1); ASN1Set set = (ASN1Set) seq2.getObjectAt(1);
digestAttr = ((DEROctetString) set.getObjectAt(0)).getOctets(); digestAttr = ((DEROctetString) set.getObjectAt(0)).getOctets();
} } else if (((ASN1ObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_ADBE_REVOCATION)) {
else if (((DERObjectIdentifier)seq2.getObjectAt(0)).getId().equals(ID_ADBE_REVOCATION)) {
ASN1Set setout = (ASN1Set) seq2.getObjectAt(1); ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0); ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
for (int j = 0; j < seqout.size(); ++j) { for (int j = 0; j < seqout.size(); ++j) {
@ -488,7 +482,7 @@ public class PdfPKCS7 {
throw new IllegalArgumentException("Authenticated attribute is missing the digest."); throw new IllegalArgumentException("Authenticated attribute is missing the digest.");
++next; ++next;
} }
digestEncryptionAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(next++)).getObjectAt(0)).getId(); digestEncryptionAlgorithm = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++)).getObjectAt(0)).getId();
digest = ((DEROctetString) signerInfo.getObjectAt(next++)).getOctets(); digest = ((DEROctetString) signerInfo.getObjectAt(next++)).getOctets();
if (next < signerInfo.size() && (signerInfo.getObjectAt(next) instanceof DERTaggedObject)) { if (next < signerInfo.size() && (signerInfo.getObjectAt(next) instanceof DERTaggedObject)) {
DERTaggedObject taggedObject = (DERTaggedObject) signerInfo.getObjectAt(next); DERTaggedObject taggedObject = (DERTaggedObject) signerInfo.getObjectAt(next);
@ -513,14 +507,14 @@ public class PdfPKCS7 {
else else
sig = Signature.getInstance(getDigestAlgorithm(), provider); sig = Signature.getInstance(getDigestAlgorithm(), provider);
sig.initVerify(signCert.getPublicKey()); sig.initVerify(signCert.getPublicKey());
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Generates a signature. * Generates a signature.
*
* @param privKey the private key * @param privKey the private key
* @param certChain the certificate chain * @param certChain the certificate chain
* @param crlList the certificate revocation list * @param crlList the certificate revocation list
@ -534,8 +528,7 @@ public class PdfPKCS7 {
public PdfPKCS7(PrivateKey privKey, Certificate[] certChain, CRL[] crlList, public PdfPKCS7(PrivateKey privKey, Certificate[] certChain, CRL[] crlList,
String hashAlgorithm, String provider, boolean hasRSAdata) String hashAlgorithm, String provider, boolean hasRSAdata)
throws InvalidKeyException, NoSuchProviderException, throws InvalidKeyException, NoSuchProviderException,
NoSuchAlgorithmException NoSuchAlgorithmException {
{
this.privKey = privKey; this.privKey = privKey;
this.provider = provider; this.provider = provider;
@ -570,11 +563,9 @@ public class PdfPKCS7 {
digestEncryptionAlgorithm = privKey.getAlgorithm(); digestEncryptionAlgorithm = privKey.getAlgorithm();
if (digestEncryptionAlgorithm.equals("RSA")) { if (digestEncryptionAlgorithm.equals("RSA")) {
digestEncryptionAlgorithm = ID_RSA; digestEncryptionAlgorithm = ID_RSA;
} } else if (digestEncryptionAlgorithm.equals("DSA")) {
else if (digestEncryptionAlgorithm.equals("DSA")) {
digestEncryptionAlgorithm = ID_DSA; digestEncryptionAlgorithm = ID_DSA;
} } else {
else {
throw new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm); throw new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm);
} }
} }
@ -598,6 +589,7 @@ public class PdfPKCS7 {
/** /**
* Update the digest with the specified bytes. This method is used both for signing and verifying * Update the digest with the specified bytes. This method is used both for signing and verifying
*
* @param buf the data buffer * @param buf the data buffer
* @param off the offset in the data buffer * @param off the offset in the data buffer
* @param len the data length * @param len the data length
@ -612,8 +604,9 @@ public class PdfPKCS7 {
/** /**
* Verify the digest. * Verify the digest.
* @throws SignatureException on error *
* @return <CODE>true</CODE> if the signature checks out, <CODE>false</CODE> otherwise * @return <CODE>true</CODE> if the signature checks out, <CODE>false</CODE> otherwise
* @throws SignatureException on error
*/ */
public boolean verify() throws SignatureException { public boolean verify() throws SignatureException {
if (verified) if (verified)
@ -625,8 +618,7 @@ public class PdfPKCS7 {
messageDigest.update(msd); messageDigest.update(msd);
} }
verifyResult = (Arrays.equals(messageDigest.digest(), digestAttr) && sig.verify(digest)); verifyResult = (Arrays.equals(messageDigest.digest(), digestAttr) && sig.verify(digest));
} } else {
else {
if (RSAdata != null) if (RSAdata != null)
sig.update(messageDigest.digest()); sig.update(messageDigest.digest());
verifyResult = sig.verify(digest); verifyResult = sig.verify(digest);
@ -654,6 +646,7 @@ public class PdfPKCS7 {
/** /**
* Get all the X.509 certificates associated with this PKCS#7 object in no particular order. * Get all the X.509 certificates associated with this PKCS#7 object in no particular order.
* Other certificates, from OCSP for example, will also be included. * Other certificates, from OCSP for example, will also be included.
*
* @return the X.509 certificates associated with this PKCS#7 object * @return the X.509 certificates associated with this PKCS#7 object
*/ */
public Certificate[] getCertificates() { public Certificate[] getCertificates() {
@ -664,6 +657,7 @@ public class PdfPKCS7 {
* Get the X.509 sign certificate chain associated with this PKCS#7 object. * Get the X.509 sign certificate chain associated with this PKCS#7 object.
* Only the certificates used for the main signature will be returned, with * Only the certificates used for the main signature will be returned, with
* the signing certificate first. * the signing certificate first.
*
* @return the X.509 certificates associated with this PKCS#7 object * @return the X.509 certificates associated with this PKCS#7 object
* @since 2.1.6 * @since 2.1.6
*/ */
@ -696,8 +690,7 @@ public class PdfPKCS7 {
cc.add(oc.get(k)); cc.add(oc.get(k));
oc.remove(k); oc.remove(k);
break; break;
} } catch (Exception e) {
catch (Exception e) {
} }
} }
} }
@ -706,6 +699,7 @@ public class PdfPKCS7 {
/** /**
* Get the X.509 certificate revocation lists associated with this PKCS#7 object * Get the X.509 certificate revocation lists associated with this PKCS#7 object
*
* @return the X.509 certificate revocation lists associated with this PKCS#7 object * @return the X.509 certificate revocation lists associated with this PKCS#7 object
*/ */
public Collection getCRLs() { public Collection getCRLs() {
@ -714,6 +708,7 @@ public class PdfPKCS7 {
/** /**
* Get the X.509 certificate actually used to sign the digest. * Get the X.509 certificate actually used to sign the digest.
*
* @return the X.509 certificate actually used to sign the digest * @return the X.509 certificate actually used to sign the digest
*/ */
public X509Certificate getSigningCertificate() { public X509Certificate getSigningCertificate() {
@ -722,6 +717,7 @@ public class PdfPKCS7 {
/** /**
* Get the version of the PKCS#7 object. Always 1 * Get the version of the PKCS#7 object. Always 1
*
* @return the version of the PKCS#7 object. Always 1 * @return the version of the PKCS#7 object. Always 1
*/ */
public int getVersion() { public int getVersion() {
@ -730,6 +726,7 @@ public class PdfPKCS7 {
/** /**
* Get the version of the PKCS#7 "SignerInfo" object. Always 1 * Get the version of the PKCS#7 "SignerInfo" object. Always 1
*
* @return the version of the PKCS#7 "SignerInfo" object. Always 1 * @return the version of the PKCS#7 "SignerInfo" object. Always 1
*/ */
public int getSigningInfoVersion() { public int getSigningInfoVersion() {
@ -738,6 +735,7 @@ public class PdfPKCS7 {
/** /**
* Get the algorithm used to calculate the message digest * Get the algorithm used to calculate the message digest
*
* @return the algorithm used to calculate the message digest * @return the algorithm used to calculate the message digest
*/ */
public String getDigestAlgorithm() { public String getDigestAlgorithm() {
@ -750,6 +748,7 @@ public class PdfPKCS7 {
/** /**
* Returns the algorithm. * Returns the algorithm.
*
* @return the digest algorithm * @return the digest algorithm
*/ */
public String getHashAlgorithm() { public String getHashAlgorithm() {
@ -759,6 +758,7 @@ public class PdfPKCS7 {
/** /**
* Loads the default root certificates at &lt;java.home&gt;/lib/security/cacerts * Loads the default root certificates at &lt;java.home&gt;/lib/security/cacerts
* with the default provider. * with the default provider.
*
* @return a <CODE>KeyStore</CODE> * @return a <CODE>KeyStore</CODE>
*/ */
public static KeyStore loadCacertsKeyStore() { public static KeyStore loadCacertsKeyStore() {
@ -767,6 +767,7 @@ public class PdfPKCS7 {
/** /**
* Loads the default root certificates at &lt;java.home&gt;/lib/security/cacerts. * Loads the default root certificates at &lt;java.home&gt;/lib/security/cacerts.
*
* @param provider the provider or <code>null</code> for the default provider * @param provider the provider or <code>null</code> for the default provider
* @return a <CODE>KeyStore</CODE> * @return a <CODE>KeyStore</CODE>
*/ */
@ -784,17 +785,21 @@ public class PdfPKCS7 {
k = KeyStore.getInstance("JKS", provider); k = KeyStore.getInstance("JKS", provider);
k.load(fin, null); k.load(fin, null);
return k; return k;
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (Exception ex) {
} }
finally {
try{if (fin != null) {fin.close();}}catch(Exception ex){}
} }
} }
/** /**
* Verifies a single certificate. * Verifies a single certificate.
*
* @param cert the certificate to verify * @param cert the certificate to verify
* @param crls the certificate revocation list or <CODE>null</CODE> * @param crls the certificate revocation list or <CODE>null</CODE>
* @param calendar the date or <CODE>null</CODE> for the current date * @param calendar the date or <CODE>null</CODE> for the current date
@ -808,8 +813,7 @@ public class PdfPKCS7 {
return "Has unsupported critical extension"; return "Has unsupported critical extension";
try { try {
cert.checkValidity(calendar.getTime()); cert.checkValidity(calendar.getTime());
} } catch (Exception e) {
catch (Exception e) {
return e.getMessage(); return e.getMessage();
} }
if (crls != null) { if (crls != null) {
@ -823,6 +827,7 @@ public class PdfPKCS7 {
/** /**
* Verifies a certificate chain against a KeyStore. * Verifies a certificate chain against a KeyStore.
*
* @param certs the certificate chain * @param certs the certificate chain
* @param keystore the <CODE>KeyStore</CODE> * @param keystore the <CODE>KeyStore</CODE>
* @param crls the certificate revocation list or <CODE>null</CODE> * @param crls the certificate revocation list or <CODE>null</CODE>
@ -851,16 +856,13 @@ public class PdfPKCS7 {
try { try {
cert.verify(certStoreX509.getPublicKey()); cert.verify(certStoreX509.getPublicKey());
return null; return null;
} } catch (Exception e) {
catch (Exception e) {
continue; continue;
} }
} catch (Exception ex) {
} }
catch (Exception ex) {
} }
} } catch (Exception e) {
}
catch (Exception e) {
} }
int j; int j;
for (j = 0; j < certs.length; ++j) { for (j = 0; j < certs.length; ++j) {
@ -870,8 +872,7 @@ public class PdfPKCS7 {
try { try {
cert.verify(certNext.getPublicKey()); cert.verify(certNext.getPublicKey());
break; break;
} } catch (Exception e) {
catch (Exception e) {
} }
} }
if (j == certs.length) if (j == certs.length)
@ -942,6 +943,7 @@ public class PdfPKCS7 {
/** /**
* Retrieves the OCSP URL from the given certificate. * Retrieves the OCSP URL from the given certificate.
*
* @param certificate the certificate * @param certificate the certificate
* @return the URL or null * @return the URL or null
* @throws CertificateParsingException on error * @throws CertificateParsingException on error
@ -960,7 +962,7 @@ public class PdfPKCS7 {
if (AccessDescription.size() != 2) { if (AccessDescription.size() != 2) {
continue; continue;
} else { } else {
if ((AccessDescription.getObjectAt(0) instanceof DERObjectIdentifier) && ((DERObjectIdentifier)AccessDescription.getObjectAt(0)).getId().equals("1.3.6.1.5.5.7.48.1")) { if ((AccessDescription.getObjectAt(0) instanceof ASN1ObjectIdentifier) && ((ASN1ObjectIdentifier) AccessDescription.getObjectAt(0)).getId().equals("1.3.6.1.5.5.7.48.1")) {
String AccessLocation = getStringFromGeneralName((ASN1Object) AccessDescription.getObjectAt(1)); String AccessLocation = getStringFromGeneralName((ASN1Object) AccessDescription.getObjectAt(1));
if (AccessLocation == null) { if (AccessLocation == null) {
return ""; return "";
@ -977,6 +979,7 @@ public class PdfPKCS7 {
/** /**
* Checks if OCSP revocation refers to the document signing certificate. * Checks if OCSP revocation refers to the document signing certificate.
*
* @return true if it checks false otherwise * @return true if it checks false otherwise
* @since 2.1.6 * @since 2.1.6
*/ */
@ -998,7 +1001,6 @@ public class PdfPKCS7 {
// } // }
// return false; // return false;
// } // }
private static ASN1Object getExtensionValue(X509Certificate cert, String oid) throws IOException { private static ASN1Object getExtensionValue(X509Certificate cert, String oid) throws IOException {
byte[] bytes = cert.getExtensionValue(oid); byte[] bytes = cert.getExtensionValue(oid);
if (bytes == null) { if (bytes == null) {
@ -1017,6 +1019,7 @@ public class PdfPKCS7 {
/** /**
* Get the "issuer" from the TBSCertificate bytes that are passed in * Get the "issuer" from the TBSCertificate bytes that are passed in
*
* @param enc a TBSCertificate in a byte array * @param enc a TBSCertificate in a byte array
* @return a DERObject * @return a DERObject
*/ */
@ -1025,14 +1028,14 @@ public class PdfPKCS7 {
ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc)); ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
ASN1Sequence seq = (ASN1Sequence) in.readObject(); ASN1Sequence seq = (ASN1Sequence) in.readObject();
return (ASN1Object) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 3 : 2); return (ASN1Object) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 3 : 2);
} } catch (IOException e) {
catch (IOException e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Get the "subject" from the TBSCertificate bytes that are passed in * Get the "subject" from the TBSCertificate bytes that are passed in
*
* @param enc A TBSCertificate in a byte array * @param enc A TBSCertificate in a byte array
* @return a DERObject * @return a DERObject
*/ */
@ -1041,42 +1044,42 @@ public class PdfPKCS7 {
ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc)); ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
ASN1Sequence seq = (ASN1Sequence) in.readObject(); ASN1Sequence seq = (ASN1Sequence) in.readObject();
return (ASN1Object) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 5 : 4); return (ASN1Object) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 5 : 4);
} } catch (IOException e) {
catch (IOException e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Get the issuer fields from an X509 Certificate * Get the issuer fields from an X509 Certificate
*
* @param cert an X509Certificate * @param cert an X509Certificate
* @return an X509Name * @return an X509Name
*/ */
public static X509Name getIssuerFields(X509Certificate cert) { public static X509Name getIssuerFields(X509Certificate cert) {
try { try {
return new X509Name((ASN1Sequence) getIssuer(cert.getTBSCertificate())); return new X509Name((ASN1Sequence) getIssuer(cert.getTBSCertificate()));
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Get the subject fields from an X509 Certificate * Get the subject fields from an X509 Certificate
*
* @param cert an X509Certificate * @param cert an X509Certificate
* @return an X509Name * @return an X509Name
*/ */
public static X509Name getSubjectFields(X509Certificate cert) { public static X509Name getSubjectFields(X509Certificate cert) {
try { try {
return new X509Name((ASN1Sequence) getSubject(cert.getTBSCertificate())); return new X509Name((ASN1Sequence) getSubject(cert.getTBSCertificate()));
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Gets the bytes for the PKCS#1 object. * Gets the bytes for the PKCS#1 object.
*
* @return a byte array * @return a byte array
*/ */
public byte[] getEncodedPKCS1() { public byte[] getEncodedPKCS1() {
@ -1092,14 +1095,14 @@ public class PdfPKCS7 {
dout.close(); dout.close();
return bOut.toByteArray(); return bOut.toByteArray();
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Sets the digest/signature to an external calculated value. * Sets the digest/signature to an external calculated value.
*
* @param digest the digest. This is the actual signature * @param digest the digest. This is the actual signature
* @param RSAdata the extra data that goes into the data tag in PKCS#7 * @param RSAdata the extra data that goes into the data tag in PKCS#7
* @param digestEncryptionAlgorithm the encryption algorithm. It may must be <CODE>null</CODE> if the <CODE>digest</CODE> * @param digestEncryptionAlgorithm the encryption algorithm. It may must be <CODE>null</CODE> if the <CODE>digest</CODE>
@ -1112,17 +1115,16 @@ public class PdfPKCS7 {
if (digestEncryptionAlgorithm != null) { if (digestEncryptionAlgorithm != null) {
if (digestEncryptionAlgorithm.equals("RSA")) { if (digestEncryptionAlgorithm.equals("RSA")) {
this.digestEncryptionAlgorithm = ID_RSA; this.digestEncryptionAlgorithm = ID_RSA;
} } else if (digestEncryptionAlgorithm.equals("DSA")) {
else if (digestEncryptionAlgorithm.equals("DSA")) {
this.digestEncryptionAlgorithm = ID_DSA; this.digestEncryptionAlgorithm = ID_DSA;
} } else
else
throw new ExceptionConverter(new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm)); throw new ExceptionConverter(new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm));
} }
} }
/** /**
* Gets the bytes for the PKCS7SignedData object. * Gets the bytes for the PKCS7SignedData object.
*
* @return the bytes for the PKCS7SignedData object * @return the bytes for the PKCS7SignedData object
*/ */
public byte[] getEncodedPKCS7() { public byte[] getEncodedPKCS7() {
@ -1132,6 +1134,7 @@ public class PdfPKCS7 {
/** /**
* Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
* in the signerInfo can also be set. If either of the parameters is <CODE>null</CODE>, none will be used. * in the signerInfo can also be set. If either of the parameters is <CODE>null</CODE>, none will be used.
*
* @param secondDigest the digest in the authenticatedAttributes * @param secondDigest the digest in the authenticatedAttributes
* @param signingTime the signing time in the authenticatedAttributes * @param signingTime the signing time in the authenticatedAttributes
* @return the bytes for the PKCS7SignedData object * @return the bytes for the PKCS7SignedData object
@ -1144,6 +1147,7 @@ public class PdfPKCS7 {
* Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
* in the signerInfo can also be set, OR a time-stamp-authority client * in the signerInfo can also be set, OR a time-stamp-authority client
* may be provided. * may be provided.
*
* @param secondDigest the digest in the authenticatedAttributes * @param secondDigest the digest in the authenticatedAttributes
* @param signingTime the signing time in the authenticatedAttributes * @param signingTime the signing time in the authenticatedAttributes
* @param tsaClient TSAClient - null or an optional time stamp authority client * @param tsaClient TSAClient - null or an optional time stamp authority client
@ -1156,13 +1160,11 @@ public class PdfPKCS7 {
digest = externalDigest; digest = externalDigest;
if (RSAdata != null) if (RSAdata != null)
RSAdata = externalRSAdata; RSAdata = externalRSAdata;
} } else if (externalRSAdata != null && RSAdata != null) {
else if (externalRSAdata != null && RSAdata != null) {
RSAdata = externalRSAdata; RSAdata = externalRSAdata;
sig.update(RSAdata); sig.update(RSAdata);
digest = sig.sign(); digest = sig.sign();
} } else {
else {
if (RSAdata != null) { if (RSAdata != null) {
RSAdata = messageDigest.digest(); RSAdata = messageDigest.digest();
sig.update(RSAdata); sig.update(RSAdata);
@ -1174,14 +1176,14 @@ public class PdfPKCS7 {
ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector(); ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector();
for (Iterator it = digestalgos.iterator(); it.hasNext(); ) { for (Iterator it = digestalgos.iterator(); it.hasNext(); ) {
ASN1EncodableVector algos = new ASN1EncodableVector(); ASN1EncodableVector algos = new ASN1EncodableVector();
algos.add(new DERObjectIdentifier((String)it.next())); algos.add(new ASN1ObjectIdentifier((String) it.next()));
algos.add(DERNull.INSTANCE); algos.add(DERNull.INSTANCE);
digestAlgorithms.add(new DERSequence(algos)); digestAlgorithms.add(new DERSequence(algos));
} }
// Create the contentInfo. // Create the contentInfo.
ASN1EncodableVector v = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_PKCS7_DATA)); v.add(new ASN1ObjectIdentifier(ID_PKCS7_DATA));
if (RSAdata != null) if (RSAdata != null)
v.add(new DERTaggedObject(0, new DEROctetString(RSAdata))); v.add(new DERTaggedObject(0, new DEROctetString(RSAdata)));
DERSequence contentinfo = new DERSequence(v); DERSequence contentinfo = new DERSequence(v);
@ -1202,17 +1204,17 @@ public class PdfPKCS7 {
// Add the signerInfo version // Add the signerInfo version
// //
signerinfo.add(new DERInteger(signerversion)); signerinfo.add(new ASN1Integer(signerversion));
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(getIssuer(signCert.getTBSCertificate())); v.add(getIssuer(signCert.getTBSCertificate()));
v.add(new DERInteger(signCert.getSerialNumber())); v.add(new ASN1Integer(signCert.getSerialNumber()));
signerinfo.add(new DERSequence(v)); signerinfo.add(new DERSequence(v));
// Add the digestAlgorithm // Add the digestAlgorithm
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(digestAlgorithm)); v.add(new ASN1ObjectIdentifier(digestAlgorithm));
v.add(new DERNull()); v.add(DERNull.INSTANCE);
signerinfo.add(new DERSequence(v)); signerinfo.add(new DERSequence(v));
// add the authenticated attribute if present // add the authenticated attribute if present
@ -1221,8 +1223,8 @@ public class PdfPKCS7 {
} }
// Add the digestEncryptionAlgorithm // Add the digestEncryptionAlgorithm
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(digestEncryptionAlgorithm)); v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithm));
v.add(new DERNull()); v.add(DERNull.INSTANCE);
signerinfo.add(new DERSequence(v)); signerinfo.add(new DERSequence(v));
// Add the digest // Add the digest
@ -1244,7 +1246,7 @@ public class PdfPKCS7 {
// Finally build the body out of all the components above // Finally build the body out of all the components above
ASN1EncodableVector body = new ASN1EncodableVector(); ASN1EncodableVector body = new ASN1EncodableVector();
body.add(new DERInteger(version)); body.add(new ASN1Integer(version));
body.add(new DERSet(digestAlgorithms)); body.add(new DERSet(digestAlgorithms));
body.add(contentinfo); body.add(contentinfo);
body.add(new DERTaggedObject(false, 0, dercertificates)); body.add(new DERTaggedObject(false, 0, dercertificates));
@ -1266,7 +1268,7 @@ public class PdfPKCS7 {
// and return it // and return it
// //
ASN1EncodableVector whole = new ASN1EncodableVector(); ASN1EncodableVector whole = new ASN1EncodableVector();
whole.add(new DERObjectIdentifier(ID_PKCS7_SIGNED_DATA)); whole.add(new ASN1ObjectIdentifier(ID_PKCS7_SIGNED_DATA));
whole.add(new DERTaggedObject(0, new DERSequence(body))); whole.add(new DERTaggedObject(0, new DERSequence(body)));
ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayOutputStream bOut = new ByteArrayOutputStream();
@ -1276,8 +1278,7 @@ public class PdfPKCS7 {
dout.close(); dout.close();
return bOut.toByteArray(); return bOut.toByteArray();
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
@ -1287,6 +1288,7 @@ public class PdfPKCS7 {
* to start with the timeStampToken (signedData 1.2.840.113549.1.7.2). * to start with the timeStampToken (signedData 1.2.840.113549.1.7.2).
* Token is the TSA response without response status, which is usually * Token is the TSA response without response status, which is usually
* handled by the (vendor supplied) TSA request/response interface). * handled by the (vendor supplied) TSA request/response interface).
*
* @param timeStampToken byte[] - time stamp token, DER encoded signedData * @param timeStampToken byte[] - time stamp token, DER encoded signedData
* @return ASN1EncodableVector * @return ASN1EncodableVector
* @throws IOException * @throws IOException
@ -1302,7 +1304,7 @@ public class PdfPKCS7 {
ASN1EncodableVector unauthAttributes = new ASN1EncodableVector(); ASN1EncodableVector unauthAttributes = new ASN1EncodableVector();
ASN1EncodableVector v = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken v.add(new ASN1ObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken
ASN1Sequence seq = (ASN1Sequence) tempstream.readObject(); ASN1Sequence seq = (ASN1Sequence) tempstream.readObject();
v.add(new DERSet(seq)); v.add(new DERSet(seq));
@ -1334,6 +1336,7 @@ public class PdfPKCS7 {
* pk7.update(sh, 0, sh.length); * pk7.update(sh, 0, sh.length);
* byte sg[] = pk7.getEncodedPKCS7(hash, cal); * byte sg[] = pk7.getEncodedPKCS7(hash, cal);
* </pre> * </pre>
*
* @param secondDigest the content digest * @param secondDigest the content digest
* @param signingTime the signing time * @param signingTime the signing time
* @return the byte array representation of the authenticatedAttributes ready to be signed * @return the byte array representation of the authenticatedAttributes ready to be signed
@ -1341,8 +1344,7 @@ public class PdfPKCS7 {
public byte[] getAuthenticatedAttributeBytes(byte secondDigest[], Calendar signingTime, byte[] ocsp) { public byte[] getAuthenticatedAttributeBytes(byte secondDigest[], Calendar signingTime, byte[] ocsp) {
try { try {
return getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp).getEncoded("DER"); return getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp).getEncoded("DER");
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
@ -1351,36 +1353,35 @@ public class PdfPKCS7 {
try { try {
ASN1EncodableVector attribute = new ASN1EncodableVector(); ASN1EncodableVector attribute = new ASN1EncodableVector();
ASN1EncodableVector v = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_CONTENT_TYPE)); v.add(new ASN1ObjectIdentifier(ID_CONTENT_TYPE));
v.add(new DERSet(new DERObjectIdentifier(ID_PKCS7_DATA))); v.add(new DERSet(new ASN1ObjectIdentifier(ID_PKCS7_DATA)));
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_SIGNING_TIME)); v.add(new ASN1ObjectIdentifier(ID_SIGNING_TIME));
v.add(new DERSet(new DERUTCTime(signingTime.getTime()))); v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_MESSAGE_DIGEST)); v.add(new ASN1ObjectIdentifier(ID_MESSAGE_DIGEST));
v.add(new DERSet(new DEROctetString(secondDigest))); v.add(new DERSet(new DEROctetString(secondDigest)));
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
if (ocsp != null) { if (ocsp != null) {
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION)); v.add(new ASN1ObjectIdentifier(ID_ADBE_REVOCATION));
DEROctetString doctet = new DEROctetString(ocsp); DEROctetString doctet = new DEROctetString(ocsp);
ASN1EncodableVector vo1 = new ASN1EncodableVector(); ASN1EncodableVector vo1 = new ASN1EncodableVector();
ASN1EncodableVector v2 = new ASN1EncodableVector(); ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic); v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
v2.add(doctet); v2.add(doctet);
DEREnumerated den = new DEREnumerated(0); ASN1Enumerated den = new ASN1Enumerated(0);
ASN1EncodableVector v3 = new ASN1EncodableVector(); ASN1EncodableVector v3 = new ASN1EncodableVector();
v3.add(den); v3.add(den);
v3.add(new DERTaggedObject(true, 0, new DERSequence(v2))); v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
vo1.add(new DERSequence(v3)); vo1.add(new DERSequence(v3));
v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 1, new DERSequence(vo1))))); v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 1, new DERSequence(vo1)))));
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
} } else if (!crls.isEmpty()) {
else if (!crls.isEmpty()) {
v = new ASN1EncodableVector(); v = new ASN1EncodableVector();
v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION)); v.add(new ASN1ObjectIdentifier(ID_ADBE_REVOCATION));
ASN1EncodableVector v2 = new ASN1EncodableVector(); ASN1EncodableVector v2 = new ASN1EncodableVector();
for (Iterator i = crls.iterator(); i.hasNext(); ) { for (Iterator i = crls.iterator(); i.hasNext(); ) {
ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(((X509CRL) i.next()).getEncoded())); ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(((X509CRL) i.next()).getEncoded()));
@ -1390,14 +1391,14 @@ public class PdfPKCS7 {
attribute.add(new DERSequence(v)); attribute.add(new DERSequence(v));
} }
return new DERSet(attribute); return new DERSet(attribute);
} } catch (Exception e) {
catch (Exception e) {
throw new ExceptionConverter(e); throw new ExceptionConverter(e);
} }
} }
/** /**
* Getter for property reason. * Getter for property reason.
*
* @return Value of property reason. * @return Value of property reason.
*/ */
public String getReason() { public String getReason() {
@ -1406,6 +1407,7 @@ public class PdfPKCS7 {
/** /**
* Setter for property reason. * Setter for property reason.
*
* @param reason New value of property reason. * @param reason New value of property reason.
*/ */
public void setReason(String reason) { public void setReason(String reason) {
@ -1414,6 +1416,7 @@ public class PdfPKCS7 {
/** /**
* Getter for property location. * Getter for property location.
*
* @return Value of property location. * @return Value of property location.
*/ */
public String getLocation() { public String getLocation() {
@ -1422,6 +1425,7 @@ public class PdfPKCS7 {
/** /**
* Setter for property location. * Setter for property location.
*
* @param location New value of property location. * @param location New value of property location.
*/ */
public void setLocation(String location) { public void setLocation(String location) {
@ -1430,6 +1434,7 @@ public class PdfPKCS7 {
/** /**
* Getter for property signDate. * Getter for property signDate.
*
* @return Value of property signDate. * @return Value of property signDate.
*/ */
public Calendar getSignDate() { public Calendar getSignDate() {
@ -1438,6 +1443,7 @@ public class PdfPKCS7 {
/** /**
* Setter for property signDate. * Setter for property signDate.
*
* @param signDate New value of property signDate. * @param signDate New value of property signDate.
*/ */
public void setSignDate(Calendar signDate) { public void setSignDate(Calendar signDate) {
@ -1446,6 +1452,7 @@ public class PdfPKCS7 {
/** /**
* Getter for property sigName. * Getter for property sigName.
*
* @return Value of property sigName. * @return Value of property sigName.
*/ */
public String getSignName() { public String getSignName() {
@ -1454,6 +1461,7 @@ public class PdfPKCS7 {
/** /**
* Setter for property sigName. * Setter for property sigName.
*
* @param signName New value of property sigName. * @param signName New value of property sigName.
*/ */
public void setSignName(String signName) { public void setSignName(String signName) {
@ -1467,72 +1475,88 @@ public class PdfPKCS7 {
/** /**
* country code - StringType(SIZE(2)) * country code - StringType(SIZE(2))
*/ */
public static final DERObjectIdentifier C = new DERObjectIdentifier("2.5.4.6"); public static final ASN1ObjectIdentifier C = new ASN1ObjectIdentifier("2.5.4.6");
/** /**
* organization - StringType(SIZE(1..64)) * organization - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier O = new DERObjectIdentifier("2.5.4.10"); public static final ASN1ObjectIdentifier O = new ASN1ObjectIdentifier("2.5.4.10");
/** /**
* organizational unit name - StringType(SIZE(1..64)) * organizational unit name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier OU = new DERObjectIdentifier("2.5.4.11"); public static final ASN1ObjectIdentifier OU = new ASN1ObjectIdentifier("2.5.4.11");
/** /**
* Title * Title
*/ */
public static final DERObjectIdentifier T = new DERObjectIdentifier("2.5.4.12"); public static final ASN1ObjectIdentifier T = new ASN1ObjectIdentifier("2.5.4.12");
/** /**
* common name - StringType(SIZE(1..64)) * common name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier CN = new DERObjectIdentifier("2.5.4.3"); public static final ASN1ObjectIdentifier CN = new ASN1ObjectIdentifier("2.5.4.3");
/** /**
* device serial number name - StringType(SIZE(1..64)) * device serial number name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier SN = new DERObjectIdentifier("2.5.4.5"); public static final ASN1ObjectIdentifier SN = new ASN1ObjectIdentifier("2.5.4.5");
/** /**
* locality name - StringType(SIZE(1..64)) * locality name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier L = new DERObjectIdentifier("2.5.4.7"); public static final ASN1ObjectIdentifier L = new ASN1ObjectIdentifier("2.5.4.7");
/** /**
* state, or province name - StringType(SIZE(1..64)) * state, or province name - StringType(SIZE(1..64))
*/ */
public static final DERObjectIdentifier ST = new DERObjectIdentifier("2.5.4.8"); public static final ASN1ObjectIdentifier ST = new ASN1ObjectIdentifier("2.5.4.8");
/** Naming attribute of type X520name */ /**
public static final DERObjectIdentifier SURNAME = new DERObjectIdentifier("2.5.4.4"); * Naming attribute of type X520name
/** Naming attribute of type X520name */ */
public static final DERObjectIdentifier GIVENNAME = new DERObjectIdentifier("2.5.4.42"); public static final ASN1ObjectIdentifier SURNAME = new ASN1ObjectIdentifier("2.5.4.4");
/** Naming attribute of type X520name */ /**
public static final DERObjectIdentifier INITIALS = new DERObjectIdentifier("2.5.4.43"); * Naming attribute of type X520name
/** Naming attribute of type X520name */ */
public static final DERObjectIdentifier GENERATION = new DERObjectIdentifier("2.5.4.44"); public static final ASN1ObjectIdentifier GIVENNAME = new ASN1ObjectIdentifier("2.5.4.42");
/** Naming attribute of type X520name */ /**
public static final DERObjectIdentifier UNIQUE_IDENTIFIER = new DERObjectIdentifier("2.5.4.45"); * Naming attribute of type X520name
*/
public static final ASN1ObjectIdentifier INITIALS = new ASN1ObjectIdentifier("2.5.4.43");
/**
* Naming attribute of type X520name
*/
public static final ASN1ObjectIdentifier GENERATION = new ASN1ObjectIdentifier("2.5.4.44");
/**
* Naming attribute of type X520name
*/
public static final ASN1ObjectIdentifier UNIQUE_IDENTIFIER = new ASN1ObjectIdentifier("2.5.4.45");
/** /**
* Email address (RSA PKCS#9 extension) - IA5String. * Email address (RSA PKCS#9 extension) - IA5String.
* <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here. * <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.
*/ */
public static final DERObjectIdentifier EmailAddress = new DERObjectIdentifier("1.2.840.113549.1.9.1"); public static final ASN1ObjectIdentifier EmailAddress = new ASN1ObjectIdentifier("1.2.840.113549.1.9.1");
/** /**
* email address in Verisign certificates * email address in Verisign certificates
*/ */
public static final DERObjectIdentifier E = EmailAddress; public static final ASN1ObjectIdentifier E = EmailAddress;
/** object identifier */ /**
public static final DERObjectIdentifier DC = new DERObjectIdentifier("0.9.2342.19200300.100.1.25"); * object identifier
*/
public static final ASN1ObjectIdentifier DC = new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.25");
/** LDAP User id. */ /**
public static final DERObjectIdentifier UID = new DERObjectIdentifier("0.9.2342.19200300.100.1.1"); * LDAP User id.
*/
public static final ASN1ObjectIdentifier UID = new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.1");
/** A HashMap with default symbols */ /**
* A HashMap with default symbols
*/
public static HashMap DefaultSymbols = new HashMap(); public static HashMap DefaultSymbols = new HashMap();
static { static {
@ -1552,11 +1576,15 @@ public class PdfPKCS7 {
DefaultSymbols.put(INITIALS, "INITIALS"); DefaultSymbols.put(INITIALS, "INITIALS");
DefaultSymbols.put(GENERATION, "GENERATION"); DefaultSymbols.put(GENERATION, "GENERATION");
} }
/** A HashMap with values */
/**
* A HashMap with values
*/
public HashMap values = new HashMap(); public HashMap values = new HashMap();
/** /**
* Constructs an X509 name * Constructs an X509 name
*
* @param seq an ASN1 Sequence * @param seq an ASN1 Sequence
*/ */
public X509Name(ASN1Sequence seq) { public X509Name(ASN1Sequence seq) {
@ -1579,8 +1607,10 @@ public class PdfPKCS7 {
} }
} }
} }
/** /**
* Constructs an X509 name * Constructs an X509 name
*
* @param dirName a directory name * @param dirName a directory name
*/ */
public X509Name(String dirName) { public X509Name(String dirName) {
@ -1613,6 +1643,7 @@ public class PdfPKCS7 {
/** /**
* gets a field array from the values Hashmap * gets a field array from the values Hashmap
*
* @param name * @param name
* @return an ArrayList * @return an ArrayList
*/ */
@ -1623,6 +1654,7 @@ public class PdfPKCS7 {
/** /**
* getter for values * getter for values
*
* @return a HashMap with the fields of the X509 name * @return a HashMap with the fields of the X509 name
*/ */
public HashMap getFields() { public HashMap getFields() {
@ -1675,24 +1707,19 @@ public class PdfPKCS7 {
if (c == '"') { if (c == '"') {
if (!escaped) { if (!escaped) {
quoted = !quoted; quoted = !quoted;
} } else {
else {
buf.append(c); buf.append(c);
} }
escaped = false; escaped = false;
} } else {
else {
if (escaped || quoted) { if (escaped || quoted) {
buf.append(c); buf.append(c);
escaped = false; escaped = false;
} } else if (c == '\\') {
else if (c == '\\') {
escaped = true; escaped = true;
} } else if (c == ',') {
else if (c == ',') {
break; break;
} } else {
else {
buf.append(c); buf.append(c);
} }
} }

134
fine-itext/src/main/java/com/fr/third/v2/lowagie/text/pdf/PdfPublicKeySecurityHandler.java

@ -49,11 +49,123 @@
/** /**
* The below 2 methods are from pdfbox. * The below 2 methods are from pdfbox.
* * <p>
* private DERObject createDERForRecipient(byte[] in, X509Certificate cert) ; * private DERObject createDERForRecipient(byte[] in, X509Certificate cert) ;
* private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0); * private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0);
* * <p>
* 2006-11-22 Aiken Sam. * 2006-11-22 Aiken Sam.
* <p>
* Copyright (c) 2003-2006, www.pdfbox.org
* All rights reserved.
* <p>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* <p>
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of pdfbox; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
* <p>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* <p>
* http://www.pdfbox.org
* <p>
* Copyright (c) 2003-2006, www.pdfbox.org
* All rights reserved.
* <p>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* <p>
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of pdfbox; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
* <p>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* <p>
* http://www.pdfbox.org
* <p>
* Copyright (c) 2003-2006, www.pdfbox.org
* All rights reserved.
* <p>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* <p>
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of pdfbox; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
* <p>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* <p>
* http://www.pdfbox.org
* <p>
* Copyright (c) 2003-2006, www.pdfbox.org
* All rights reserved.
* <p>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* <p>
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of pdfbox; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
* <p>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* <p>
* http://www.pdfbox.org
*/ */
/** /**
@ -90,7 +202,9 @@
package com.fr.third.v2.lowagie.text.pdf; package com.fr.third.v2.lowagie.text.pdf;
import com.fr.third.org.bouncycastle.asn1.ASN1Object; import com.fr.third.org.bouncycastle.asn1.ASN1Object;
import com.fr.third.org.bouncycastle.asn1.ASN1OutputStream;
import com.fr.third.org.bouncycastle.asn1.ASN1Set; import com.fr.third.org.bouncycastle.asn1.ASN1Set;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@ -110,9 +224,8 @@ import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import com.fr.third.org.bouncycastle.asn1.ASN1InputStream; import com.fr.third.org.bouncycastle.asn1.ASN1InputStream;
import com.fr.third.org.bouncycastle.asn1.DERObjectIdentifier; import com.fr.third.org.bouncycastle.asn1.ASN1ObjectIdentifier;
import com.fr.third.org.bouncycastle.asn1.DEROctetString; import com.fr.third.org.bouncycastle.asn1.DEROctetString;
import com.fr.third.org.bouncycastle.asn1.DEROutputStream;
import com.fr.third.org.bouncycastle.asn1.DERSet; import com.fr.third.org.bouncycastle.asn1.DERSet;
import com.fr.third.org.bouncycastle.asn1.cms.ContentInfo; import com.fr.third.org.bouncycastle.asn1.cms.ContentInfo;
import com.fr.third.org.bouncycastle.asn1.cms.EncryptedContentInfo; import com.fr.third.org.bouncycastle.asn1.cms.EncryptedContentInfo;
@ -161,7 +274,8 @@ public class PdfPublicKeySecurityHandler {
int index = 0; int index = 0;
if (bytes[0] != '(' && bytes[bytes.length-1] != ')') throw new BadPdfFormatException("Expect '(' and ')' at begin and end of the string."); if (bytes[0] != '(' && bytes[bytes.length - 1] != ')')
throw new BadPdfFormatException("Expect '(' and ')' at begin and end of the string.");
while (index < bytes.length) { while (index < bytes.length) {
if (bytes[index] == '\\') { if (bytes[index] == '\\') {
@ -249,7 +363,7 @@ public class PdfPublicKeySecurityHandler {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
DEROutputStream k = new DEROutputStream(baos); ASN1OutputStream k = ASN1OutputStream.create(baos);
k.writeObject(obj); k.writeObject(obj);
@ -279,8 +393,7 @@ public class PdfPublicKeySecurityHandler {
private ASN1Object createDERForRecipient(byte[] in, X509Certificate cert) private ASN1Object createDERForRecipient(byte[] in, X509Certificate cert)
throws IOException, throws IOException,
GeneralSecurityException GeneralSecurityException {
{
String s = "1.2.840.113549.3.2"; String s = "1.2.840.113549.3.2";
@ -298,7 +411,7 @@ public class PdfPublicKeySecurityHandler {
DEROctetString deroctetstring = new DEROctetString(abyte1); DEROctetString deroctetstring = new DEROctetString(abyte1);
KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded()); KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo)); DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
EncryptedContentInfo encryptedcontentinfo = EncryptedContentInfo encryptedcontentinfo =
new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring); new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (ASN1Set) null); EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (ASN1Set) null);
@ -308,8 +421,7 @@ public class PdfPublicKeySecurityHandler {
} }
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
throws GeneralSecurityException, IOException throws GeneralSecurityException, IOException {
{
ASN1InputStream asn1inputstream = ASN1InputStream asn1inputstream =
new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate())); new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure tbscertificatestructure =

Loading…
Cancel
Save