Encrypting and signing messages

See below for how to encrypt and sign a PKCS #7 message.

Logging the user

Instantiate a user, set the connection to the Directory (if the user provides the IP address), and log in.

FileInputStream credentials = new FileInputStream (<credentials_location>);
SecureStringBuffer password = new SecureStringBuffer(new StringBuffer(<user_password>));
User user = new User();
if (<IP address> != null)
{
JNDIDirectory dir = new JNDIDirectory (<ip>, <port>);
user.setConnections(dir, null);
}
CredentialReader credReader = new StreamProfileReader(credentials);
user.login(credReader, password>);

Creating the encoder

Create a PKCS7EncodeStream object.

PKCS7EncodeStream encoder = new PKCS7EncodeStream(user, new FileOutputStream(<output_file>), PKCS7EncodeStream.SIGN_AND_ENCRYPT);

Where SIGN_AND_ENCRYPT is the operation constant for signing and encrypting data. The other operations are:

  • ENCRYPT_ONLY

  • SIGN_ONLY

  • EXPORT_CERTIFICATES

  • CLEAR_SIGN

Adding the recipient's certificates

Create a CertificateSet object and load it with the recipient's public key certificates.

X509Certificate[] certs = new X509Certificate[1];
certs[0] = new X509Certificate(new FileInputStream(<recipient_cert_path>));
CertificateSet certSet = new CertificateSet(certs);
while (<command_line_cert_list>)
{
certs[0] = new X509Certificate(new FileInputStream(args[<next_recipient>]));
certSet.addElement(certs[0]);
}

Create a CertificateSet object to hold rejected certificates and call CertificateSet.setRecipients() to validate the recipient's certificates.

CertificateSet rejectedCerts = encoder.setRecipients(certSet);

See the following sample for more details.

etjava\examples\source\com\entrust\toolkit\examples\pkcs7\encode.java

Selecting the algorithms

Specify the digest and encryption algorithms.

encoder.setDigestAlgorithm(AlgorithmID.sha);
encoder.setEncryptionAlgorithm(AlgorithmID.aes256CBC);

If sending large data, specify a block size in bytes.

encoder.setBlockSize(1024);

Encrypting and signing the data

Specify the location of the input data and write the encrypted and signed data to the output stream.

FileInputStream input_data = new FileInputStream(<input_data_location>);
byte[] b = new byte[128];
int i = input_data.read(b);
while (i >= 0)
{
encoder.write(b, 0, i);
i = input_data.read(b);
}

Close the output stream when the write operation is complete.

encoder.close();