· 6 years ago · Mar 13, 2019, 03:16 PM
1// Sample text to encrypt.
2String stringToEncrypt = "Sample string to encrypt.";
3// Selects encryption mechanism. I've selected AES, CBC(Code Block Chaning) with Padding.
4Mechanism encryptionMechanism = Mechanism.get(PKCS11Constants.CKM_AES_CBC_PAD);
5// For some mechanisms there are parameters required to configure before performing the operation.
6InitializationVectorParameters encryptionIV = new InitializationVectorParameters(new byte[16]);
7// Set the parameters of the mechanism.
8encryptionMechanism.setParameters(encryptionIV);
9// Instantiate encryption. Mechanism and secret key is required.
10session.encryptInit(encryptionMechanism, secretKey);
11// Convert text to a byte array.
12byte[] dataToBeEncrypted = stringToEncrypt.getBytes();
13// Returns a byte array of encrypted data.
14byte[] encryptedData = session.encrypt(dataToBeEncrypted);
15// Print the encrypted text.
16System.out.pintln("Encrypted text : " + new String(encryptedData);