1 package org.eparapher.core.encryption;
2
3 import java.io.DataInputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.security.NoSuchAlgorithmException;
10 import java.security.NoSuchProviderException;
11 import java.security.cert.X509Certificate;
12
13 import org.apache.log4j.Logger;
14 import org.bouncycastle.cms.CMSEnvelopedData;
15 import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
16 import org.bouncycastle.cms.CMSException;
17 import org.bouncycastle.cms.CMSProcessableByteArray;
18 import org.eparapher.core.crypto.EPKeystoreManager;
19 import org.eparapher.core.crypto.keystore.IUserKeystore;
20
21
22 public class CMSEncryption {
23
24 private static Logger log = Logger.getLogger(CMSEncryption.class);
25
26 private IUserKeystore userpkandcert;
27
28 public CMSEncryption() {
29 userpkandcert = EPKeystoreManager.getInstance().getUserkeystore();
30 }
31
32 public String encrypt( String original_file, CMSEncryptionParameters cmsencparams )
33 throws FileNotFoundException, IOException, NoSuchAlgorithmException,
34 NoSuchProviderException, CMSException {
35
36
37 File file2encrypt = new File(original_file);
38 int file2encryptsize = (int) file2encrypt.length();
39 byte[] clearcontentbuffer = new byte[file2encryptsize];
40
41 DataInputStream in = new DataInputStream(new FileInputStream(file2encrypt));
42 in.readFully(clearcontentbuffer);
43 in.close();
44
45
46 String algorithm = cmsencparams.getAlgorithm();
47 int keysize = cmsencparams.getKeysize();
48 CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator();
49
50 String encrypted_file = manageFileBeforeEncryption( original_file, cmsencparams );
51
52
53 for (X509Certificate certificate : cmsencparams.getRecipientsCertificates()) {
54 log.info("Adding recipient : " + certificate.getSubjectDN() );
55 fact.addKeyTransRecipient(certificate);
56 }
57
58 CMSProcessableByteArray encryptedcontent = new CMSProcessableByteArray(clearcontentbuffer);
59
60 CMSEnvelopedData envdata = fact.generate(encryptedcontent, algorithm, keysize, "BC");
61 byte[] enveloped = envdata.getEncoded();
62 log.info("Got encoded pkcs7 bytes " + enveloped.length + " bytes");
63 FileOutputStream envfos = new FileOutputStream( encrypted_file );
64 envfos.write(enveloped);
65 envfos.close();
66
67
68
69
70
71 log.info("Your files are encrypted");
72
73 return encrypted_file;
74 }
75
76 private String manageFileBeforeEncryption(String original_file, CMSEncryptionParameters cmsencparams) {
77 return original_file + ".p7m";
78 }
79
80 }