Java
Chilkat2 Java
Encrypt / Decrypt Secure Strings
See more Encryption Examples
Demonstrates how to use the EncryptSecureENC and DecryptSecureENC methods to encrypt/decrypt secure strings. These methods were added in Chilkat v9.5.0.71 (released January 2018).Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.SecureString;
public class ChilkatExample {
public static void main(String[] args) {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load the secure string with some text.
SecureString secStr1 = new SecureString();
try {
secStr1.loadFile("qa_data/txt/helloWorld.txt", "utf-8");
} catch (ChilkatException e) {
System.out.println("Failed to load helloWorld.txt");
return;
}
Crypt2 crypt = new Crypt2();
crypt.setCryptAlgorithm("aes");
crypt.setCipherMode("cbc");
crypt.setKeyLength(128);
crypt.setEncodedKey("000102030405060708090A0B0C0D0E0F", "hex");
crypt.setEncodedIV("000102030405060708090A0B0C0D0E0F", "hex");
crypt.setEncodingMode("base64");
// Return the base64 encoded encrypted contents of secStr1.
String encryptedStr = crypt.encryptSecureENC(secStr1);
System.out.println("Encrypted string: " + encryptedStr);
// Output:
// Encrypted string: qiq+IFhcjTkEIkZyf31V/g==
// Decrypt to secStr2:
SecureString secStr2 = new SecureString();
crypt.decryptSecureENC(encryptedStr, secStr2);
// Access the contents of secStr2
System.out.println("Decrypted string: " + secStr2.access());
// Output:
// Decrypted string: Hello World!
}
}