01: package org.bouncycastle.cms;
02:
03: import java.io.ByteArrayInputStream;
04: import java.io.ByteArrayOutputStream;
05: import java.io.IOException;
06: import java.util.zip.DeflaterOutputStream;
07:
08: import org.bouncycastle.asn1.ASN1InputStream;
09: import org.bouncycastle.asn1.ASN1OctetString;
10: import org.bouncycastle.asn1.BERConstructedOctetString;
11: import org.bouncycastle.asn1.DERObject;
12: import org.bouncycastle.asn1.DERObjectIdentifier;
13: import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
14: import org.bouncycastle.asn1.cms.CompressedData;
15: import org.bouncycastle.asn1.cms.ContentInfo;
16: import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
17:
18: /**
19: * General class for generating a compressed CMS message.
20: * <p>
21: * A simple example of usage.
22: * <p>
23: * <pre>
24: * CMSCompressedDataGenerator fact = new CMSCompressedDataGenerator();
25: *
26: * CMSCompressedData data = fact.generate(content, algorithm);
27: * </pre>
28: */
29: public class CMSCompressedDataGenerator {
30: public static final String ZLIB = "1.2.840.113549.1.9.16.3.8";
31:
32: /**
33: * base constructor
34: */
35: public CMSCompressedDataGenerator() {
36: }
37:
38: private DERObject makeObj(byte[] encoding) throws IOException {
39: if (encoding == null) {
40: return null;
41: }
42:
43: ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);
44: ASN1InputStream aIn = new ASN1InputStream(bIn);
45:
46: return aIn.readObject();
47: }
48:
49: private AlgorithmIdentifier makeAlgId(String oid, byte[] params)
50: throws IOException {
51: if (params != null) {
52: return new AlgorithmIdentifier(
53: new DERObjectIdentifier(oid), makeObj(params));
54: } else {
55: return new AlgorithmIdentifier(new DERObjectIdentifier(oid));
56: }
57: }
58:
59: /**
60: * generate an object that contains an CMS Compressed Data
61: */
62: public CMSCompressedData generate(CMSProcessable content,
63: String compressionOID) throws CMSException {
64: AlgorithmIdentifier comAlgId;
65: ASN1OctetString comOcts;
66:
67: try {
68: ByteArrayOutputStream bOut = new ByteArrayOutputStream();
69: DeflaterOutputStream zOut = new DeflaterOutputStream(bOut);
70:
71: content.write(zOut);
72:
73: zOut.close();
74:
75: comAlgId = makeAlgId(compressionOID, null);
76: comOcts = new BERConstructedOctetString(bOut.toByteArray());
77: } catch (IOException e) {
78: throw new CMSException("exception encoding data.", e);
79: }
80:
81: ContentInfo comContent = new ContentInfo(
82: CMSObjectIdentifiers.data, comOcts);
83:
84: ContentInfo contentInfo = new ContentInfo(
85: CMSObjectIdentifiers.compressedData,
86: new CompressedData(comAlgId, comContent));
87:
88: return new CMSCompressedData(contentInfo);
89: }
90: }
|