diff options
author | David Hook <dgh@cryptoworkshop.com> | 2013-11-26 09:54:55 +0400 |
---|---|---|
committer | David Hook <dgh@cryptoworkshop.com> | 2013-11-26 09:54:55 +0400 |
commit | eee8e20597c3d4c22908e1fa1cf380e6fbcb75be (patch) | |
tree | 0dcfc7d62952f1b9d26b1eea87410bbcff70e29a /pkix | |
parent | fe8f2e9a80cbd4074270024559fd0792c432d4bc (diff) |
updates
Diffstat (limited to 'pkix')
12 files changed, 70 insertions, 4523 deletions
diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSEnvelopedGenerator.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSEnvelopedGenerator.java deleted file mode 100644 index 0fe9ee9a..00000000 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSEnvelopedGenerator.java +++ /dev/null @@ -1,390 +0,0 @@ -package org.bouncycastle.cms; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import javax.crypto.SecretKey; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.cms.KEKIdentifier; -import org.bouncycastle.asn1.cms.OriginatorInfo; -import org.bouncycastle.asn1.kisa.KISAObjectIdentifiers; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.ntt.NTTObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.cms.jcajce.JceKEKRecipientInfoGenerator; -import org.bouncycastle.cms.jcajce.JceKeyAgreeRecipientInfoGenerator; -import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator; -import org.bouncycastle.cms.jcajce.JcePasswordRecipientInfoGenerator; - -/** - * General class for generating a CMS enveloped-data message. - */ -public class CMSEnvelopedGenerator -{ - public static final String DES_EDE3_CBC = PKCSObjectIdentifiers.des_EDE3_CBC.getId(); - public static final String RC2_CBC = PKCSObjectIdentifiers.RC2_CBC.getId(); - public static final String IDEA_CBC = "1.3.6.1.4.1.188.7.1.1.2"; - public static final String CAST5_CBC = "1.2.840.113533.7.66.10"; - public static final String AES128_CBC = NISTObjectIdentifiers.id_aes128_CBC.getId(); - public static final String AES192_CBC = NISTObjectIdentifiers.id_aes192_CBC.getId(); - public static final String AES256_CBC = NISTObjectIdentifiers.id_aes256_CBC.getId(); - public static final String CAMELLIA128_CBC = NTTObjectIdentifiers.id_camellia128_cbc.getId(); - public static final String CAMELLIA192_CBC = NTTObjectIdentifiers.id_camellia192_cbc.getId(); - public static final String CAMELLIA256_CBC = NTTObjectIdentifiers.id_camellia256_cbc.getId(); - public static final String SEED_CBC = KISAObjectIdentifiers.id_seedCBC.getId(); - - public static final String DES_EDE3_WRAP = PKCSObjectIdentifiers.id_alg_CMS3DESwrap.getId(); - public static final String AES128_WRAP = NISTObjectIdentifiers.id_aes128_wrap.getId(); - public static final String AES192_WRAP = NISTObjectIdentifiers.id_aes192_wrap.getId(); - public static final String AES256_WRAP = NISTObjectIdentifiers.id_aes256_wrap.getId(); - public static final String CAMELLIA128_WRAP = NTTObjectIdentifiers.id_camellia128_wrap.getId(); - public static final String CAMELLIA192_WRAP = NTTObjectIdentifiers.id_camellia192_wrap.getId(); - public static final String CAMELLIA256_WRAP = NTTObjectIdentifiers.id_camellia256_wrap.getId(); - public static final String SEED_WRAP = KISAObjectIdentifiers.id_npki_app_cmsSeed_wrap.getId(); - - public static final String ECDH_SHA1KDF = X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme.getId(); - public static final String ECMQV_SHA1KDF = X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme.getId(); - - List oldRecipientInfoGenerators = new ArrayList(); - List recipientInfoGenerators = new ArrayList(); - - protected CMSAttributeTableGenerator unprotectedAttributeGenerator = null; - - SecureRandom rand; - protected OriginatorInfo originatorInfo; - - /** - * base constructor - */ - public CMSEnvelopedGenerator() - { - this(new SecureRandom()); - } - - /** - * constructor allowing specific source of randomness - * @param rand instance of SecureRandom to use - */ - public CMSEnvelopedGenerator( - SecureRandom rand) - { - this.rand = rand; - } - - public void setUnprotectedAttributeGenerator(CMSAttributeTableGenerator unprotectedAttributeGenerator) - { - this.unprotectedAttributeGenerator = unprotectedAttributeGenerator; - } - - - public void setOriginatorInfo(OriginatorInformation originatorInfo) - { - this.originatorInfo = originatorInfo.toASN1Structure(); - } - - /** - * add a recipient. - * - * @deprecated use the addRecipientGenerator and JceKeyTransRecipientInfoGenerator - * @param cert recipient's public key certificate - * @exception IllegalArgumentException if there is a problem with the certificate - */ - public void addKeyTransRecipient( - X509Certificate cert) - throws IllegalArgumentException - { - try - { - oldRecipientInfoGenerators.add(new JceKeyTransRecipientInfoGenerator(cert)); - } - catch (CertificateEncodingException e) - { - throw new IllegalArgumentException("unable to encode certificate: " + e.getMessage()); - } - } - - /** - * add a recipient - * - * @deprecated use the addRecipientGenerator and JceKeyTransRecipientInfoGenerator - * @param key the public key used by the recipient - * @param subKeyId the identifier for the recipient's public key - * @exception IllegalArgumentException if there is a problem with the key - */ - public void addKeyTransRecipient( - PublicKey key, - byte[] subKeyId) - throws IllegalArgumentException - { - oldRecipientInfoGenerators.add(new JceKeyTransRecipientInfoGenerator(subKeyId, key)); - } - - /** - * add a KEK recipient. - * - * @deprecated use the addRecipientGenerator and JceKEKRecipientInfoGenerator - * @param key the secret key to use for wrapping - * @param keyIdentifier the byte string that identifies the key - */ - public void addKEKRecipient( - SecretKey key, - byte[] keyIdentifier) - { - addKEKRecipient(key, new KEKIdentifier(keyIdentifier, null, null)); - } - - /** - * add a KEK recipient. - * - * @deprecated use the addRecipientGenerator and JceKEKRecipientInfoGenerator - * @param key the secret key to use for wrapping - * @param kekIdentifier a KEKIdentifier structure (identifies the key) - */ - public void addKEKRecipient( - SecretKey key, - KEKIdentifier kekIdentifier) - { - oldRecipientInfoGenerators.add(new JceKEKRecipientInfoGenerator(kekIdentifier, key)); - } - - /** - * @deprecated use addRecipientGenerator and JcePasswordRecipientInfoGenerator - * @param pbeKey PBE key - * @param kekAlgorithmOid key encryption algorithm to use. - */ - public void addPasswordRecipient( - CMSPBEKey pbeKey, - String kekAlgorithmOid) - { - oldRecipientInfoGenerators.add(new JcePasswordRecipientInfoGenerator(new ASN1ObjectIdentifier(kekAlgorithmOid), pbeKey.getPassword()) - .setSaltAndIterationCount(pbeKey.getSalt(), pbeKey.getIterationCount()) - .setPasswordConversionScheme((pbeKey instanceof PKCS5Scheme2UTF8PBEKey) ? PasswordRecipient.PKCS5_SCHEME2_UTF8 : PasswordRecipient.PKCS5_SCHEME2)); - } - - /** - * Add a key agreement based recipient. - * - * @deprecated use the addRecipientGenerator and JceKeyAgreeRecipientInfoGenerator - * @param agreementAlgorithm key agreement algorithm to use. - * @param senderPrivateKey private key to initialise sender side of agreement with. - * @param senderPublicKey sender public key to include with message. - * @param recipientCert recipient's public key certificate. - * @param cekWrapAlgorithm OID for key wrapping algorithm to use. - * @param provider provider to use for the agreement calculation. - * @exception NoSuchProviderException if the specified provider cannot be found - * @exception NoSuchAlgorithmException if the algorithm requested cannot be found - * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified - */ - public void addKeyAgreementRecipient( - String agreementAlgorithm, - PrivateKey senderPrivateKey, - PublicKey senderPublicKey, - X509Certificate recipientCert, - String cekWrapAlgorithm, - String provider) - throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException - { - addKeyAgreementRecipient(agreementAlgorithm, senderPrivateKey, senderPublicKey, recipientCert, cekWrapAlgorithm, CMSUtils.getProvider(provider)); - } - - /** - * Add a key agreement based recipient. - * - * @deprecated use the addRecipientGenerator and JceKeyAgreeRecipientInfoGenerator - * @param agreementAlgorithm key agreement algorithm to use. - * @param senderPrivateKey private key to initialise sender side of agreement with. - * @param senderPublicKey sender public key to include with message. - * @param recipientCert recipient's public key certificate. - * @param cekWrapAlgorithm OID for key wrapping algorithm to use. - * @param provider provider to use for the agreement calculation. - * @exception NoSuchAlgorithmException if the algorithm requested cannot be found - * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified - */ - public void addKeyAgreementRecipient( - String agreementAlgorithm, - PrivateKey senderPrivateKey, - PublicKey senderPublicKey, - X509Certificate recipientCert, - String cekWrapAlgorithm, - Provider provider) - throws NoSuchAlgorithmException, InvalidKeyException - { - List recipients = new ArrayList(); - - recipients.add(recipientCert); - - addKeyAgreementRecipients(agreementAlgorithm, senderPrivateKey, senderPublicKey, - recipients, cekWrapAlgorithm, provider); - } - - /** - * Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure). - * - * @deprecated use the addRecipientGenerator and JceKeyAgreeRecipientInfoGenerator - * @param agreementAlgorithm key agreement algorithm to use. - * @param senderPrivateKey private key to initialise sender side of agreement with. - * @param senderPublicKey sender public key to include with message. - * @param recipientCerts recipients' public key certificates. - * @param cekWrapAlgorithm OID for key wrapping algorithm to use. - * @param provider provider to use for the agreement calculation. - * @exception NoSuchAlgorithmException if the algorithm requested cannot be found - * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified - */ - public void addKeyAgreementRecipients( - String agreementAlgorithm, - PrivateKey senderPrivateKey, - PublicKey senderPublicKey, - Collection recipientCerts, - String cekWrapAlgorithm, - String provider) - throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException - { - addKeyAgreementRecipients(agreementAlgorithm, senderPrivateKey, senderPublicKey, recipientCerts, cekWrapAlgorithm, CMSUtils.getProvider(provider)); - } - - /** - * Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure). - * - * @deprecated use the addRecipientGenerator and JceKeyAgreeRecipientInfoGenerator - * @param agreementAlgorithm key agreement algorithm to use. - * @param senderPrivateKey private key to initialise sender side of agreement with. - * @param senderPublicKey sender public key to include with message. - * @param recipientCerts recipients' public key certificates. - * @param cekWrapAlgorithm OID for key wrapping algorithm to use. - * @param provider provider to use for the agreement calculation. - * @exception NoSuchAlgorithmException if the algorithm requested cannot be found - * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified - */ - public void addKeyAgreementRecipients( - String agreementAlgorithm, - PrivateKey senderPrivateKey, - PublicKey senderPublicKey, - Collection recipientCerts, - String cekWrapAlgorithm, - Provider provider) - throws NoSuchAlgorithmException, InvalidKeyException - { - JceKeyAgreeRecipientInfoGenerator recipientInfoGenerator = new JceKeyAgreeRecipientInfoGenerator(new ASN1ObjectIdentifier(agreementAlgorithm), senderPrivateKey, senderPublicKey, new ASN1ObjectIdentifier(cekWrapAlgorithm)).setProvider(provider); - - for (Iterator it = recipientCerts.iterator(); it.hasNext();) - { - try - { - recipientInfoGenerator.addRecipient((X509Certificate)it.next()); - } - catch (CertificateEncodingException e) - { - throw new IllegalArgumentException("unable to encode certificate: " + e.getMessage()); - } - } - - oldRecipientInfoGenerators.add(recipientInfoGenerator); - } - - /** - * Add a generator to produce the recipient info required. - * - * @param recipientGenerator a generator of a recipient info object. - */ - public void addRecipientInfoGenerator(RecipientInfoGenerator recipientGenerator) - { - recipientInfoGenerators.add(recipientGenerator); - } - - protected AlgorithmIdentifier getAlgorithmIdentifier(String encryptionOID, AlgorithmParameters params) throws IOException - { - ASN1Encodable asn1Params; - if (params != null) - { - asn1Params = ASN1Primitive.fromByteArray(params.getEncoded("ASN.1")); - } - else - { - asn1Params = DERNull.INSTANCE; - } - - return new AlgorithmIdentifier( - new ASN1ObjectIdentifier(encryptionOID), - asn1Params); - } - - protected void convertOldRecipients(SecureRandom rand, Provider provider) - { - for (Iterator it = oldRecipientInfoGenerators.iterator(); it.hasNext();) - { - Object recipient = it.next(); - - if (recipient instanceof JceKeyTransRecipientInfoGenerator) - { - JceKeyTransRecipientInfoGenerator recip = (JceKeyTransRecipientInfoGenerator)recipient; - - if (provider != null) - { - recip.setProvider(provider); - } - - recipientInfoGenerators.add(recip); - } - else if (recipient instanceof KEKRecipientInfoGenerator) - { - JceKEKRecipientInfoGenerator recip = (JceKEKRecipientInfoGenerator)recipient; - - if (provider != null) - { - recip.setProvider(provider); - } - - recip.setSecureRandom(rand); - - recipientInfoGenerators.add(recip); - } - else if (recipient instanceof JcePasswordRecipientInfoGenerator) - { - JcePasswordRecipientInfoGenerator recip = (JcePasswordRecipientInfoGenerator)recipient; - - if (provider != null) - { - recip.setProvider(provider); - } - - recip.setSecureRandom(rand); - - recipientInfoGenerators.add(recip); - } - else if (recipient instanceof JceKeyAgreeRecipientInfoGenerator) - { - JceKeyAgreeRecipientInfoGenerator recip = (JceKeyAgreeRecipientInfoGenerator)recipient; - - if (provider != null) - { - recip.setProvider(provider); - } - - recip.setSecureRandom(rand); - - recipientInfoGenerators.add(recip); - } - } - - oldRecipientInfoGenerators.clear(); - } -} diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSEnvelopedHelper.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSEnvelopedHelper.java deleted file mode 100644 index 54dc6af7..00000000 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSEnvelopedHelper.java +++ /dev/null @@ -1,257 +0,0 @@ -package org.bouncycastle.cms; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.crypto.KeyGenerator; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.cms.KEKRecipientInfo; -import org.bouncycastle.asn1.cms.KeyAgreeRecipientInfo; -import org.bouncycastle.asn1.cms.KeyTransRecipientInfo; -import org.bouncycastle.asn1.cms.PasswordRecipientInfo; -import org.bouncycastle.asn1.cms.RecipientInfo; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.operator.DigestCalculator; -import org.bouncycastle.util.Integers; - -class CMSEnvelopedHelper -{ - static final CMSEnvelopedHelper INSTANCE = new CMSEnvelopedHelper(); - - private static final Map KEYSIZES = new HashMap(); - private static final Map BASE_CIPHER_NAMES = new HashMap(); - private static final Map CIPHER_ALG_NAMES = new HashMap(); - private static final Map MAC_ALG_NAMES = new HashMap(); - - static - { - KEYSIZES.put(CMSEnvelopedGenerator.DES_EDE3_CBC, Integers.valueOf(192)); - KEYSIZES.put(CMSEnvelopedGenerator.AES128_CBC, Integers.valueOf(128)); - KEYSIZES.put(CMSEnvelopedGenerator.AES192_CBC, Integers.valueOf(192)); - KEYSIZES.put(CMSEnvelopedGenerator.AES256_CBC, Integers.valueOf(256)); - - BASE_CIPHER_NAMES.put(CMSEnvelopedGenerator.DES_EDE3_CBC, "DESEDE"); - BASE_CIPHER_NAMES.put(CMSEnvelopedGenerator.AES128_CBC, "AES"); - BASE_CIPHER_NAMES.put(CMSEnvelopedGenerator.AES192_CBC, "AES"); - BASE_CIPHER_NAMES.put(CMSEnvelopedGenerator.AES256_CBC, "AES"); - - CIPHER_ALG_NAMES.put(CMSEnvelopedGenerator.DES_EDE3_CBC, "DESEDE/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSEnvelopedGenerator.AES128_CBC, "AES/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSEnvelopedGenerator.AES192_CBC, "AES/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSEnvelopedGenerator.AES256_CBC, "AES/CBC/PKCS5Padding"); - - MAC_ALG_NAMES.put(CMSEnvelopedGenerator.DES_EDE3_CBC, "DESEDEMac"); - MAC_ALG_NAMES.put(CMSEnvelopedGenerator.AES128_CBC, "AESMac"); - MAC_ALG_NAMES.put(CMSEnvelopedGenerator.AES192_CBC, "AESMac"); - MAC_ALG_NAMES.put(CMSEnvelopedGenerator.AES256_CBC, "AESMac"); - } - - KeyGenerator createSymmetricKeyGenerator( - String encryptionOID, - Provider provider) - throws NoSuchAlgorithmException - { - try - { - return createKeyGenerator(encryptionOID, provider); - } - catch (NoSuchAlgorithmException e) - { - try - { - String algName = (String)BASE_CIPHER_NAMES.get(encryptionOID); - if (algName != null) - { - return createKeyGenerator(algName, provider); - } - } - catch (NoSuchAlgorithmException ex) - { - // ignore - } - if (provider != null) - { - return createSymmetricKeyGenerator(encryptionOID, null); - } - throw e; - } - } - - int getKeySize(String oid) - { - Integer keySize = (Integer)KEYSIZES.get(oid); - - if (keySize == null) - { - throw new IllegalArgumentException("no keysize for " + oid); - } - - return keySize.intValue(); - } - - private KeyGenerator createKeyGenerator( - String algName, - Provider provider) - throws NoSuchAlgorithmException - { - if (provider != null) - { - try - { - return KeyGenerator.getInstance(algName, provider.getName()); - } - catch (NoSuchProviderException e) - { - throw new NoSuchAlgorithmException(e.toString()); - } - } - else - { - return KeyGenerator.getInstance(algName); - } - } - - static RecipientInformationStore buildRecipientInformationStore( - ASN1Set recipientInfos, AlgorithmIdentifier messageAlgorithm, CMSSecureReadable secureReadable) - { - return buildRecipientInformationStore(recipientInfos, messageAlgorithm, secureReadable, null); - } - - static RecipientInformationStore buildRecipientInformationStore( - ASN1Set recipientInfos, AlgorithmIdentifier messageAlgorithm, CMSSecureReadable secureReadable, AuthAttributesProvider additionalData) - { - List infos = new ArrayList(); - for (int i = 0; i != recipientInfos.size(); i++) - { - RecipientInfo info = RecipientInfo.getInstance(recipientInfos.getObjectAt(i)); - - readRecipientInfo(infos, info, messageAlgorithm, secureReadable, additionalData); - } - return new RecipientInformationStore(infos); - } - - private static void readRecipientInfo( - List infos, RecipientInfo info, AlgorithmIdentifier messageAlgorithm, CMSSecureReadable secureReadable, AuthAttributesProvider additionalData) - { - ASN1Encodable recipInfo = info.getInfo(); - if (recipInfo instanceof KeyTransRecipientInfo) - { - infos.add(new KeyTransRecipientInformation( - (KeyTransRecipientInfo)recipInfo, messageAlgorithm, secureReadable, additionalData)); - } - else if (recipInfo instanceof KEKRecipientInfo) - { - infos.add(new KEKRecipientInformation( - (KEKRecipientInfo)recipInfo, messageAlgorithm, secureReadable, additionalData)); - } - else if (recipInfo instanceof KeyAgreeRecipientInfo) - { - KeyAgreeRecipientInformation.readRecipientInfo(infos, - (KeyAgreeRecipientInfo)recipInfo, messageAlgorithm, secureReadable, additionalData); - } - else if (recipInfo instanceof PasswordRecipientInfo) - { - infos.add(new PasswordRecipientInformation( - (PasswordRecipientInfo)recipInfo, messageAlgorithm, secureReadable, additionalData)); - } - } - - static class CMSDigestAuthenticatedSecureReadable - implements CMSSecureReadable - { - private DigestCalculator digestCalculator; - private CMSReadable readable; - - public CMSDigestAuthenticatedSecureReadable(DigestCalculator digestCalculator, CMSReadable readable) - { - this.digestCalculator = digestCalculator; - this.readable = readable; - } - - public InputStream getInputStream() - throws IOException, CMSException - { - return new FilterInputStream(readable.getInputStream()) - { - public int read() - throws IOException - { - int b = in.read(); - - if (b >= 0) - { - digestCalculator.getOutputStream().write(b); - } - - return b; - } - - public int read(byte[] inBuf, int inOff, int inLen) - throws IOException - { - int n = in.read(inBuf, inOff, inLen); - - if (n >= 0) - { - digestCalculator.getOutputStream().write(inBuf, inOff, n); - } - - return n; - } - }; - } - - public byte[] getDigest() - { - return digestCalculator.getDigest(); - } - } - - static class CMSAuthenticatedSecureReadable implements CMSSecureReadable - { - private AlgorithmIdentifier algorithm; - private CMSReadable readable; - - CMSAuthenticatedSecureReadable(AlgorithmIdentifier algorithm, CMSReadable readable) - { - this.algorithm = algorithm; - this.readable = readable; - } - - public InputStream getInputStream() - throws IOException, CMSException - { - return readable.getInputStream(); - } - - } - - static class CMSEnvelopedSecureReadable implements CMSSecureReadable - { - private AlgorithmIdentifier algorithm; - private CMSReadable readable; - - CMSEnvelopedSecureReadable(AlgorithmIdentifier algorithm, CMSReadable readable) - { - this.algorithm = algorithm; - this.readable = readable; - } - - public InputStream getInputStream() - throws IOException, CMSException - { - return readable.getInputStream(); - } - - } -} diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSProcessableByteArray.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSProcessableByteArray.java index 005f6996..8342df21 100644 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSProcessableByteArray.java +++ b/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSProcessableByteArray.java @@ -7,6 +7,7 @@ import java.io.OutputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; +import org.bouncycastle.util.Arrays; /** * a holding class for a byte array of data to be processed. @@ -44,7 +45,7 @@ public class CMSProcessableByteArray public Object getContent() { - return bytes.clone(); + return Arrays.clone(bytes); } public ASN1ObjectIdentifier getContentType() diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedData.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedData.java deleted file mode 100644 index c976dfee..00000000 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedData.java +++ /dev/null @@ -1,772 +0,0 @@ -package org.bouncycastle.cms; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.BERSequence; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.cms.ContentInfo; -import org.bouncycastle.asn1.cms.SignedData; -import org.bouncycastle.asn1.cms.SignerInfo; -import org.bouncycastle.asn1.x509.AttributeCertificate; -import org.bouncycastle.asn1.x509.Certificate; -import org.bouncycastle.asn1.x509.CertificateList; -import org.bouncycastle.cert.X509AttributeCertificateHolder; -import org.bouncycastle.cert.X509CRLHolder; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; -import org.bouncycastle.operator.SignatureAlgorithmIdentifierFinder; -import org.bouncycastle.util.CollectionStore; -import org.bouncycastle.util.Store; -import org.bouncycastle.x509.NoSuchStoreException; -import org.bouncycastle.x509.X509Store; - -/** - * general class for handling a pkcs7-signature message. - * - * A simple example of usage - note, in the example below the validity of - * the certificate isn't verified, just the fact that one of the certs - * matches the given signer... - * - * <pre> - * Store certStore = s.getCertificates(); - * SignerInformationStore signers = s.getSignerInfos(); - * Collection c = signers.getSigners(); - * Iterator it = c.iterator(); - * - * while (it.hasNext()) - * { - * SignerInformation signer = (SignerInformation)it.next(); - * Collection certCollection = certStore.getMatches(signer.getSID()); - * - * Iterator certIt = certCollection.iterator(); - * X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); - * - * if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) - * { - * verified++; - * } - * } - * </pre> - */ -public class CMSSignedData -{ - private static final CMSSignedHelper HELPER = CMSSignedHelper.INSTANCE; - - SignedData signedData; - ContentInfo contentInfo; - CMSTypedData signedContent; - SignerInformationStore signerInfoStore; - X509Store attributeStore; - X509Store certificateStore; - X509Store crlStore; - private Map hashes; - - private CMSSignedData( - CMSSignedData c) - { - this.signedData = c.signedData; - this.contentInfo = c.contentInfo; - this.signedContent = c.signedContent; - this.signerInfoStore = c.signerInfoStore; - } - - public CMSSignedData( - byte[] sigBlock) - throws CMSException - { - this(CMSUtils.readContentInfo(sigBlock)); - } - - public CMSSignedData( - CMSProcessable signedContent, - byte[] sigBlock) - throws CMSException - { - this(signedContent, CMSUtils.readContentInfo(sigBlock)); - } - - /** - * Content with detached signature, digests precomputed - * - * @param hashes a map of precomputed digests for content indexed by name of hash. - * @param sigBlock the signature object. - */ - public CMSSignedData( - Map hashes, - byte[] sigBlock) - throws CMSException - { - this(hashes, CMSUtils.readContentInfo(sigBlock)); - } - - /** - * base constructor - content with detached signature. - * - * @param signedContent the content that was signed. - * @param sigData the signature object. - */ - public CMSSignedData( - CMSProcessable signedContent, - InputStream sigData) - throws CMSException - { - this(signedContent, CMSUtils.readContentInfo(new ASN1InputStream(sigData))); - } - - /** - * base constructor - with encapsulated content - */ - public CMSSignedData( - InputStream sigData) - throws CMSException - { - this(CMSUtils.readContentInfo(sigData)); - } - - public CMSSignedData( - final CMSProcessable signedContent, - ContentInfo sigData) - throws CMSException - { - if (signedContent instanceof CMSTypedData) - { - this.signedContent = (CMSTypedData)signedContent; - } - else - { - this.signedContent = new CMSTypedData() - { - public ASN1ObjectIdentifier getContentType() - { - return signedData.getEncapContentInfo().getContentType(); - } - - public void write(OutputStream out) - throws IOException, CMSException - { - signedContent.write(out); - } - - public Object getContent() - { - return signedContent.getContent(); - } - }; - } - - this.contentInfo = sigData; - this.signedData = getSignedData(); - } - - public CMSSignedData( - Map hashes, - ContentInfo sigData) - throws CMSException - { - this.hashes = hashes; - this.contentInfo = sigData; - this.signedData = getSignedData(); - } - - public CMSSignedData( - ContentInfo sigData) - throws CMSException - { - this.contentInfo = sigData; - this.signedData = getSignedData(); - - // - // this can happen if the signed message is sent simply to send a - // certificate chain. - // - if (signedData.getEncapContentInfo().getContent() != null) - { - this.signedContent = new CMSProcessableByteArray(signedData.getEncapContentInfo().getContentType(), - ((ASN1OctetString)(signedData.getEncapContentInfo() - .getContent())).getOctets()); - } - else - { - this.signedContent = null; - } - } - - private SignedData getSignedData() - throws CMSException - { - try - { - return SignedData.getInstance(contentInfo.getContent()); - } - catch (ClassCastException e) - { - throw new CMSException("Malformed content.", e); - } - catch (IllegalArgumentException e) - { - throw new CMSException("Malformed content.", e); - } - } - - /** - * Return the version number for this object - */ - public int getVersion() - { - return signedData.getVersion().getValue().intValue(); - } - - /** - * return the collection of signers that are associated with the - * signatures for the message. - */ - public SignerInformationStore getSignerInfos() - { - if (signerInfoStore == null) - { - ASN1Set s = signedData.getSignerInfos(); - List signerInfos = new ArrayList(); - SignatureAlgorithmIdentifierFinder sigAlgFinder = new DefaultSignatureAlgorithmIdentifierFinder(); - - for (int i = 0; i != s.size(); i++) - { - SignerInfo info = SignerInfo.getInstance(s.getObjectAt(i)); - ASN1ObjectIdentifier contentType = signedData.getEncapContentInfo().getContentType(); - - if (hashes == null) - { - signerInfos.add(new SignerInformation(info, contentType, signedContent, null)); - } - else - { - Object obj = hashes.keySet().iterator().next(); - byte[] hash = (obj instanceof String) ? (byte[])hashes.get(info.getDigestAlgorithm().getAlgorithm().getId()) : (byte[])hashes.get(info.getDigestAlgorithm().getAlgorithm()); - - signerInfos.add(new SignerInformation(info, contentType, null, hash)); - } - } - - signerInfoStore = new SignerInformationStore(signerInfos); - } - - return signerInfoStore; - } - - /** - * return a X509Store containing the attribute certificates, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider name of provider to use - * @return a store of attribute certificates - * @exception NoSuchProviderException if the provider requested isn't available. - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use base Store returning method - */ - public X509Store getAttributeCertificates( - String type, - String provider) - throws NoSuchStoreException, NoSuchProviderException, CMSException - { - return getAttributeCertificates(type, CMSUtils.getProvider(provider)); - } - - /** - * return a X509Store containing the attribute certificates, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider provider to use - * @return a store of attribute certificates - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use base Store returning method - */ - public X509Store getAttributeCertificates( - String type, - Provider provider) - throws NoSuchStoreException, CMSException - { - if (attributeStore == null) - { - attributeStore = HELPER.createAttributeStore(type, provider, signedData.getCertificates()); - } - - return attributeStore; - } - - /** - * return a X509Store containing the public key certificates, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider name of provider to use - * @return a store of public key certificates - * @exception NoSuchProviderException if the provider requested isn't available. - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use base Store returning method - */ - public X509Store getCertificates( - String type, - String provider) - throws NoSuchStoreException, NoSuchProviderException, CMSException - { - return getCertificates(type, CMSUtils.getProvider(provider)); - } - - /** - * return a X509Store containing the public key certificates, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider provider to use - * @return a store of public key certificates - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use base Store returning method - */ - public X509Store getCertificates( - String type, - Provider provider) - throws NoSuchStoreException, CMSException - { - if (certificateStore == null) - { - certificateStore = HELPER.createCertificateStore(type, provider, signedData.getCertificates()); - } - - return certificateStore; - } - - /** - * return a X509Store containing CRLs, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider name of provider to use - * @return a store of CRLs - * @exception NoSuchProviderException if the provider requested isn't available. - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use base Store returning method - */ - public X509Store getCRLs( - String type, - String provider) - throws NoSuchStoreException, NoSuchProviderException, CMSException - { - return getCRLs(type, CMSUtils.getProvider(provider)); - } - - /** - * return a X509Store containing CRLs, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider provider to use - * @return a store of CRLs - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use base Store returning method - */ - public X509Store getCRLs( - String type, - Provider provider) - throws NoSuchStoreException, CMSException - { - if (crlStore == null) - { - crlStore = HELPER.createCRLsStore(type, provider, signedData.getCRLs()); - } - - return crlStore; - } - - /** - * return a CertStore containing the certificates and CRLs associated with - * this message. - * - * @exception NoSuchProviderException if the provider requested isn't available. - * @exception NoSuchAlgorithmException if the cert store isn't available. - * @exception CMSException if a general exception prevents creation of the CertStore - * @deprecated use base Store returning method - */ - public CertStore getCertificatesAndCRLs( - String type, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, CMSException - { - return getCertificatesAndCRLs(type, CMSUtils.getProvider(provider)); - } - - /** - * return a CertStore containing the certificates and CRLs associated with - * this message. - * - * @exception NoSuchAlgorithmException if the cert store isn't available. - * @exception CMSException if a general exception prevents creation of the CertStore - * @deprecated use base Store returning method - */ - public CertStore getCertificatesAndCRLs( - String type, - Provider provider) - throws NoSuchAlgorithmException, CMSException - { - ASN1Set certSet = signedData.getCertificates(); - ASN1Set crlSet = signedData.getCRLs(); - - return HELPER.createCertStore(type, provider, certSet, crlSet); - } - - public Store getCertificates() - { - ASN1Set certSet = signedData.getCertificates(); - - if (certSet != null) - { - List certList = new ArrayList(certSet.size()); - - for (Enumeration en = certSet.getObjects(); en.hasMoreElements();) - { - ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive(); - - if (obj instanceof ASN1Sequence) - { - certList.add(new X509CertificateHolder(Certificate.getInstance(obj))); - } - } - - return new CollectionStore(certList); - } - - return new CollectionStore(new ArrayList()); - } - - public Store getCRLs() - { - ASN1Set crlSet = signedData.getCRLs(); - - if (crlSet != null) - { - List crlList = new ArrayList(crlSet.size()); - - for (Enumeration en = crlSet.getObjects(); en.hasMoreElements();) - { - ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive(); - - if (obj instanceof ASN1Sequence) - { - crlList.add(new X509CRLHolder(CertificateList.getInstance(obj))); - } - } - - return new CollectionStore(crlList); - } - - return new CollectionStore(new ArrayList()); - } - - public Store getAttributeCertificates() - { - ASN1Set certSet = signedData.getCertificates(); - - if (certSet != null) - { - List certList = new ArrayList(certSet.size()); - - for (Enumeration en = certSet.getObjects(); en.hasMoreElements();) - { - ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive(); - - if (obj instanceof ASN1TaggedObject) - { - certList.add(new X509AttributeCertificateHolder(AttributeCertificate.getInstance(((ASN1TaggedObject)obj).getObject()))); - } - } - - return new CollectionStore(certList); - } - - return new CollectionStore(new ArrayList()); - } - - /** - * Return the a string representation of the OID associated with the - * encapsulated content info structure carried in the signed data. - * - * @return the OID for the content type. - */ - public String getSignedContentTypeOID() - { - return signedData.getEncapContentInfo().getContentType().getId(); - } - - public CMSTypedData getSignedContent() - { - return signedContent; - } - - /** - * return the ContentInfo - * @deprecated use toASN1Structure() - */ - public ContentInfo getContentInfo() - { - return contentInfo; - } - - /** - * return the ContentInfo - */ - public ContentInfo toASN1Structure() - { - return contentInfo; - } - - /** - * return the ASN.1 encoded representation of this object. - */ - public byte[] getEncoded() - throws IOException - { - return contentInfo.getEncoded(); - } - - /** - * Replace the signerinformation store associated with this - * CMSSignedData object with the new one passed in. You would - * probably only want to do this if you wanted to change the unsigned - * attributes associated with a signer, or perhaps delete one. - * - * @param signedData the signed data object to be used as a base. - * @param signerInformationStore the new signer information store to use. - * @return a new signed data object. - */ - public static CMSSignedData replaceSigners( - CMSSignedData signedData, - SignerInformationStore signerInformationStore) - { - // - // copy - // - CMSSignedData cms = new CMSSignedData(signedData); - - // - // replace the store - // - cms.signerInfoStore = signerInformationStore; - - // - // replace the signers in the SignedData object - // - ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); - ASN1EncodableVector vec = new ASN1EncodableVector(); - - Iterator it = signerInformationStore.getSigners().iterator(); - while (it.hasNext()) - { - SignerInformation signer = (SignerInformation)it.next(); - digestAlgs.add(CMSSignedHelper.INSTANCE.fixAlgID(signer.getDigestAlgorithmID())); - vec.add(signer.toASN1Structure()); - } - - ASN1Set digests = new DERSet(digestAlgs); - ASN1Set signers = new DERSet(vec); - ASN1Sequence sD = (ASN1Sequence)signedData.signedData.toASN1Primitive(); - - vec = new ASN1EncodableVector(); - - // - // signers are the last item in the sequence. - // - vec.add(sD.getObjectAt(0)); // version - vec.add(digests); - - for (int i = 2; i != sD.size() - 1; i++) - { - vec.add(sD.getObjectAt(i)); - } - - vec.add(signers); - - cms.signedData = SignedData.getInstance(new BERSequence(vec)); - - // - // replace the contentInfo with the new one - // - cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData); - - return cms; - } - - /** - * Replace the certificate and CRL information associated with this - * CMSSignedData object with the new one passed in. - * - * @param signedData the signed data object to be used as a base. - * @param certsAndCrls the new certificates and CRLs to be used. - * @return a new signed data object. - * @exception CMSException if there is an error processing the CertStore - * @deprecated use method taking Store arguments. - */ - public static CMSSignedData replaceCertificatesAndCRLs( - CMSSignedData signedData, - CertStore certsAndCrls) - throws CMSException - { - // - // copy - // - CMSSignedData cms = new CMSSignedData(signedData); - - // - // replace the certs and crls in the SignedData object - // - ASN1Set certs = null; - ASN1Set crls = null; - - try - { - ASN1Set set = CMSUtils.createBerSetFromList(CMSUtils.getCertificatesFromStore(certsAndCrls)); - - if (set.size() != 0) - { - certs = set; - } - } - catch (CertStoreException e) - { - throw new CMSException("error getting certs from certStore", e); - } - - try - { - ASN1Set set = CMSUtils.createBerSetFromList(CMSUtils.getCRLsFromStore(certsAndCrls)); - - if (set.size() != 0) - { - crls = set; - } - } - catch (CertStoreException e) - { - throw new CMSException("error getting crls from certStore", e); - } - - // - // replace the CMS structure. - // - cms.signedData = new SignedData(signedData.signedData.getDigestAlgorithms(), - signedData.signedData.getEncapContentInfo(), - certs, - crls, - signedData.signedData.getSignerInfos()); - - // - // replace the contentInfo with the new one - // - cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData); - - return cms; - } - - /** - * Replace the certificate and CRL information associated with this - * CMSSignedData object with the new one passed in. - * - * @param signedData the signed data object to be used as a base. - * @param certificates the new certificates to be used. - * @param attrCerts the new attribute certificates to be used. - * @param crls the new CRLs to be used. - * @return a new signed data object. - * @exception CMSException if there is an error processing the CertStore - */ - public static CMSSignedData replaceCertificatesAndCRLs( - CMSSignedData signedData, - Store certificates, - Store attrCerts, - Store crls) - throws CMSException - { - // - // copy - // - CMSSignedData cms = new CMSSignedData(signedData); - - // - // replace the certs and crls in the SignedData object - // - ASN1Set certSet = null; - ASN1Set crlSet = null; - - if (certificates != null || attrCerts != null) - { - List certs = new ArrayList(); - - if (certificates != null) - { - certs.addAll(CMSUtils.getCertificatesFromStore(certificates)); - } - if (attrCerts != null) - { - certs.addAll(CMSUtils.getAttributeCertificatesFromStore(attrCerts)); - } - - ASN1Set set = CMSUtils.createBerSetFromList(certs); - - if (set.size() != 0) - { - certSet = set; - } - } - - if (crls != null) - { - ASN1Set set = CMSUtils.createBerSetFromList(CMSUtils.getCRLsFromStore(crls)); - - if (set.size() != 0) - { - crlSet = set; - } - } - - // - // replace the CMS structure. - // - cms.signedData = new SignedData(signedData.signedData.getDigestAlgorithms(), - signedData.signedData.getEncapContentInfo(), - certSet, - crlSet, - signedData.signedData.getSignerInfos()); - - // - // replace the contentInfo with the new one - // - cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData); - - return cms; - } -} diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedDataParser.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedDataParser.java deleted file mode 100644 index 6452b05a..00000000 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedDataParser.java +++ /dev/null @@ -1,1009 +0,0 @@ -package org.bouncycastle.cms; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1Generator; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1OctetStringParser; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1SequenceParser; -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.ASN1SetParser; -import org.bouncycastle.asn1.ASN1StreamParser; -import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.BERSequenceGenerator; -import org.bouncycastle.asn1.BERSetParser; -import org.bouncycastle.asn1.BERTaggedObject; -import org.bouncycastle.asn1.BERTags; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.DERTaggedObject; -import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; -import org.bouncycastle.asn1.cms.ContentInfoParser; -import org.bouncycastle.asn1.cms.SignedDataParser; -import org.bouncycastle.asn1.cms.SignerInfo; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.AttributeCertificate; -import org.bouncycastle.asn1.x509.CertificateList; -import org.bouncycastle.asn1.x509.Certificate; -import org.bouncycastle.cert.X509AttributeCertificateHolder; -import org.bouncycastle.cert.X509CRLHolder; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.operator.DigestCalculator; -import org.bouncycastle.operator.DigestCalculatorProvider; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.bc.BcDigestCalculatorProvider; -import org.bouncycastle.util.CollectionStore; -import org.bouncycastle.util.Store; -import org.bouncycastle.util.io.Streams; -import org.bouncycastle.x509.NoSuchStoreException; -import org.bouncycastle.x509.X509Store; - -/** - * Parsing class for an CMS Signed Data object from an input stream. - * <p> - * Note: that because we are in a streaming mode only one signer can be tried and it is important - * that the methods on the parser are called in the appropriate order. - * </p> - * <p> - * A simple example of usage for an encapsulated signature. - * </p> - * <p> - * Two notes: first, in the example below the validity of - * the certificate isn't verified, just the fact that one of the certs - * matches the given signer, and, second, because we are in a streaming - * mode the order of the operations is important. - * </p> - * <pre> - * CMSSignedDataParser sp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), encapSigData); - * - * sp.getSignedContent().drain(); - * - * Store certStore = sp.getCertificates(); - * SignerInformationStore signers = sp.getSignerInfos(); - * - * Collection c = signers.getSigners(); - * Iterator it = c.iterator(); - * - * while (it.hasNext()) - * { - * SignerInformation signer = (SignerInformation)it.next(); - * Collection certCollection = certStore.getMatches(signer.getSID()); - * - * Iterator certIt = certCollection.iterator(); - * X509CertificateHolder cert = (X509CertificateHolder)certIt.next(); - * - * System.out.println("verify returns: " + signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))); - * } - * </pre> - * Note also: this class does not introduce buffering - if you are processing large files you should create - * the parser with: - * <pre> - * CMSSignedDataParser ep = new CMSSignedDataParser(new BufferedInputStream(encapSigData, bufSize)); - * </pre> - * where bufSize is a suitably large buffer size. - */ -public class CMSSignedDataParser - extends CMSContentInfoParser -{ - private static final CMSSignedHelper HELPER = CMSSignedHelper.INSTANCE; - - private SignedDataParser _signedData; - private ASN1ObjectIdentifier _signedContentType; - private CMSTypedStream _signedContent; - private Map digests; - - private SignerInformationStore _signerInfoStore; - private X509Store _attributeStore; - private ASN1Set _certSet, _crlSet; - private boolean _isCertCrlParsed; - private X509Store _certificateStore; - private X509Store _crlStore; - - /** - * @deprecated use method taking a DigestCalculatorProvider - */ - public CMSSignedDataParser( - byte[] sigBlock) - throws CMSException - { - this(createDefaultDigestProvider(), new ByteArrayInputStream(sigBlock)); - } - - - public CMSSignedDataParser( - DigestCalculatorProvider digestCalculatorProvider, - byte[] sigBlock) - throws CMSException - { - this(digestCalculatorProvider, new ByteArrayInputStream(sigBlock)); - } - - /** - * @deprecated use method taking digest calculator provider. - * @param signedContent - * @param sigBlock - * @throws CMSException - */ - public CMSSignedDataParser( - CMSTypedStream signedContent, - byte[] sigBlock) - throws CMSException - { - this(createDefaultDigestProvider(), signedContent, new ByteArrayInputStream(sigBlock)); - } - - public CMSSignedDataParser( - DigestCalculatorProvider digestCalculatorProvider, - CMSTypedStream signedContent, - byte[] sigBlock) - throws CMSException - { - this(digestCalculatorProvider, signedContent, new ByteArrayInputStream(sigBlock)); - } - - private static DigestCalculatorProvider createDefaultDigestProvider() - throws CMSException - { - return new BcDigestCalculatorProvider(); - } - - /** - * base constructor - with encapsulated content - * - * @deprecated use method taking a DigestCalculatorProvider - */ - public CMSSignedDataParser( - InputStream sigData) - throws CMSException - { - this(createDefaultDigestProvider(), null, sigData); - } - - /** - * base constructor - with encapsulated content - */ - public CMSSignedDataParser( - DigestCalculatorProvider digestCalculatorProvider, - InputStream sigData) - throws CMSException - { - this(digestCalculatorProvider, null, sigData); - } - - /** - * base constructor - * - * @param signedContent the content that was signed. - * @param sigData the signature object stream. - * * - * @deprecated use method taking a DigestCalculatorProvider - */ - public CMSSignedDataParser( - CMSTypedStream signedContent, - InputStream sigData) - throws CMSException - { - this(createDefaultDigestProvider(), signedContent, sigData); - } - - /** - * base constructor - * - * @param digestCalculatorProvider for generating accumulating digests - * @param signedContent the content that was signed. - * @param sigData the signature object stream. - */ - public CMSSignedDataParser( - DigestCalculatorProvider digestCalculatorProvider, - CMSTypedStream signedContent, - InputStream sigData) - throws CMSException - { - super(sigData); - - try - { - _signedContent = signedContent; - _signedData = SignedDataParser.getInstance(_contentInfo.getContent(BERTags.SEQUENCE)); - digests = new HashMap(); - - ASN1SetParser digAlgs = _signedData.getDigestAlgorithms(); - ASN1Encodable o; - - while ((o = digAlgs.readObject()) != null) - { - AlgorithmIdentifier algId = AlgorithmIdentifier.getInstance(o); - try - { - DigestCalculator calculator = digestCalculatorProvider.get(algId); - - if (calculator != null) - { - this.digests.put(algId.getAlgorithm(), calculator); - } - } - catch (OperatorCreationException e) - { - // ignore - } - } - - // - // If the message is simply a certificate chain message getContent() may return null. - // - ContentInfoParser cont = _signedData.getEncapContentInfo(); - ASN1OctetStringParser octs = (ASN1OctetStringParser) - cont.getContent(BERTags.OCTET_STRING); - - if (octs != null) - { - CMSTypedStream ctStr = new CMSTypedStream( - cont.getContentType().getId(), octs.getOctetStream()); - - if (_signedContent == null) - { - _signedContent = ctStr; - } - else - { - // - // content passed in, need to read past empty encapsulated content info object if present - // - ctStr.drain(); - } - } - - if (signedContent == null) - { - _signedContentType = cont.getContentType(); - } - else - { - _signedContentType = _signedContent.getContentType(); - } - } - catch (IOException e) - { - throw new CMSException("io exception: " + e.getMessage(), e); - } - - if (digests.isEmpty()) - { - throw new CMSException("no digests could be created for message."); - } - } - - /** - * Return the version number for the SignedData object - * - * @return the version number - */ - public int getVersion() - { - return _signedData.getVersion().getValue().intValue(); - } - - /** - * return the collection of signers that are associated with the - * signatures for the message. - * @throws CMSException - */ - public SignerInformationStore getSignerInfos() - throws CMSException - { - if (_signerInfoStore == null) - { - populateCertCrlSets(); - - List signerInfos = new ArrayList(); - Map hashes = new HashMap(); - - Iterator it = digests.keySet().iterator(); - while (it.hasNext()) - { - Object digestKey = it.next(); - - hashes.put(digestKey, ((DigestCalculator)digests.get(digestKey)).getDigest()); - } - - try - { - ASN1SetParser s = _signedData.getSignerInfos(); - ASN1Encodable o; - - while ((o = s.readObject()) != null) - { - SignerInfo info = SignerInfo.getInstance(o.toASN1Primitive()); - - byte[] hash = (byte[])hashes.get(info.getDigestAlgorithm().getAlgorithm()); - - signerInfos.add(new SignerInformation(info, _signedContentType, null, hash)); - } - } - catch (IOException e) - { - throw new CMSException("io exception: " + e.getMessage(), e); - } - - _signerInfoStore = new SignerInformationStore(signerInfos); - } - - return _signerInfoStore; - } - - /** - * return a X509Store containing the attribute certificates, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider name of provider to use - * @return a store of attribute certificates - * @exception NoSuchProviderException if the provider requested isn't available. - * @exception org.bouncycastle.x509.NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - */ - public X509Store getAttributeCertificates( - String type, - String provider) - throws NoSuchStoreException, NoSuchProviderException, CMSException - { - return getAttributeCertificates(type, CMSUtils.getProvider(provider)); - } - - /** - * return a X509Store containing the attribute certificates, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider provider to use - * @return a store of attribute certificates - * @exception org.bouncycastle.x509.NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - */ - public X509Store getAttributeCertificates( - String type, - Provider provider) - throws NoSuchStoreException, CMSException - { - if (_attributeStore == null) - { - populateCertCrlSets(); - - _attributeStore = HELPER.createAttributeStore(type, provider, _certSet); - } - - return _attributeStore; - } - - /** - * return a X509Store containing the public key certificates, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider provider to use - * @return a store of public key certificates - * @exception NoSuchProviderException if the provider requested isn't available. - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use getCertificates() - */ - public X509Store getCertificates( - String type, - String provider) - throws NoSuchStoreException, NoSuchProviderException, CMSException - { - return getCertificates(type, CMSUtils.getProvider(provider)); - } - - /** - * return a X509Store containing the public key certificates, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider provider to use - * @return a store of public key certificates - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use getCertificates() - */ - public X509Store getCertificates( - String type, - Provider provider) - throws NoSuchStoreException, CMSException - { - if (_certificateStore == null) - { - populateCertCrlSets(); - - _certificateStore = HELPER.createCertificateStore(type, provider, _certSet); - } - - return _certificateStore; - } - - /** - * return a X509Store containing CRLs, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider name of provider to use - * @return a store of CRLs - * @exception NoSuchProviderException if the provider requested isn't available. - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use getCRLs() - */ - public X509Store getCRLs( - String type, - String provider) - throws NoSuchStoreException, NoSuchProviderException, CMSException - { - return getCRLs(type, CMSUtils.getProvider(provider)); - } - - /** - * return a X509Store containing CRLs, if any, contained - * in this message. - * - * @param type type of store to create - * @param provider provider to use - * @return a store of CRLs - * @exception NoSuchStoreException if the store type isn't available. - * @exception CMSException if a general exception prevents creation of the X509Store - * @deprecated use getCRLs() - */ - public X509Store getCRLs( - String type, - Provider provider) - throws NoSuchStoreException, CMSException - { - if (_crlStore == null) - { - populateCertCrlSets(); - - _crlStore = HELPER.createCRLsStore(type, provider, _crlSet); - } - - return _crlStore; - } - - /** - * return a CertStore containing the certificates and CRLs associated with - * this message. - * - * @exception NoSuchProviderException if the provider requested isn't available. - * @exception NoSuchAlgorithmException if the cert store isn't available. - * @exception CMSException if a general exception prevents creation of the CertStore - * @deprecated use getCertificates() - */ - public CertStore getCertificatesAndCRLs( - String type, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, CMSException - { - return getCertificatesAndCRLs(type, CMSUtils.getProvider(provider)); - } - - /** - * return a CertStore containing the certificates and CRLs associated with - * this message. - * - * @exception NoSuchProviderException if the provider requested isn't available. - * @exception NoSuchAlgorithmException if the cert store isn't available. - * @exception CMSException if a general exception prevents creation of the CertStore - * @deprecated use getCertificates() - */ - public CertStore getCertificatesAndCRLs( - String type, - Provider provider) - throws NoSuchAlgorithmException, NoSuchProviderException, CMSException - { - populateCertCrlSets(); - - return HELPER.createCertStore(type, provider, _certSet, _crlSet); - } - - public Store getCertificates() - throws CMSException - { - populateCertCrlSets(); - - ASN1Set certSet = _certSet; - - if (certSet != null) - { - List certList = new ArrayList(certSet.size()); - - for (Enumeration en = certSet.getObjects(); en.hasMoreElements();) - { - ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive(); - - if (obj instanceof ASN1Sequence) - { - certList.add(new X509CertificateHolder(Certificate.getInstance(obj))); - } - } - - return new CollectionStore(certList); - } - - return new CollectionStore(new ArrayList()); - } - - public Store getCRLs() - throws CMSException - { - populateCertCrlSets(); - - ASN1Set crlSet = _crlSet; - - if (crlSet != null) - { - List crlList = new ArrayList(crlSet.size()); - - for (Enumeration en = crlSet.getObjects(); en.hasMoreElements();) - { - ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive(); - - if (obj instanceof ASN1Sequence) - { - crlList.add(new X509CRLHolder(CertificateList.getInstance(obj))); - } - } - - return new CollectionStore(crlList); - } - - return new CollectionStore(new ArrayList()); - } - - public Store getAttributeCertificates() - throws CMSException - { - populateCertCrlSets(); - - ASN1Set certSet = _certSet; - - if (certSet != null) - { - List certList = new ArrayList(certSet.size()); - - for (Enumeration en = certSet.getObjects(); en.hasMoreElements();) - { - ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive(); - - if (obj instanceof ASN1TaggedObject) - { - ASN1TaggedObject tagged = (ASN1TaggedObject)obj; - - if (tagged.getTagNo() == 2) - { - certList.add(new X509AttributeCertificateHolder(AttributeCertificate.getInstance(ASN1Sequence.getInstance(tagged, false)))); - } - } - } - - return new CollectionStore(certList); - } - - return new CollectionStore(new ArrayList()); - } - - private void populateCertCrlSets() - throws CMSException - { - if (_isCertCrlParsed) - { - return; - } - - _isCertCrlParsed = true; - - try - { - // care! Streaming - these must be done in exactly this order. - _certSet = getASN1Set(_signedData.getCertificates()); - _crlSet = getASN1Set(_signedData.getCrls()); - } - catch (IOException e) - { - throw new CMSException("problem parsing cert/crl sets", e); - } - } - - /** - * Return the a string representation of the OID associated with the - * encapsulated content info structure carried in the signed data. - * - * @return the OID for the content type. - */ - public String getSignedContentTypeOID() - { - return _signedContentType.getId(); - } - - public CMSTypedStream getSignedContent() - { - if (_signedContent == null) - { - return null; - } - - InputStream digStream = CMSUtils.attachDigestsToInputStream( - digests.values(), _signedContent.getContentStream()); - - return new CMSTypedStream(_signedContent.getContentType(), digStream); - } - - /** - * Replace the signerinformation store associated with the passed - * in message contained in the stream original with the new one passed in. - * You would probably only want to do this if you wanted to change the unsigned - * attributes associated with a signer, or perhaps delete one. - * <p> - * The output stream is returned unclosed. - * </p> - * @param original the signed data stream to be used as a base. - * @param signerInformationStore the new signer information store to use. - * @param out the stream to write the new signed data object to. - * @return out. - */ - public static OutputStream replaceSigners( - InputStream original, - SignerInformationStore signerInformationStore, - OutputStream out) - throws CMSException, IOException - { - ASN1StreamParser in = new ASN1StreamParser(original); - ContentInfoParser contentInfo = new ContentInfoParser((ASN1SequenceParser)in.readObject()); - SignedDataParser signedData = SignedDataParser.getInstance(contentInfo.getContent(BERTags.SEQUENCE)); - - BERSequenceGenerator sGen = new BERSequenceGenerator(out); - - sGen.addObject(CMSObjectIdentifiers.signedData); - - BERSequenceGenerator sigGen = new BERSequenceGenerator(sGen.getRawOutputStream(), 0, true); - - // version number - sigGen.addObject(signedData.getVersion()); - - // digests - signedData.getDigestAlgorithms().toASN1Primitive(); // skip old ones - - ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); - - for (Iterator it = signerInformationStore.getSigners().iterator(); it.hasNext();) - { - SignerInformation signer = (SignerInformation)it.next(); - digestAlgs.add(CMSSignedHelper.INSTANCE.fixAlgID(signer.getDigestAlgorithmID())); - } - - sigGen.getRawOutputStream().write(new DERSet(digestAlgs).getEncoded()); - - // encap content info - ContentInfoParser encapContentInfo = signedData.getEncapContentInfo(); - - BERSequenceGenerator eiGen = new BERSequenceGenerator(sigGen.getRawOutputStream()); - - eiGen.addObject(encapContentInfo.getContentType()); - - pipeEncapsulatedOctetString(encapContentInfo, eiGen.getRawOutputStream()); - - eiGen.close(); - - - writeSetToGeneratorTagged(sigGen, signedData.getCertificates(), 0); - writeSetToGeneratorTagged(sigGen, signedData.getCrls(), 1); - - - ASN1EncodableVector signerInfos = new ASN1EncodableVector(); - for (Iterator it = signerInformationStore.getSigners().iterator(); it.hasNext();) - { - SignerInformation signer = (SignerInformation)it.next(); - - signerInfos.add(signer.toASN1Structure()); - } - - sigGen.getRawOutputStream().write(new DERSet(signerInfos).getEncoded()); - - sigGen.close(); - - sGen.close(); - - return out; - } - - /** - * Replace the certificate and CRL information associated with this - * CMSSignedData object with the new one passed in. - * <p> - * The output stream is returned unclosed. - * </p> - * @param original the signed data stream to be used as a base. - * @param certsAndCrls the new certificates and CRLs to be used. - * @param out the stream to write the new signed data object to. - * @return out. - * @exception CMSException if there is an error processing the CertStore - * @deprecated use method that takes Store objects. - */ - public static OutputStream replaceCertificatesAndCRLs( - InputStream original, - CertStore certsAndCrls, - OutputStream out) - throws CMSException, IOException - { - ASN1StreamParser in = new ASN1StreamParser(original); - ContentInfoParser contentInfo = new ContentInfoParser((ASN1SequenceParser)in.readObject()); - SignedDataParser signedData = SignedDataParser.getInstance(contentInfo.getContent(BERTags.SEQUENCE)); - - BERSequenceGenerator sGen = new BERSequenceGenerator(out); - - sGen.addObject(CMSObjectIdentifiers.signedData); - - BERSequenceGenerator sigGen = new BERSequenceGenerator(sGen.getRawOutputStream(), 0, true); - - // version number - sigGen.addObject(signedData.getVersion()); - - // digests - sigGen.getRawOutputStream().write(signedData.getDigestAlgorithms().toASN1Primitive().getEncoded()); - - // encap content info - ContentInfoParser encapContentInfo = signedData.getEncapContentInfo(); - - BERSequenceGenerator eiGen = new BERSequenceGenerator(sigGen.getRawOutputStream()); - - eiGen.addObject(encapContentInfo.getContentType()); - - pipeEncapsulatedOctetString(encapContentInfo, eiGen.getRawOutputStream()); - - eiGen.close(); - - // - // skip existing certs and CRLs - // - getASN1Set(signedData.getCertificates()); - getASN1Set(signedData.getCrls()); - - // - // replace the certs and crls in the SignedData object - // - ASN1Set certs; - - try - { - certs = CMSUtils.createBerSetFromList(CMSUtils.getCertificatesFromStore(certsAndCrls)); - } - catch (CertStoreException e) - { - throw new CMSException("error getting certs from certStore", e); - } - - if (certs.size() > 0) - { - sigGen.getRawOutputStream().write(new DERTaggedObject(false, 0, certs).getEncoded()); - } - - ASN1Set crls; - - try - { - crls = CMSUtils.createBerSetFromList(CMSUtils.getCRLsFromStore(certsAndCrls)); - } - catch (CertStoreException e) - { - throw new CMSException("error getting crls from certStore", e); - } - - if (crls.size() > 0) - { - sigGen.getRawOutputStream().write(new DERTaggedObject(false, 1, crls).getEncoded()); - } - - sigGen.getRawOutputStream().write(signedData.getSignerInfos().toASN1Primitive().getEncoded()); - - sigGen.close(); - - sGen.close(); - - return out; - } - - /** - * Replace the certificate and CRL information associated with this - * CMSSignedData object with the new one passed in. - * <p> - * The output stream is returned unclosed. - * </p> - * @param original the signed data stream to be used as a base. - * @param certs new certificates to be used, if any. - * @param crls new CRLs to be used, if any. - * @param attrCerts new attribute certificates to be used, if any. - * @param out the stream to write the new signed data object to. - * @return out. - * @exception CMSException if there is an error processing the CertStore - */ - public static OutputStream replaceCertificatesAndCRLs( - InputStream original, - Store certs, - Store crls, - Store attrCerts, - OutputStream out) - throws CMSException, IOException - { - ASN1StreamParser in = new ASN1StreamParser(original); - ContentInfoParser contentInfo = new ContentInfoParser((ASN1SequenceParser)in.readObject()); - SignedDataParser signedData = SignedDataParser.getInstance(contentInfo.getContent(BERTags.SEQUENCE)); - - BERSequenceGenerator sGen = new BERSequenceGenerator(out); - - sGen.addObject(CMSObjectIdentifiers.signedData); - - BERSequenceGenerator sigGen = new BERSequenceGenerator(sGen.getRawOutputStream(), 0, true); - - // version number - sigGen.addObject(signedData.getVersion()); - - // digests - sigGen.getRawOutputStream().write(signedData.getDigestAlgorithms().toASN1Primitive().getEncoded()); - - // encap content info - ContentInfoParser encapContentInfo = signedData.getEncapContentInfo(); - - BERSequenceGenerator eiGen = new BERSequenceGenerator(sigGen.getRawOutputStream()); - - eiGen.addObject(encapContentInfo.getContentType()); - - pipeEncapsulatedOctetString(encapContentInfo, eiGen.getRawOutputStream()); - - eiGen.close(); - - // - // skip existing certs and CRLs - // - getASN1Set(signedData.getCertificates()); - getASN1Set(signedData.getCrls()); - - // - // replace the certs and crls in the SignedData object - // - if (certs != null || attrCerts != null) - { - List certificates = new ArrayList(); - - if (certs != null) - { - certificates.addAll(CMSUtils.getCertificatesFromStore(certs)); - } - if (attrCerts != null) - { - certificates.addAll(CMSUtils.getAttributeCertificatesFromStore(attrCerts)); - } - - ASN1Set asn1Certs = CMSUtils.createBerSetFromList(certificates); - - if (asn1Certs.size() > 0) - { - sigGen.getRawOutputStream().write(new DERTaggedObject(false, 0, asn1Certs).getEncoded()); - } - } - - if (crls != null) - { - ASN1Set asn1Crls = CMSUtils.createBerSetFromList(CMSUtils.getCRLsFromStore(crls)); - - if (asn1Crls.size() > 0) - { - sigGen.getRawOutputStream().write(new DERTaggedObject(false, 1, asn1Crls).getEncoded()); - } - } - - sigGen.getRawOutputStream().write(signedData.getSignerInfos().toASN1Primitive().getEncoded()); - - sigGen.close(); - - sGen.close(); - - return out; - } - - private static void writeSetToGeneratorTagged( - ASN1Generator asn1Gen, - ASN1SetParser asn1SetParser, - int tagNo) - throws IOException - { - ASN1Set asn1Set = getASN1Set(asn1SetParser); - - if (asn1Set != null) - { - if (asn1SetParser instanceof BERSetParser) - { - asn1Gen.getRawOutputStream().write(new BERTaggedObject(false, tagNo, asn1Set).getEncoded()); - } - else - { - asn1Gen.getRawOutputStream().write(new DERTaggedObject(false, tagNo, asn1Set).getEncoded()); - } - } - } - - private static ASN1Set getASN1Set( - ASN1SetParser asn1SetParser) - { - return asn1SetParser == null - ? null - : ASN1Set.getInstance(asn1SetParser.toASN1Primitive()); - } - - private static void pipeEncapsulatedOctetString(ContentInfoParser encapContentInfo, - OutputStream rawOutputStream) throws IOException - { - ASN1OctetStringParser octs = (ASN1OctetStringParser) - encapContentInfo.getContent(BERTags.OCTET_STRING); - - if (octs != null) - { - pipeOctetString(octs, rawOutputStream); - } - -// BERTaggedObjectParser contentObject = (BERTaggedObjectParser)encapContentInfo.getContentObject(); -// if (contentObject != null) -// { -// // Handle IndefiniteLengthInputStream safely -// InputStream input = ASN1StreamParser.getSafeRawInputStream(contentObject.getContentStream(true)); -// -// // TODO BerTaggedObjectGenerator? -// BEROutputStream berOut = new BEROutputStream(rawOutputStream); -// berOut.write(DERTags.CONSTRUCTED | DERTags.TAGGED | 0); -// berOut.write(0x80); -// -// pipeRawOctetString(input, rawOutputStream); -// -// berOut.write(0x00); -// berOut.write(0x00); -// -// input.close(); -// } - } - - private static void pipeOctetString( - ASN1OctetStringParser octs, - OutputStream output) - throws IOException - { - // TODO Allow specification of a specific fragment size? - OutputStream outOctets = CMSUtils.createBEROctetOutputStream( - output, 0, true, 0); - Streams.pipeAll(octs.getOctetStream(), outOctets); - outOctets.close(); - } - -// private static void pipeRawOctetString( -// InputStream rawInput, -// OutputStream rawOutput) -// throws IOException -// { -// InputStream tee = new TeeInputStream(rawInput, rawOutput); -// ASN1StreamParser sp = new ASN1StreamParser(tee); -// ASN1OctetStringParser octs = (ASN1OctetStringParser)sp.readObject(); -// Streams.drain(octs.getOctetStream()); -// } -} diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedGenerator.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedGenerator.java deleted file mode 100644 index 4ef4f007..00000000 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedGenerator.java +++ /dev/null @@ -1,281 +0,0 @@ -package org.bouncycastle.cms; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.interfaces.DSAPrivateKey; -import java.security.interfaces.RSAPrivateKey; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DERObjectIdentifier; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.DERTaggedObject; -import org.bouncycastle.asn1.cms.AttributeTable; -import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; -import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.AttributeCertificate; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.jce.interfaces.GOST3410PrivateKey; -import org.bouncycastle.util.Store; -import org.bouncycastle.x509.X509AttributeCertificate; -import org.bouncycastle.x509.X509Store; - -public class CMSSignedGenerator -{ - /** - * Default type for the signed data. - */ - public static final String DATA = CMSObjectIdentifiers.data.getId(); - - public static final String DIGEST_SHA1 = OIWObjectIdentifiers.idSHA1.getId(); - public static final String DIGEST_SHA224 = NISTObjectIdentifiers.id_sha224.getId(); - public static final String DIGEST_SHA256 = NISTObjectIdentifiers.id_sha256.getId(); - public static final String DIGEST_SHA384 = NISTObjectIdentifiers.id_sha384.getId(); - public static final String DIGEST_SHA512 = NISTObjectIdentifiers.id_sha512.getId(); - public static final String DIGEST_MD5 = PKCSObjectIdentifiers.md5.getId(); - public static final String DIGEST_GOST3411 = CryptoProObjectIdentifiers.gostR3411.getId(); - public static final String DIGEST_RIPEMD128 = TeleTrusTObjectIdentifiers.ripemd128.getId(); - public static final String DIGEST_RIPEMD160 = TeleTrusTObjectIdentifiers.ripemd160.getId(); - public static final String DIGEST_RIPEMD256 = TeleTrusTObjectIdentifiers.ripemd256.getId(); - - public static final String ENCRYPTION_RSA = PKCSObjectIdentifiers.rsaEncryption.getId(); - public static final String ENCRYPTION_DSA = X9ObjectIdentifiers.id_dsa_with_sha1.getId(); - public static final String ENCRYPTION_ECDSA = X9ObjectIdentifiers.ecdsa_with_SHA1.getId(); - public static final String ENCRYPTION_RSA_PSS = PKCSObjectIdentifiers.id_RSASSA_PSS.getId(); - public static final String ENCRYPTION_GOST3410 = CryptoProObjectIdentifiers.gostR3410_94.getId(); - public static final String ENCRYPTION_ECGOST3410 = CryptoProObjectIdentifiers.gostR3410_2001.getId(); - - private static final String ENCRYPTION_ECDSA_WITH_SHA1 = X9ObjectIdentifiers.ecdsa_with_SHA1.getId(); - private static final String ENCRYPTION_ECDSA_WITH_SHA224 = X9ObjectIdentifiers.ecdsa_with_SHA224.getId(); - private static final String ENCRYPTION_ECDSA_WITH_SHA256 = X9ObjectIdentifiers.ecdsa_with_SHA256.getId(); - private static final String ENCRYPTION_ECDSA_WITH_SHA384 = X9ObjectIdentifiers.ecdsa_with_SHA384.getId(); - private static final String ENCRYPTION_ECDSA_WITH_SHA512 = X9ObjectIdentifiers.ecdsa_with_SHA512.getId(); - - private static final Set NO_PARAMS = new HashSet(); - private static final Map EC_ALGORITHMS = new HashMap(); - - static - { - NO_PARAMS.add(ENCRYPTION_DSA); - NO_PARAMS.add(ENCRYPTION_ECDSA); - NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA1); - NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA224); - NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA256); - NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA384); - NO_PARAMS.add(ENCRYPTION_ECDSA_WITH_SHA512); - - EC_ALGORITHMS.put(DIGEST_SHA1, ENCRYPTION_ECDSA_WITH_SHA1); - EC_ALGORITHMS.put(DIGEST_SHA224, ENCRYPTION_ECDSA_WITH_SHA224); - EC_ALGORITHMS.put(DIGEST_SHA256, ENCRYPTION_ECDSA_WITH_SHA256); - EC_ALGORITHMS.put(DIGEST_SHA384, ENCRYPTION_ECDSA_WITH_SHA384); - EC_ALGORITHMS.put(DIGEST_SHA512, ENCRYPTION_ECDSA_WITH_SHA512); - } - - protected List certs = new ArrayList(); - protected List crls = new ArrayList(); - protected List _signers = new ArrayList(); - protected List signerGens = new ArrayList(); - protected Map digests = new HashMap(); - - protected SecureRandom rand; - - /** - * base constructor - */ - protected CMSSignedGenerator() - { - this(new SecureRandom()); - } - - /** - * constructor allowing specific source of randomness - * @param rand instance of SecureRandom to use - */ - protected CMSSignedGenerator( - SecureRandom rand) - { - this.rand = rand; - } - - protected String getEncOID( - PrivateKey key, - String digestOID) - { - String encOID = null; - - if (key instanceof RSAPrivateKey || "RSA".equalsIgnoreCase(key.getAlgorithm())) - { - encOID = ENCRYPTION_RSA; - } - else if (key instanceof DSAPrivateKey || "DSA".equalsIgnoreCase(key.getAlgorithm())) - { - encOID = ENCRYPTION_DSA; - if (!digestOID.equals(DIGEST_SHA1)) - { - throw new IllegalArgumentException("can't mix DSA with anything but SHA1"); - } - } - else if ("ECDSA".equalsIgnoreCase(key.getAlgorithm()) || "EC".equalsIgnoreCase(key.getAlgorithm())) - { - encOID = (String)EC_ALGORITHMS.get(digestOID); - if (encOID == null) - { - throw new IllegalArgumentException("can't mix ECDSA with anything but SHA family digests"); - } - } - else if (key instanceof GOST3410PrivateKey || "GOST3410".equalsIgnoreCase(key.getAlgorithm())) - { - encOID = ENCRYPTION_GOST3410; - } - else if ("ECGOST3410".equalsIgnoreCase(key.getAlgorithm())) - { - encOID = ENCRYPTION_ECGOST3410; - } - - return encOID; - } - - protected Map getBaseParameters(DERObjectIdentifier contentType, AlgorithmIdentifier digAlgId, byte[] hash) - { - Map param = new HashMap(); - param.put(CMSAttributeTableGenerator.CONTENT_TYPE, contentType); - param.put(CMSAttributeTableGenerator.DIGEST_ALGORITHM_IDENTIFIER, digAlgId); - param.put(CMSAttributeTableGenerator.DIGEST, hash.clone()); - return param; - } - - protected ASN1Set getAttributeSet( - AttributeTable attr) - { - if (attr != null) - { - return new DERSet(attr.toASN1EncodableVector()); - } - - return null; - } - - /** - * add the certificates and CRLs contained in the given CertStore - * to the pool that will be included in the encoded signature block. - * <p> - * Note: this assumes the CertStore will support null in the get - * methods. - * @param certStore CertStore containing the public key certificates and CRLs - * @throws org.bouncycastle.jce.cert.CertStoreException if an issue occurs processing the CertStore - * @throws CMSException if an issue occurse transforming data from the CertStore into the message - * @deprecated use addCertificates and addCRLs - */ - public void addCertificatesAndCRLs( - CertStore certStore) - throws CertStoreException, CMSException - { - certs.addAll(CMSUtils.getCertificatesFromStore(certStore)); - crls.addAll(CMSUtils.getCRLsFromStore(certStore)); - } - - public void addCertificates( - Store certStore) - throws CMSException - { - certs.addAll(CMSUtils.getCertificatesFromStore(certStore)); - } - - public void addCRLs( - Store crlStore) - throws CMSException - { - crls.addAll(CMSUtils.getCRLsFromStore(crlStore)); - } - - public void addAttributeCertificates( - Store attrStore) - throws CMSException - { - certs.addAll(CMSUtils.getAttributeCertificatesFromStore(attrStore)); - } - - /** - * Add the attribute certificates contained in the passed in store to the - * generator. - * - * @param store a store of Version 2 attribute certificates - * @throws CMSException if an error occurse processing the store. - * @deprecated use basic Store method - */ - public void addAttributeCertificates( - X509Store store) - throws CMSException - { - try - { - for (Iterator it = store.getMatches(null).iterator(); it.hasNext();) - { - X509AttributeCertificate attrCert = (X509AttributeCertificate)it.next(); - - certs.add(new DERTaggedObject(false, 2, - AttributeCertificate.getInstance(ASN1Primitive.fromByteArray(attrCert.getEncoded())))); - } - } - catch (IllegalArgumentException e) - { - throw new CMSException("error processing attribute certs", e); - } - catch (IOException e) - { - throw new CMSException("error processing attribute certs", e); - } - } - - - /** - * Add a store of precalculated signers to the generator. - * - * @param signerStore store of signers - */ - public void addSigners( - SignerInformationStore signerStore) - { - Iterator it = signerStore.getSigners().iterator(); - - while (it.hasNext()) - { - _signers.add(it.next()); - } - } - - public void addSignerInfoGenerator(SignerInfoGenerator infoGen) - { - signerGens.add(infoGen); - } - - /** - * Return a map of oids and byte arrays representing the digests calculated on the content during - * the last generate. - * - * @return a map of oids (as String objects) and byte[] representing digests. - */ - public Map getGeneratedDigests() - { - return new HashMap(digests); - } -} diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedHelper.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedHelper.java deleted file mode 100644 index 80822f47..00000000 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSSignedHelper.java +++ /dev/null @@ -1,414 +0,0 @@ -package org.bouncycastle.cms; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.cert.CRLException; -import java.security.cert.CertStore; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.CollectionCertStoreParameters; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Sequence; -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.ASN1TaggedObject; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DERObjectIdentifier; -import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.bouncycastle.asn1.eac.EACObjectIdentifiers; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; -import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; -import org.bouncycastle.x509.NoSuchStoreException; -import org.bouncycastle.x509.X509CollectionStoreParameters; -import org.bouncycastle.x509.X509Store; -import org.bouncycastle.x509.X509V2AttributeCertificate; - -class CMSSignedHelper -{ - static final CMSSignedHelper INSTANCE = new CMSSignedHelper(); - - private static final Map encryptionAlgs = new HashMap(); - private static final Map digestAlgs = new HashMap(); - private static final Map digestAliases = new HashMap(); - - private static void addEntries(DERObjectIdentifier alias, String digest, String encryption) - { - digestAlgs.put(alias.getId(), digest); - encryptionAlgs.put(alias.getId(), encryption); - } - - static - { - addEntries(NISTObjectIdentifiers.dsa_with_sha224, "SHA224", "DSA"); - addEntries(NISTObjectIdentifiers.dsa_with_sha256, "SHA256", "DSA"); - addEntries(NISTObjectIdentifiers.dsa_with_sha384, "SHA384", "DSA"); - addEntries(NISTObjectIdentifiers.dsa_with_sha512, "SHA512", "DSA"); - addEntries(OIWObjectIdentifiers.dsaWithSHA1, "SHA1", "DSA"); - addEntries(OIWObjectIdentifiers.md4WithRSA, "MD4", "RSA"); - addEntries(OIWObjectIdentifiers.md4WithRSAEncryption, "MD4", "RSA"); - addEntries(OIWObjectIdentifiers.md5WithRSA, "MD5", "RSA"); - addEntries(OIWObjectIdentifiers.sha1WithRSA, "SHA1", "RSA"); - addEntries(PKCSObjectIdentifiers.md2WithRSAEncryption, "MD2", "RSA"); - addEntries(PKCSObjectIdentifiers.md4WithRSAEncryption, "MD4", "RSA"); - addEntries(PKCSObjectIdentifiers.md5WithRSAEncryption, "MD5", "RSA"); - addEntries(PKCSObjectIdentifiers.sha1WithRSAEncryption, "SHA1", "RSA"); - addEntries(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224", "RSA"); - addEntries(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256", "RSA"); - addEntries(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384", "RSA"); - addEntries(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512", "RSA"); - addEntries(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1", "ECDSA"); - addEntries(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224", "ECDSA"); - addEntries(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256", "ECDSA"); - addEntries(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384", "ECDSA"); - addEntries(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512", "ECDSA"); - addEntries(X9ObjectIdentifiers.id_dsa_with_sha1, "SHA1", "DSA"); - addEntries(EACObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1", "ECDSA"); - addEntries(EACObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224", "ECDSA"); - addEntries(EACObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256", "ECDSA"); - addEntries(EACObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384", "ECDSA"); - addEntries(EACObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512", "ECDSA"); - addEntries(EACObjectIdentifiers.id_TA_RSA_v1_5_SHA_1, "SHA1", "RSA"); - addEntries(EACObjectIdentifiers.id_TA_RSA_v1_5_SHA_256, "SHA256", "RSA"); - addEntries(EACObjectIdentifiers.id_TA_RSA_PSS_SHA_1, "SHA1", "RSAandMGF1"); - addEntries(EACObjectIdentifiers.id_TA_RSA_PSS_SHA_256, "SHA256", "RSAandMGF1"); - - encryptionAlgs.put(X9ObjectIdentifiers.id_dsa.getId(), "DSA"); - encryptionAlgs.put(PKCSObjectIdentifiers.rsaEncryption.getId(), "RSA"); - encryptionAlgs.put(TeleTrusTObjectIdentifiers.teleTrusTRSAsignatureAlgorithm, "RSA"); - encryptionAlgs.put(X509ObjectIdentifiers.id_ea_rsa.getId(), "RSA"); - encryptionAlgs.put(CMSSignedDataGenerator.ENCRYPTION_RSA_PSS, "RSAandMGF1"); - encryptionAlgs.put(CryptoProObjectIdentifiers.gostR3410_94.getId(), "GOST3410"); - encryptionAlgs.put(CryptoProObjectIdentifiers.gostR3410_2001.getId(), "ECGOST3410"); - encryptionAlgs.put("1.3.6.1.4.1.5849.1.6.2", "ECGOST3410"); - encryptionAlgs.put("1.3.6.1.4.1.5849.1.1.5", "GOST3410"); - encryptionAlgs.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId(), "ECGOST3410"); - encryptionAlgs.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94.getId(), "GOST3410"); - - digestAlgs.put(PKCSObjectIdentifiers.md2.getId(), "MD2"); - digestAlgs.put(PKCSObjectIdentifiers.md4.getId(), "MD4"); - digestAlgs.put(PKCSObjectIdentifiers.md5.getId(), "MD5"); - digestAlgs.put(OIWObjectIdentifiers.idSHA1.getId(), "SHA1"); - digestAlgs.put(NISTObjectIdentifiers.id_sha224.getId(), "SHA224"); - digestAlgs.put(NISTObjectIdentifiers.id_sha256.getId(), "SHA256"); - digestAlgs.put(NISTObjectIdentifiers.id_sha384.getId(), "SHA384"); - digestAlgs.put(NISTObjectIdentifiers.id_sha512.getId(), "SHA512"); - digestAlgs.put(TeleTrusTObjectIdentifiers.ripemd128.getId(), "RIPEMD128"); - digestAlgs.put(TeleTrusTObjectIdentifiers.ripemd160.getId(), "RIPEMD160"); - digestAlgs.put(TeleTrusTObjectIdentifiers.ripemd256.getId(), "RIPEMD256"); - digestAlgs.put(CryptoProObjectIdentifiers.gostR3411.getId(), "GOST3411"); - digestAlgs.put("1.3.6.1.4.1.5849.1.2.1", "GOST3411"); - - digestAliases.put("SHA1", new String[] { "SHA-1" }); - digestAliases.put("SHA224", new String[] { "SHA-224" }); - digestAliases.put("SHA256", new String[] { "SHA-256" }); - digestAliases.put("SHA384", new String[] { "SHA-384" }); - digestAliases.put("SHA512", new String[] { "SHA-512" }); - } - - /** - * Return the digest algorithm using one of the standard JCA string - * representations rather than the algorithm identifier (if possible). - */ - String getDigestAlgName( - String digestAlgOID) - { - String algName = (String)digestAlgs.get(digestAlgOID); - - if (algName != null) - { - return algName; - } - - return digestAlgOID; - } - - /** - * Return the digest encryption algorithm using one of the standard - * JCA string representations rather the the algorithm identifier (if - * possible). - */ - String getEncryptionAlgName( - String encryptionAlgOID) - { - String algName = (String)encryptionAlgs.get(encryptionAlgOID); - - if (algName != null) - { - return algName; - } - - return encryptionAlgOID; - } - - - X509Store createAttributeStore( - String type, - Provider provider, - ASN1Set certSet) - throws NoSuchStoreException, CMSException - { - List certs = new ArrayList(); - - if (certSet != null) - { - Enumeration e = certSet.getObjects(); - - while (e.hasMoreElements()) - { - try - { - ASN1Primitive obj = ((ASN1Encodable)e.nextElement()).toASN1Primitive(); - - if (obj instanceof ASN1TaggedObject) - { - ASN1TaggedObject tagged = (ASN1TaggedObject)obj; - - if (tagged.getTagNo() == 2) - { - certs.add(new X509V2AttributeCertificate(ASN1Sequence.getInstance(tagged, false).getEncoded())); - } - } - } - catch (IOException ex) - { - throw new CMSException( - "can't re-encode attribute certificate!", ex); - } - } - } - - try - { - return X509Store.getInstance( - "AttributeCertificate/" +type, new X509CollectionStoreParameters(certs), provider); - } - catch (IllegalArgumentException e) - { - throw new CMSException("can't setup the X509Store", e); - } - } - - X509Store createCertificateStore( - String type, - Provider provider, - ASN1Set certSet) - throws NoSuchStoreException, CMSException - { - List certs = new ArrayList(); - - if (certSet != null) - { - addCertsFromSet(certs, certSet, provider); - } - - try - { - return X509Store.getInstance( - "Certificate/" +type, new X509CollectionStoreParameters(certs), provider); - } - catch (IllegalArgumentException e) - { - throw new CMSException("can't setup the X509Store", e); - } - } - - X509Store createCRLsStore( - String type, - Provider provider, - ASN1Set crlSet) - throws NoSuchStoreException, CMSException - { - List crls = new ArrayList(); - - if (crlSet != null) - { - addCRLsFromSet(crls, crlSet, provider); - } - - try - { - return X509Store.getInstance( - "CRL/" +type, new X509CollectionStoreParameters(crls), provider); - } - catch (IllegalArgumentException e) - { - throw new CMSException("can't setup the X509Store", e); - } - } - - CertStore createCertStore( - String type, - Provider provider, - ASN1Set certSet, - ASN1Set crlSet) - throws CMSException, NoSuchAlgorithmException - { - List certsAndcrls = new ArrayList(); - - // - // load the certificates and revocation lists if we have any - // - - if (certSet != null) - { - addCertsFromSet(certsAndcrls, certSet, provider); - } - - if (crlSet != null) - { - addCRLsFromSet(certsAndcrls, crlSet, provider); - } - - try - { - if (provider != null) - { - return CertStore.getInstance(type, new CollectionCertStoreParameters(certsAndcrls), provider.getName()); - } - else - { - return CertStore.getInstance(type, new CollectionCertStoreParameters(certsAndcrls)); - } - } - catch (InvalidAlgorithmParameterException e) - { - throw new CMSException("can't setup the CertStore", e); - } - catch (NoSuchProviderException e) - { - throw new CMSException("can't setup the CertStore", e); - } - } - - private void addCertsFromSet(List certs, ASN1Set certSet, Provider provider) - throws CMSException - { - CertificateFactory cf; - - try - { - if (provider != null) - { - cf = CertificateFactory.getInstance("X.509", provider.getName()); - } - else - { - cf = CertificateFactory.getInstance("X.509"); - } - } - catch (CertificateException ex) - { - throw new CMSException("can't get certificate factory.", ex); - } - catch (NoSuchProviderException ex) - { - throw new CMSException("can't get certificate factory.", ex); - } - Enumeration e = certSet.getObjects(); - - while (e.hasMoreElements()) - { - try - { - ASN1Primitive obj = ((ASN1Encodable)e.nextElement()).toASN1Primitive(); - - if (obj instanceof ASN1Sequence) - { - certs.add(cf.generateCertificate( - new ByteArrayInputStream(obj.getEncoded()))); - } - } - catch (IOException ex) - { - throw new CMSException( - "can't re-encode certificate!", ex); - } - catch (CertificateException ex) - { - throw new CMSException( - "can't re-encode certificate!", ex); - } - } - } - - private void addCRLsFromSet(List crls, ASN1Set certSet, Provider provider) - throws CMSException - { - CertificateFactory cf; - - try - { - if (provider != null) - { - cf = CertificateFactory.getInstance("X.509", provider.getName()); - } - else - { - cf = CertificateFactory.getInstance("X.509"); - } - } - catch (CertificateException ex) - { - throw new CMSException("can't get certificate factory.", ex); - } - catch (NoSuchProviderException ex) - { - throw new CMSException("can't get certificate factory.", ex); - } - Enumeration e = certSet.getObjects(); - - while (e.hasMoreElements()) - { - try - { - ASN1Primitive obj = ((ASN1Encodable)e.nextElement()).toASN1Primitive(); - - crls.add(cf.generateCRL( - new ByteArrayInputStream(obj.getEncoded()))); - } - catch (IOException ex) - { - throw new CMSException("can't re-encode CRL!", ex); - } - catch (CRLException ex) - { - throw new CMSException("can't re-encode CRL!", ex); - } - } - } - - AlgorithmIdentifier fixAlgID(AlgorithmIdentifier algId) - { - if (algId.getParameters() == null) - { - return new AlgorithmIdentifier(algId.getObjectId(), DERNull.INSTANCE); - } - - return algId; - } - - void setSigningEncryptionAlgorithmMapping(DERObjectIdentifier oid, String algorithmName) - { - encryptionAlgs.put(oid.getId(), algorithmName); - } - - void setSigningDigestAlgorithmMapping(DERObjectIdentifier oid, String algorithmName) - { - digestAlgs.put(oid.getId(), algorithmName); - } -} diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSUtils.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSUtils.java deleted file mode 100644 index 75c6beba..00000000 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/CMSUtils.java +++ /dev/null @@ -1,337 +0,0 @@ -package org.bouncycastle.cms; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; -import java.security.cert.CRLException; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.bouncycastle.asn1.ASN1Encodable; -import org.bouncycastle.asn1.ASN1EncodableVector; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Primitive; -import org.bouncycastle.asn1.ASN1Set; -import org.bouncycastle.asn1.BEROctetStringGenerator; -import org.bouncycastle.asn1.BERSet; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.DERTaggedObject; -import org.bouncycastle.asn1.cms.ContentInfo; -import org.bouncycastle.asn1.cms.IssuerAndSerialNumber; -import org.bouncycastle.asn1.x509.CertificateList; -import org.bouncycastle.asn1.x509.TBSCertificateStructure; -import org.bouncycastle.asn1.x509.X509CertificateStructure; -import org.bouncycastle.cert.X509AttributeCertificateHolder; -import org.bouncycastle.cert.X509CRLHolder; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.operator.DigestCalculator; -import org.bouncycastle.util.Store; -import org.bouncycastle.util.io.Streams; -import org.bouncycastle.util.io.TeeInputStream; -import org.bouncycastle.util.io.TeeOutputStream; - -class CMSUtils -{ - static ContentInfo readContentInfo( - byte[] input) - throws CMSException - { - // enforce limit checking as from a byte array - return readContentInfo(new ASN1InputStream(input)); - } - - static ContentInfo readContentInfo( - InputStream input) - throws CMSException - { - // enforce some limit checking - return readContentInfo(new ASN1InputStream(input)); - } - - static List getCertificatesFromStore(CertStore certStore) - throws CertStoreException, CMSException - { - List certs = new ArrayList(); - - try - { - for (Iterator it = certStore.getCertificates(null).iterator(); it.hasNext();) - { - X509Certificate c = (X509Certificate)it.next(); - - certs.add(X509CertificateStructure.getInstance( - ASN1Primitive.fromByteArray(c.getEncoded()))); - } - - return certs; - } - catch (IllegalArgumentException e) - { - throw new CMSException("error processing certs", e); - } - catch (IOException e) - { - throw new CMSException("error processing certs", e); - } - catch (CertificateEncodingException e) - { - throw new CMSException("error encoding certs", e); - } - } - - static List getCertificatesFromStore(Store certStore) - throws CMSException - { - List certs = new ArrayList(); - - try - { - for (Iterator it = certStore.getMatches(null).iterator(); it.hasNext();) - { - X509CertificateHolder c = (X509CertificateHolder)it.next(); - - certs.add(c.toASN1Structure()); - } - - return certs; - } - catch (ClassCastException e) - { - throw new CMSException("error processing certs", e); - } - } - - static List getAttributeCertificatesFromStore(Store attrStore) - throws CMSException - { - List certs = new ArrayList(); - - try - { - for (Iterator it = attrStore.getMatches(null).iterator(); it.hasNext();) - { - X509AttributeCertificateHolder attrCert = (X509AttributeCertificateHolder)it.next(); - - certs.add(new DERTaggedObject(false, 2, attrCert.toASN1Structure())); - } - - return certs; - } - catch (ClassCastException e) - { - throw new CMSException("error processing certs", e); - } - } - - static List getCRLsFromStore(CertStore certStore) - throws CertStoreException, CMSException - { - List crls = new ArrayList(); - - try - { - for (Iterator it = certStore.getCRLs(null).iterator(); it.hasNext();) - { - X509CRL c = (X509CRL)it.next(); - - crls.add(CertificateList.getInstance(ASN1Primitive.fromByteArray(c.getEncoded()))); - } - - return crls; - } - catch (IllegalArgumentException e) - { - throw new CMSException("error processing crls", e); - } - catch (IOException e) - { - throw new CMSException("error processing crls", e); - } - catch (CRLException e) - { - throw new CMSException("error encoding crls", e); - } - } - - static List getCRLsFromStore(Store crlStore) - throws CMSException - { - List certs = new ArrayList(); - - try - { - for (Iterator it = crlStore.getMatches(null).iterator(); it.hasNext();) - { - X509CRLHolder c = (X509CRLHolder)it.next(); - - certs.add(c.toASN1Structure()); - } - - return certs; - } - catch (ClassCastException e) - { - throw new CMSException("error processing certs", e); - } - } - - static ASN1Set createBerSetFromList(List derObjects) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - for (Iterator it = derObjects.iterator(); it.hasNext();) - { - v.add((ASN1Encodable)it.next()); - } - - return new BERSet(v); - } - - static ASN1Set createDerSetFromList(List derObjects) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - for (Iterator it = derObjects.iterator(); it.hasNext();) - { - v.add((ASN1Encodable)it.next()); - } - - return new DERSet(v); - } - - static OutputStream createBEROctetOutputStream(OutputStream s, - int tagNo, boolean isExplicit, int bufferSize) throws IOException - { - BEROctetStringGenerator octGen = new BEROctetStringGenerator(s, tagNo, isExplicit); - - if (bufferSize != 0) - { - return octGen.getOctetOutputStream(new byte[bufferSize]); - } - - return octGen.getOctetOutputStream(); - } - - static TBSCertificateStructure getTBSCertificateStructure( - X509Certificate cert) - { - try - { - return TBSCertificateStructure.getInstance( - ASN1Primitive.fromByteArray(cert.getTBSCertificate())); - } - catch (Exception e) - { - throw new IllegalArgumentException( - "can't extract TBS structure from this cert"); - } - } - - static IssuerAndSerialNumber getIssuerAndSerialNumber(X509Certificate cert) - { - TBSCertificateStructure tbsCert = getTBSCertificateStructure(cert); - return new IssuerAndSerialNumber(tbsCert.getIssuer(), tbsCert.getSerialNumber().getValue()); - } - - private static ContentInfo readContentInfo( - ASN1InputStream in) - throws CMSException - { - try - { - return ContentInfo.getInstance(in.readObject()); - } - catch (IOException e) - { - throw new CMSException("IOException reading content.", e); - } - catch (ClassCastException e) - { - throw new CMSException("Malformed content.", e); - } - catch (IllegalArgumentException e) - { - throw new CMSException("Malformed content.", e); - } - } - - public static byte[] streamToByteArray( - InputStream in) - throws IOException - { - return Streams.readAll(in); - } - - public static byte[] streamToByteArray( - InputStream in, - int limit) - throws IOException - { - return Streams.readAllLimited(in, limit); - } - - public static Provider getProvider(String providerName) - throws NoSuchProviderException - { - if (providerName != null) - { - Provider prov = Security.getProvider(providerName); - - if (prov != null) - { - return prov; - } - - throw new NoSuchProviderException("provider " + providerName + " not found."); - } - - return null; - } - - static InputStream attachDigestsToInputStream(Collection digests, InputStream s) - { - InputStream result = s; - Iterator it = digests.iterator(); - while (it.hasNext()) - { - DigestCalculator digest = (DigestCalculator)it.next(); - result = new TeeInputStream(result, digest.getOutputStream()); - } - return result; - } - - static OutputStream attachSignersToOutputStream(Collection signers, OutputStream s) - { - OutputStream result = s; - Iterator it = signers.iterator(); - while (it.hasNext()) - { - SignerInfoGenerator signerGen = (SignerInfoGenerator)it.next(); - result = getSafeTeeOutputStream(result, signerGen.getCalculatingOutputStream()); - } - return result; - } - - static OutputStream getSafeOutputStream(OutputStream s) - { - return s == null ? new NullOutputStream() : s; - } - - static OutputStream getSafeTeeOutputStream(OutputStream s1, - OutputStream s2) - { - return s1 == null ? getSafeOutputStream(s2) - : s2 == null ? getSafeOutputStream(s1) : new TeeOutputStream( - s1, s2); - } -} diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/SignerInfoGenerator.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/SignerInfoGenerator.java index 4ac1c91a..acd2665b 100644 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/SignerInfoGenerator.java +++ b/pkix/src/main/jdk1.1/org/bouncycastle/cms/SignerInfoGenerator.java @@ -7,7 +7,6 @@ import java.util.HashMap; import java.util.Map; import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DEROctetString; @@ -23,6 +22,7 @@ import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DigestCalculator; import org.bouncycastle.operator.DigestCalculatorProvider; import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.util.Arrays; import org.bouncycastle.util.io.TeeOutputStream; public class SignerInfoGenerator @@ -123,12 +123,12 @@ public class SignerInfoGenerator public SignerIdentifier getSID() { - return signerIdentifier; + return signerIdentifier; } - public ASN1Integer getGeneratedVersion() + public int getGeneratedVersion() { - return new ASN1Integer(signerIdentifier.isTagged() ? 3 : 1); + return signerIdentifier.isTagged() ? 3 : 1; } public boolean hasAssociatedCertificate() @@ -190,7 +190,7 @@ public class SignerInfoGenerator digestAlg = digester.getAlgorithmIdentifier(); calculatedDigest = digester.getDigest(); Map parameters = getBaseParameters(contentType, digester.getAlgorithmIdentifier(), calculatedDigest); - AttributeTable signed = sAttrGen.getAttributes(new HashMap(parameters)); + AttributeTable signed = sAttrGen.getAttributes(Collections.unmodifiableMap(parameters)); signedAttr = getAttributeSet(signed); @@ -221,9 +221,9 @@ public class SignerInfoGenerator if (unsAttrGen != null) { Map parameters = getBaseParameters(contentType, digestAlg, calculatedDigest); - parameters.put(CMSAttributeTableGenerator.SIGNATURE, sigBytes.clone()); + parameters.put(CMSAttributeTableGenerator.SIGNATURE, Arrays.clone(sigBytes)); - AttributeTable unsigned = unsAttrGen.getAttributes(new HashMap(parameters)); + AttributeTable unsigned = unsAttrGen.getAttributes(Collections.unmodifiableMap(parameters)); unsignedAttr = getAttributeSet(unsigned); } @@ -265,7 +265,7 @@ public class SignerInfoGenerator } param.put(CMSAttributeTableGenerator.DIGEST_ALGORITHM_IDENTIFIER, digAlgId); - param.put(CMSAttributeTableGenerator.DIGEST, hash.clone()); + param.put(CMSAttributeTableGenerator.DIGEST, Arrays.clone(hash)); return param; } @@ -273,7 +273,7 @@ public class SignerInfoGenerator { if (calculatedDigest != null) { - return (byte[])calculatedDigest.clone(); + return Arrays.clone(calculatedDigest); } return null; diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/cms/jcajce/EnvelopedDataHelper.java b/pkix/src/main/jdk1.1/org/bouncycastle/cms/jcajce/EnvelopedDataHelper.java index 9bcc4506..cc1a114c 100644 --- a/pkix/src/main/jdk1.1/org/bouncycastle/cms/jcajce/EnvelopedDataHelper.java +++ b/pkix/src/main/jdk1.1/org/bouncycastle/cms/jcajce/EnvelopedDataHelper.java @@ -1,6 +1,5 @@ package org.bouncycastle.cms.jcajce; -import java.io.IOException; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; @@ -32,9 +31,7 @@ import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Null; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.RC2CBCParameter; @@ -42,18 +39,23 @@ import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.cms.CMSAlgorithm; import org.bouncycastle.cms.CMSEnvelopedDataGenerator; import org.bouncycastle.cms.CMSException; +import org.bouncycastle.operator.DefaultSecretKeySizeProvider; import org.bouncycastle.operator.GenericKey; +import org.bouncycastle.operator.SecretKeySizeProvider; import org.bouncycastle.operator.SymmetricKeyUnwrapper; import org.bouncycastle.operator.jcajce.JceAsymmetricKeyUnwrapper; -class EnvelopedDataHelper +public class EnvelopedDataHelper { + protected static final SecretKeySizeProvider KEY_SIZE_PROVIDER = DefaultSecretKeySizeProvider.INSTANCE; + protected static final Map BASE_CIPHER_NAMES = new HashMap(); protected static final Map CIPHER_ALG_NAMES = new HashMap(); protected static final Map MAC_ALG_NAMES = new HashMap(); static { + BASE_CIPHER_NAMES.put(CMSAlgorithm.DES_CBC, "DES"); BASE_CIPHER_NAMES.put(CMSAlgorithm.DES_EDE3_CBC, "DESEDE"); BASE_CIPHER_NAMES.put(CMSAlgorithm.AES128_CBC, "AES"); BASE_CIPHER_NAMES.put(CMSAlgorithm.AES192_CBC, "AES"); @@ -64,7 +66,10 @@ class EnvelopedDataHelper BASE_CIPHER_NAMES.put(CMSAlgorithm.CAMELLIA192_CBC, "Camellia"); BASE_CIPHER_NAMES.put(CMSAlgorithm.CAMELLIA256_CBC, "Camellia"); BASE_CIPHER_NAMES.put(CMSAlgorithm.SEED_CBC, "SEED"); + BASE_CIPHER_NAMES.put(PKCSObjectIdentifiers.rc4, "RC4"); + CIPHER_ALG_NAMES.put(CMSAlgorithm.DES_CBC, "DES/CBC/PKCS5Padding"); + CIPHER_ALG_NAMES.put(CMSAlgorithm.RC2_CBC, "RC2/CBC/PKCS5Padding"); CIPHER_ALG_NAMES.put(CMSAlgorithm.DES_EDE3_CBC, "DESEDE/CBC/PKCS5Padding"); CIPHER_ALG_NAMES.put(CMSAlgorithm.AES128_CBC, "AES/CBC/PKCS5Padding"); CIPHER_ALG_NAMES.put(CMSAlgorithm.AES192_CBC, "AES/CBC/PKCS5Padding"); @@ -75,6 +80,7 @@ class EnvelopedDataHelper CIPHER_ALG_NAMES.put(CMSAlgorithm.CAMELLIA192_CBC, "Camellia/CBC/PKCS5Padding"); CIPHER_ALG_NAMES.put(CMSAlgorithm.CAMELLIA256_CBC, "Camellia/CBC/PKCS5Padding"); CIPHER_ALG_NAMES.put(CMSAlgorithm.SEED_CBC, "SEED/CBC/PKCS5Padding"); + CIPHER_ALG_NAMES.put(PKCSObjectIdentifiers.rc4, "RC4"); MAC_ALG_NAMES.put(CMSAlgorithm.DES_EDE3_CBC, "DESEDEMac"); MAC_ALG_NAMES.put(CMSAlgorithm.AES128_CBC, "AESMac"); @@ -155,7 +161,7 @@ class EnvelopedDataHelper throw new IllegalArgumentException("unknown generic key type"); } - Key getJceKey(ASN1ObjectIdentifier algorithm, GenericKey key) + public Key getJceKey(ASN1ObjectIdentifier algorithm, GenericKey key) { if (key.getRepresentation() instanceof Key) { @@ -170,6 +176,33 @@ class EnvelopedDataHelper throw new IllegalArgumentException("unknown generic key type"); } + public void keySizeCheck(AlgorithmIdentifier keyAlgorithm, Key key) + throws CMSException + { + int expectedKeySize = EnvelopedDataHelper.KEY_SIZE_PROVIDER.getKeySize(keyAlgorithm); + if (expectedKeySize > 0) + { + byte[] keyEnc = null; + + try + { + keyEnc = key.getEncoded(); + } + catch (Exception e) + { + // ignore - we're using a HSM... + } + + if (keyEnc != null) + { + if (keyEnc.length * 8 != expectedKeySize) + { + throw new CMSException("Expected key size for algorithm OID not found in recipient."); + } + } + } + } + Cipher createCipher(ASN1ObjectIdentifier algorithm) throws CMSException { @@ -191,15 +224,7 @@ class EnvelopedDataHelper } return helper.createCipher(algorithm.getId()); } - catch (NoSuchPaddingException e) - { - throw new CMSException("cannot create cipher: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("cannot create cipher: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) + catch (Exception e) { throw new CMSException("cannot create cipher: " + e.getMessage(), e); } @@ -226,11 +251,7 @@ class EnvelopedDataHelper } return helper.createMac(algorithm.getId()); } - catch (NoSuchProviderException e) - { - throw new CMSException("cannot create mac: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) + catch (Exception e) { throw new CMSException("cannot create mac: " + e.getMessage(), e); } @@ -252,15 +273,7 @@ class EnvelopedDataHelper { return helper.createCipher(cipherName); } - catch (NoSuchPaddingException e) - { - throw new CMSException("cannot create cipher: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("cannot create cipher: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) + catch (Exception e) { throw new CMSException("cannot create cipher: " + e.getMessage(), e); } @@ -287,18 +300,14 @@ class EnvelopedDataHelper } return helper.createKeyAgreement(algorithm.getId()); } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("cannot create key pair generator: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) + catch (Exception e) { throw new CMSException("cannot create key pair generator: " + e.getMessage(), e); } } AlgorithmParameterGenerator createAlgorithmParameterGenerator(ASN1ObjectIdentifier algorithm) - throws GeneralSecurityException + throws CMSException { String algorithmName = (String)BASE_CIPHER_NAMES.get(algorithm); @@ -318,17 +327,13 @@ class EnvelopedDataHelper } return helper.createAlgorithmParameterGenerator(algorithm.getId()); } - catch (NoSuchAlgorithmException e) - { - throw new GeneralSecurityException("cannot create key generator: " + e.getMessage()); - } - catch (NoSuchProviderException e) + catch (Exception e) { - throw new GeneralSecurityException("cannot create key generator: " + e.getMessage()); + throw new CMSException("cannot create key pair generator: " + e.getMessage(), e); } } - Cipher createContentCipher(final Key sKey, final AlgorithmIdentifier encryptionAlgID) + public Cipher createContentCipher(final Key sKey, final AlgorithmIdentifier encryptionAlgID) throws CMSException { return (Cipher)execute(new JCECallback() @@ -348,20 +353,14 @@ class EnvelopedDataHelper { AlgorithmParameters params = createAlgorithmParameters(encryptionAlgID.getAlgorithm()); - try - { - params.init(sParams.toASN1Primitive().getEncoded(), "ASN.1"); - } - catch (IOException e) - { - throw new CMSException("error decoding algorithm parameters.", e); - } + CMSUtils.loadParameters(params, sParams); cipher.init(Cipher.DECRYPT_MODE, sKey, params); } catch (NoSuchAlgorithmException e) { - if (encAlg.equals(CMSEnvelopedDataGenerator.DES_EDE3_CBC) + if (encAlg.equals(CMSAlgorithm.DES_CBC.getId()) + || encAlg.equals(CMSEnvelopedDataGenerator.DES_EDE3_CBC) || encAlg.equals(CMSEnvelopedDataGenerator.IDEA_CBC) || encAlg.equals(CMSEnvelopedDataGenerator.AES128_CBC) || encAlg.equals(CMSEnvelopedDataGenerator.AES192_CBC) @@ -378,7 +377,8 @@ class EnvelopedDataHelper } else { - if (encAlg.equals(CMSEnvelopedDataGenerator.DES_EDE3_CBC) + if (encAlg.equals(CMSAlgorithm.DES_CBC.getId()) + || encAlg.equals(CMSEnvelopedDataGenerator.DES_EDE3_CBC) || encAlg.equals(CMSEnvelopedDataGenerator.IDEA_CBC) || encAlg.equals(CMSEnvelopedDataGenerator.CAST5_CBC)) { @@ -415,14 +415,7 @@ class EnvelopedDataHelper { AlgorithmParameters params = createAlgorithmParameters(macAlgId.getAlgorithm()); - try - { - params.init(sParams.toASN1Primitive().getEncoded(), "ASN.1"); - } - catch (IOException e) - { - throw new CMSException("error decoding algorithm parameters.", e); - } + CMSUtils.loadParameters(params, sParams); mac.init(sKey, params.getParameterSpec(IvParameterSpec.class)); } @@ -462,7 +455,7 @@ class EnvelopedDataHelper } - KeyPairGenerator createKeyPairGenerator(DERObjectIdentifier algorithm) + KeyPairGenerator createKeyPairGenerator(ASN1ObjectIdentifier algorithm) throws CMSException { try @@ -483,11 +476,7 @@ class EnvelopedDataHelper } return helper.createKeyPairGenerator(algorithm.getId()); } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("cannot create key pair generator: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) + catch (Exception e) { throw new CMSException("cannot create key pair generator: " + e.getMessage(), e); } @@ -514,11 +503,7 @@ class EnvelopedDataHelper } return helper.createKeyGenerator(algorithm.getId()); } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("cannot create key generator: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) + catch (Exception e) { throw new CMSException("cannot create key generator: " + e.getMessage(), e); } @@ -531,7 +516,7 @@ class EnvelopedDataHelper { AlgorithmParameterGenerator pGen = createAlgorithmParameterGenerator(encryptionOID); - if (encryptionOID.equals(CMSEnvelopedDataGenerator.RC2_CBC)) + if (encryptionOID.equals(CMSAlgorithm.RC2_CBC)) { byte[] iv = new byte[8]; @@ -549,7 +534,7 @@ class EnvelopedDataHelper return pGen.generateParameters(); } - catch (GeneralSecurityException e) + catch (Exception e) { throw new CMSException("exception creating algorithm parameter generator: " + e, e); } @@ -561,14 +546,7 @@ class EnvelopedDataHelper ASN1Encodable asn1Params; if (params != null) { - try - { - asn1Params = ASN1Primitive.fromByteArray(params.getEncoded("ASN.1")); - } - catch (IOException e) - { - throw new CMSException("cannot encode parameters: " + e.getMessage(), e); - } + asn1Params = CMSUtils.extractParameters(params); } else { @@ -633,11 +611,7 @@ class EnvelopedDataHelper } return helper.createKeyFactory(algorithm.getId()); } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("cannot create key factory: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) + catch (Exception e) { throw new CMSException("cannot create key factory: " + e.getMessage(), e); } diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/tsp/TimeStampToken.java b/pkix/src/main/jdk1.1/org/bouncycastle/tsp/TimeStampToken.java deleted file mode 100644 index bc4a631a..00000000 --- a/pkix/src/main/jdk1.1/org/bouncycastle/tsp/TimeStampToken.java +++ /dev/null @@ -1,496 +0,0 @@ -package org.bouncycastle.tsp; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.cert.CertStore; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; -import java.util.Collection; -import java.util.Date; - -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.cms.Attribute; -import org.bouncycastle.asn1.cms.AttributeTable; -import org.bouncycastle.asn1.cms.ContentInfo; -import org.bouncycastle.asn1.cms.IssuerAndSerialNumber; -import org.bouncycastle.asn1.ess.ESSCertID; -import org.bouncycastle.asn1.ess.ESSCertIDv2; -import org.bouncycastle.asn1.ess.SigningCertificate; -import org.bouncycastle.asn1.ess.SigningCertificateV2; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.tsp.TSTInfo; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.IssuerSerial; -import org.bouncycastle.asn1.x509.X509Name; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cms.CMSException; -import org.bouncycastle.cms.CMSProcessable; -import org.bouncycastle.cms.CMSSignedData; -import org.bouncycastle.cms.SignerId; -import org.bouncycastle.cms.SignerInformation; -import org.bouncycastle.cms.SignerInformationVerifier; -import org.bouncycastle.jce.PrincipalUtil; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.operator.DigestCalculator; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.util.Arrays; -import org.bouncycastle.util.Store; - -public class TimeStampToken -{ - CMSSignedData tsToken; - - SignerInformation tsaSignerInfo; - - Date genTime; - - TimeStampTokenInfo tstInfo; - - CertID certID; - - public TimeStampToken(ContentInfo contentInfo) - throws TSPException, IOException - { - this(getSignedData(contentInfo)); - } - - private static CMSSignedData getSignedData(ContentInfo contentInfo) - throws TSPException - { - try - { - return new CMSSignedData(contentInfo); - } - catch (CMSException e) - { - throw new TSPException("TSP parsing error: " + e.getMessage(), e.getCause()); - } - } - - public TimeStampToken(CMSSignedData signedData) - throws TSPException, IOException - { - this.tsToken = signedData; - - if (!this.tsToken.getSignedContentTypeOID().equals(PKCSObjectIdentifiers.id_ct_TSTInfo.getId())) - { - throw new TSPValidationException("ContentInfo object not for a time stamp."); - } - - Collection signers = tsToken.getSignerInfos().getSigners(); - - if (signers.size() != 1) - { - throw new IllegalArgumentException("Time-stamp token signed by " - + signers.size() - + " signers, but it must contain just the TSA signature."); - } - - tsaSignerInfo = (SignerInformation)signers.iterator().next(); - - try - { - CMSProcessable content = tsToken.getSignedContent(); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - content.write(bOut); - - ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bOut.toByteArray())); - - this.tstInfo = new TimeStampTokenInfo(TSTInfo.getInstance(aIn.readObject())); - - Attribute attr = tsaSignerInfo.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate); - - if (attr != null) - { - SigningCertificate signCert = SigningCertificate.getInstance(attr.getAttrValues().getObjectAt(0)); - - this.certID = new CertID(ESSCertID.getInstance(signCert.getCerts()[0])); - } - else - { - attr = tsaSignerInfo.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2); - - if (attr == null) - { - throw new TSPValidationException("no signing certificate attribute found, time stamp invalid."); - } - - SigningCertificateV2 signCertV2 = SigningCertificateV2.getInstance(attr.getAttrValues().getObjectAt(0)); - - this.certID = new CertID(ESSCertIDv2.getInstance(signCertV2.getCerts()[0])); - } - } - catch (CMSException e) - { - throw new TSPException(e.getMessage(), e.getUnderlyingException()); - } - } - - public TimeStampTokenInfo getTimeStampInfo() - { - return tstInfo; - } - - public SignerId getSID() - { - return tsaSignerInfo.getSID(); - } - - public AttributeTable getSignedAttributes() - { - return tsaSignerInfo.getSignedAttributes(); - } - - public AttributeTable getUnsignedAttributes() - { - return tsaSignerInfo.getUnsignedAttributes(); - } - - /** - * @deprecated use getCertificates() or getCRLs() - */ - public CertStore getCertificatesAndCRLs( - String type, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, CMSException - { - return tsToken.getCertificatesAndCRLs(type, provider); - } - - public Store getCertificates() - { - return tsToken.getCertificates(); - } - - public Store getCRLs() - { - return tsToken.getCRLs(); - } - - public Store getAttributeCertificates() - { - return tsToken.getAttributeCertificates(); - } - - /** - * Validate the time stamp token. - * <p> - * To be valid the token must be signed by the passed in certificate and - * the certificate must be the one referred to by the SigningCertificate - * attribute included in the hashed attributes of the token. The - * certificate must also have the ExtendedKeyUsageExtension with only - * KeyPurposeId.id_kp_timeStamping and have been valid at the time the - * timestamp was created. - * </p> - * <p> - * A successful call to validate means all the above are true. - * </p> - * @deprecated - */ - public void validate( - X509Certificate cert, - String provider) - throws TSPException, TSPValidationException, - CertificateExpiredException, CertificateNotYetValidException, NoSuchProviderException - { - try - { - if (!Arrays.constantTimeAreEqual(certID.getCertHash(), MessageDigest.getInstance(certID.getHashAlgorithmName()).digest(cert.getEncoded()))) - { - throw new TSPValidationException("certificate hash does not match certID hash."); - } - - if (certID.getIssuerSerial() != null) - { - if (!certID.getIssuerSerial().getSerial().getValue().equals(cert.getSerialNumber())) - { - throw new TSPValidationException("certificate serial number does not match certID for signature."); - } - - GeneralName[] names = certID.getIssuerSerial().getIssuer().getNames(); - X509Principal principal = PrincipalUtil.getIssuerX509Principal(cert); - boolean found = false; - - for (int i = 0; i != names.length; i++) - { - if (names[i].getTagNo() == 4 && new X509Principal(X509Name.getInstance(names[i].getName())).equals(principal)) - { - found = true; - break; - } - } - - if (!found) - { - throw new TSPValidationException("certificate name does not match certID for signature. "); - } - } - - TSPUtil.validateCertificate(cert); - - cert.checkValidity(tstInfo.getGenTime()); - - if (!tsaSignerInfo.verify(cert, provider)) - { - throw new TSPValidationException("signature not created by certificate."); - } - } - catch (CMSException e) - { - if (e.getUnderlyingException() != null) - { - throw new TSPException(e.getMessage(), e.getUnderlyingException()); - } - else - { - throw new TSPException("CMS exception: " + e, e); - } - } - catch (NoSuchAlgorithmException e) - { - throw new TSPException("cannot find algorithm: " + e, e); - } - catch (CertificateEncodingException e) - { - throw new TSPException("problem processing certificate: " + e, e); - } - } - - /** - * Validate the time stamp token. - * <p> - * To be valid the token must be signed by the passed in certificate and - * the certificate must be the one referred to by the SigningCertificate - * attribute included in the hashed attributes of the token. The - * certificate must also have the ExtendedKeyUsageExtension with only - * KeyPurposeId.id_kp_timeStamping and have been valid at the time the - * timestamp was created. - * </p> - * <p> - * A successful call to validate means all the above are true. - * </p> - * - * @param sigVerifier the content verifier create the objects required to verify the CMS object in the timestamp. - * @throws TSPException if an exception occurs in processing the token. - * @throws TSPValidationException if the certificate or signature fail to be valid. - * @throws IllegalArgumentException if the sigVerifierProvider has no associated certificate. - */ - public void validate( - SignerInformationVerifier sigVerifier) - throws TSPException, TSPValidationException - { - if (!sigVerifier.hasAssociatedCertificate()) - { - throw new IllegalArgumentException("verifier provider needs an associated certificate"); - } - - try - { - X509CertificateHolder certHolder = sigVerifier.getAssociatedCertificate(); - DigestCalculator calc = sigVerifier.getDigestCalculator(certID.getHashAlgorithm()); - - OutputStream cOut = calc.getOutputStream(); - - cOut.write(certHolder.getEncoded()); - cOut.close(); - - if (!Arrays.constantTimeAreEqual(certID.getCertHash(), calc.getDigest())) - { - throw new TSPValidationException("certificate hash does not match certID hash."); - } - - if (certID.getIssuerSerial() != null) - { - IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(certHolder.toASN1Structure()); - - if (!certID.getIssuerSerial().getSerial().equals(issuerSerial.getSerialNumber())) - { - throw new TSPValidationException("certificate serial number does not match certID for signature."); - } - - GeneralName[] names = certID.getIssuerSerial().getIssuer().getNames(); - boolean found = false; - - for (int i = 0; i != names.length; i++) - { - if (names[i].getTagNo() == 4 && X500Name.getInstance(names[i].getName()).equals(X500Name.getInstance(issuerSerial.getName()))) - { - found = true; - break; - } - } - - if (!found) - { - throw new TSPValidationException("certificate name does not match certID for signature. "); - } - } - - TSPUtil.validateCertificate(certHolder); - - if (!certHolder.isValidOn(tstInfo.getGenTime())) - { - throw new TSPValidationException("certificate not valid when time stamp created."); - } - - if (!tsaSignerInfo.verify(sigVerifier)) - { - throw new TSPValidationException("signature not created by certificate."); - } - } - catch (CMSException e) - { - if (e.getUnderlyingException() != null) - { - throw new TSPException(e.getMessage(), e.getUnderlyingException()); - } - else - { - throw new TSPException("CMS exception: " + e, e); - } - } - catch (IOException e) - { - throw new TSPException("problem processing certificate: " + e, e); - } - catch (OperatorCreationException e) - { - throw new TSPException("unable to create digest: " + e.getMessage(), e); - } - } - - /** - * Return true if the signature on time stamp token is valid. - * <p> - * Note: this is a much weaker proof of correctness than calling validate(). - * </p> - * - * @param sigVerifier the content verifier create the objects required to verify the CMS object in the timestamp. - * @return true if the signature matches, false otherwise. - * @throws TSPException if the signature cannot be processed or the provider cannot match the algorithm. - */ - public boolean isSignatureValid( - SignerInformationVerifier sigVerifier) - throws TSPException - { - try - { - return tsaSignerInfo.verify(sigVerifier); - } - catch (CMSException e) - { - if (e.getUnderlyingException() != null) - { - throw new TSPException(e.getMessage(), e.getUnderlyingException()); - } - else - { - throw new TSPException("CMS exception: " + e, e); - } - } - } - - /** - * Return the underlying CMSSignedData object. - * - * @return the underlying CMS structure. - */ - public CMSSignedData toCMSSignedData() - { - return tsToken; - } - - /** - * Return a ASN.1 encoded byte stream representing the encoded object. - * - * @throws IOException if encoding fails. - */ - public byte[] getEncoded() - throws IOException - { - return tsToken.getEncoded(); - } - - // perhaps this should be done using an interface on the ASN.1 classes... - private class CertID - { - private ESSCertID certID; - private ESSCertIDv2 certIDv2; - - CertID(ESSCertID certID) - { - this.certID = certID; - this.certIDv2 = null; - } - - CertID(ESSCertIDv2 certID) - { - this.certIDv2 = certID; - this.certID = null; - } - - public String getHashAlgorithmName() - { - if (certID != null) - { - return "SHA-1"; - } - else - { - if (NISTObjectIdentifiers.id_sha256.equals(certIDv2.getHashAlgorithm().getAlgorithm())) - { - return "SHA-256"; - } - return certIDv2.getHashAlgorithm().getAlgorithm().getId(); - } - } - - public AlgorithmIdentifier getHashAlgorithm() - { - if (certID != null) - { - return new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1); - } - else - { - return certIDv2.getHashAlgorithm(); - } - } - - public byte[] getCertHash() - { - if (certID != null) - { - return certID.getCertHash(); - } - else - { - return certIDv2.getCertHash(); - } - } - - public IssuerSerial getIssuerSerial() - { - if (certID != null) - { - return certID.getIssuerSerial(); - } - else - { - return certIDv2.getIssuerSerial(); - } - } - } -} diff --git a/pkix/src/main/jdk1.1/org/bouncycastle/tsp/TimeStampTokenGenerator.java b/pkix/src/main/jdk1.1/org/bouncycastle/tsp/TimeStampTokenGenerator.java deleted file mode 100644 index f3093159..00000000 --- a/pkix/src/main/jdk1.1/org/bouncycastle/tsp/TimeStampTokenGenerator.java +++ /dev/null @@ -1,472 +0,0 @@ -package org.bouncycastle.tsp; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.cert.CRLException; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.security.interfaces.DSAPrivateKey; -import java.security.interfaces.RSAPrivateKey; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.bouncycastle.asn1.ASN1Boolean; -import org.bouncycastle.asn1.ASN1Encoding; -import org.bouncycastle.asn1.ASN1GeneralizedTime; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.DERNull; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.cms.Attribute; -import org.bouncycastle.asn1.cms.AttributeTable; -import org.bouncycastle.asn1.ess.ESSCertID; -import org.bouncycastle.asn1.ess.SigningCertificate; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.bouncycastle.asn1.tsp.Accuracy; -import org.bouncycastle.asn1.tsp.MessageImprint; -import org.bouncycastle.asn1.tsp.TSTInfo; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.cert.jcajce.JcaX509CRLHolder; -import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; -import org.bouncycastle.cms.CMSAttributeTableGenerationException; -import org.bouncycastle.cms.CMSAttributeTableGenerator; -import org.bouncycastle.cms.CMSException; -import org.bouncycastle.cms.CMSProcessableByteArray; -import org.bouncycastle.cms.CMSSignedData; -import org.bouncycastle.cms.CMSSignedDataGenerator; -import org.bouncycastle.cms.CMSSignedGenerator; -import org.bouncycastle.cms.DefaultSignedAttributeTableGenerator; -import org.bouncycastle.cms.SignerInfoGenerator; -import org.bouncycastle.cms.SimpleAttributeTableGenerator; -import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; -import org.bouncycastle.jce.interfaces.GOST3410PrivateKey; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; -import org.bouncycastle.util.CollectionStore; -import org.bouncycastle.util.Store; - -public class TimeStampTokenGenerator -{ - int accuracySeconds = -1; - - int accuracyMillis = -1; - - int accuracyMicros = -1; - - boolean ordering = false; - - GeneralName tsa = null; - - private ASN1ObjectIdentifier tsaPolicyOID; - - PrivateKey key; - X509Certificate cert; - String digestOID; - AttributeTable signedAttr; - AttributeTable unsignedAttr; - - private List certs = new ArrayList(); - private List crls = new ArrayList(); - private List attrCerts = new ArrayList(); - private SignerInfoGenerator signerInfoGen; - - /** - * - */ - public TimeStampTokenGenerator( - final SignerInfoGenerator signerInfoGen, - ASN1ObjectIdentifier tsaPolicy) - throws IllegalArgumentException, TSPException - { - this.signerInfoGen = signerInfoGen; - this.tsaPolicyOID = tsaPolicy; - - if (!signerInfoGen.hasAssociatedCertificate()) - { - throw new IllegalArgumentException("SignerInfoGenerator must have an associated certificate"); - } - - TSPUtil.validateCertificate(signerInfoGen.getAssociatedCertificate()); - - try - { - final ESSCertID essCertid = new ESSCertID(MessageDigest.getInstance("SHA-1").digest(signerInfoGen.getAssociatedCertificate().getEncoded())); - - this.signerInfoGen = new SignerInfoGenerator(signerInfoGen, new CMSAttributeTableGenerator() - { - public AttributeTable getAttributes(Map parameters) - throws CMSAttributeTableGenerationException - { - AttributeTable table = signerInfoGen.getSignedAttributeTableGenerator().getAttributes(parameters); - - return table.add(PKCSObjectIdentifiers.id_aa_signingCertificate, new SigningCertificate(essCertid)); - } - }, signerInfoGen.getUnsignedAttributeTableGenerator()); - - } - catch (NoSuchAlgorithmException e) - { - throw new TSPException("Can't find a SHA-1 implementation.", e); - } - catch (IOException e) - { - throw new TSPException("Exception processing certificate.", e); - } - } - - /** - * basic creation - only the default attributes will be included here. - * @deprecated use SignerInfoGenerator constructor - */ - public TimeStampTokenGenerator( - PrivateKey key, - X509Certificate cert, - String digestOID, - String tsaPolicyOID) - throws IllegalArgumentException, TSPException - { - this(key, cert, digestOID, tsaPolicyOID, null, null); - } - - /** - * basic creation - only the default attributes will be included here. - * @deprecated use SignerInfoGenerator constructor - */ - public TimeStampTokenGenerator( - PrivateKey key, - X509Certificate cert, - ASN1ObjectIdentifier digestOID, - String tsaPolicyOID) - throws IllegalArgumentException, TSPException - { - this(key, cert, digestOID.getId(), tsaPolicyOID, null, null); - } - - /** - * create with a signer with extra signed/unsigned attributes. - * @deprecated use SignerInfoGenerator constructor - */ - public TimeStampTokenGenerator( - PrivateKey key, - X509Certificate cert, - String digestOID, - String tsaPolicyOID, - AttributeTable signedAttr, - AttributeTable unsignedAttr) - throws IllegalArgumentException, TSPException - { - this.key = key; - this.cert = cert; - this.digestOID = digestOID; - this.tsaPolicyOID = new ASN1ObjectIdentifier(tsaPolicyOID); - this.unsignedAttr = unsignedAttr; - - // - // add the essCertid - // - Hashtable signedAttrs = null; - - if (signedAttr != null) - { - signedAttrs = signedAttr.toHashtable(); - } - else - { - signedAttrs = new Hashtable(); - } - - - TSPUtil.validateCertificate(cert); - - try - { - ESSCertID essCertid = new ESSCertID(MessageDigest.getInstance("SHA-1").digest(cert.getEncoded())); - signedAttrs.put(PKCSObjectIdentifiers.id_aa_signingCertificate, - new Attribute( - PKCSObjectIdentifiers.id_aa_signingCertificate, - new DERSet(new SigningCertificate(essCertid)))); - } - catch (NoSuchAlgorithmException e) - { - throw new TSPException("Can't find a SHA-1 implementation.", e); - } - catch (CertificateEncodingException e) - { - throw new TSPException("Exception processing certificate.", e); - } - - this.signedAttr = new AttributeTable(signedAttrs); - } - - /** - * @deprecated use addCertificates and addCRLs - * @param certificates - * @throws CertStoreException - * @throws TSPException - */ - public void setCertificatesAndCRLs(CertStore certificates) - throws CertStoreException, TSPException - { - Collection c1 = certificates.getCertificates(null); - - for (Iterator it = c1.iterator(); it.hasNext();) - { - try - { - certs.add(new JcaX509CertificateHolder((X509Certificate)it.next())); - } - catch (CertificateEncodingException e) - { - throw new TSPException("cannot encode certificate: " + e.getMessage(), e); - } - } - - c1 = certificates.getCRLs(null); - - for (Iterator it = c1.iterator(); it.hasNext();) - { - try - { - crls.add(new JcaX509CRLHolder((X509CRL)it.next())); - } - catch (CRLException e) - { - throw new TSPException("cannot encode CRL: " + e.getMessage(), e); - } - } - } - - /** - * Add the store of X509 Certificates to the generator. - * - * @param certStore a Store containing X509CertificateHolder objects - */ - public void addCertificates( - Store certStore) - { - certs.addAll(certStore.getMatches(null)); - } - - /** - * - * @param crlStore a Store containing X509CRLHolder objects. - */ - public void addCRLs( - Store crlStore) - { - crls.addAll(crlStore.getMatches(null)); - } - - /** - * - * @param attrStore a Store containing X509AttributeCertificate objects. - */ - public void addAttributeCertificates( - Store attrStore) - { - attrCerts.addAll(attrStore.getMatches(null)); - } - - public void setAccuracySeconds(int accuracySeconds) - { - this.accuracySeconds = accuracySeconds; - } - - public void setAccuracyMillis(int accuracyMillis) - { - this.accuracyMillis = accuracyMillis; - } - - public void setAccuracyMicros(int accuracyMicros) - { - this.accuracyMicros = accuracyMicros; - } - - public void setOrdering(boolean ordering) - { - this.ordering = ordering; - } - - public void setTSA(GeneralName tsa) - { - this.tsa = tsa; - } - - //------------------------------------------------------------------------------ - - public TimeStampToken generate( - TimeStampRequest request, - BigInteger serialNumber, - Date genTime, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, TSPException - { - if (signerInfoGen == null) - { - try - { - JcaSignerInfoGeneratorBuilder sigBuilder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider(provider).build()); - - sigBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttr)); - - if (unsignedAttr != null) - { - sigBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(unsignedAttr)); - } - - signerInfoGen = sigBuilder.build(new JcaContentSignerBuilder(getSigAlgorithm(key, digestOID)).setProvider(provider).build(key), cert); - } - catch (OperatorCreationException e) - { - throw new TSPException("Error generating signing operator", e); - } - catch (CertificateEncodingException e) - { - throw new TSPException("Error encoding certificate", e); - } - } - - return generate(request, serialNumber, genTime); - } - - public TimeStampToken generate( - TimeStampRequest request, - BigInteger serialNumber, - Date genTime) - throws TSPException - { - if (signerInfoGen == null) - { - throw new IllegalStateException("can only use this method with SignerInfoGenerator constructor"); - } - - ASN1ObjectIdentifier digestAlgOID = request.getMessageImprintAlgOID(); - - AlgorithmIdentifier algID = new AlgorithmIdentifier(digestAlgOID, new DERNull()); - MessageImprint messageImprint = new MessageImprint(algID, request.getMessageImprintDigest()); - - Accuracy accuracy = null; - if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0) - { - ASN1Integer seconds = null; - if (accuracySeconds > 0) - { - seconds = new ASN1Integer(accuracySeconds); - } - - ASN1Integer millis = null; - if (accuracyMillis > 0) - { - millis = new ASN1Integer(accuracyMillis); - } - - ASN1Integer micros = null; - if (accuracyMicros > 0) - { - micros = new ASN1Integer(accuracyMicros); - } - - accuracy = new Accuracy(seconds, millis, micros); - } - - ASN1Boolean derOrdering = null; - if (ordering) - { - derOrdering = new ASN1Boolean(ordering); - } - - ASN1Integer nonce = null; - if (request.getNonce() != null) - { - nonce = new ASN1Integer(request.getNonce()); - } - - ASN1ObjectIdentifier tsaPolicy = tsaPolicyOID; - if (request.getReqPolicy() != null) - { - tsaPolicy = request.getReqPolicy(); - } - - TSTInfo tstInfo = new TSTInfo(tsaPolicy, - messageImprint, new ASN1Integer(serialNumber), - new ASN1GeneralizedTime(genTime), accuracy, derOrdering, - nonce, tsa, request.getExtensions()); - - try - { - CMSSignedDataGenerator signedDataGenerator = new CMSSignedDataGenerator(); - - if (request.getCertReq()) - { - // TODO: do we need to check certs non-empty? - signedDataGenerator.addCertificates(new CollectionStore(certs)); - signedDataGenerator.addCRLs(new CollectionStore(crls)); - signedDataGenerator.addAttributeCertificates(new CollectionStore(attrCerts)); - } - else - { - signedDataGenerator.addCRLs(new CollectionStore(crls)); - } - - signedDataGenerator.addSignerInfoGenerator(signerInfoGen); - - byte[] derEncodedTSTInfo = tstInfo.getEncoded(ASN1Encoding.DER); - - CMSSignedData signedData = signedDataGenerator.generate(new CMSProcessableByteArray(PKCSObjectIdentifiers.id_ct_TSTInfo, derEncodedTSTInfo), true); - - return new TimeStampToken(signedData); - } - catch (CMSException cmsEx) - { - throw new TSPException("Error generating time-stamp token", cmsEx); - } - catch (IOException e) - { - throw new TSPException("Exception encoding info", e); - } - } - - private String getSigAlgorithm( - PrivateKey key, - String digestOID) - { - String enc = null; - - if (key instanceof RSAPrivateKey || "RSA".equalsIgnoreCase(key.getAlgorithm())) - { - enc = "RSA"; - } - else if (key instanceof DSAPrivateKey || "DSA".equalsIgnoreCase(key.getAlgorithm())) - { - enc = "DSA"; - } - else if ("ECDSA".equalsIgnoreCase(key.getAlgorithm()) || "EC".equalsIgnoreCase(key.getAlgorithm())) - { - enc = "ECDSA"; - } - else if (key instanceof GOST3410PrivateKey || "GOST3410".equalsIgnoreCase(key.getAlgorithm())) - { - enc = "GOST3410"; - } - else if ("ECGOST3410".equalsIgnoreCase(key.getAlgorithm())) - { - enc = CMSSignedGenerator.ENCRYPTION_ECGOST3410; - } - - return TSPUtil.getDigestAlgName(digestOID) + "with" + enc; - } -} |