Menu Search Sign up

Java JCA & JCE

Sun JCA & its reference implementation JCE has a number of Cryptographic Engines. Here are a few use cases and code examples:

Computing a MessageDigest Object

Generating a Pair of Keys

Generating and Verifying a Signature Using Generated Keys

Determining If Two Keys Are Equal

Reading Base64-Encoded Certificates

Using Encryption

Using Password-Based Encryption


For an extensive description of JCA, refer to

Encryption/Decryption and Base64 Example

Note that for Base64, if you are using java 1.8, it is already included (java.util.Base64); if you are using java 1.6 or 1.7, you can use the apache codec package as below.

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
//download commons-codec-1.10.jar from
import org.apache.commons.codec.binary.Base64;

    static String encryptIt (String text, boolean mode) throws Exception{
        if (mode==true) {
            byte[] encryptedBytes =  encryptIt(text.getBytes(), mode);
            return Base64.encodeBase64String(encryptedBytes);
        else {
            byte[] encryptedBytes = Base64.decodeBase64(text);
            byte[] decryptedBytes = encryptIt(encryptedBytes, mode);
            return new String(decryptedBytes);

    static byte[] encryptIt (byte[] text, boolean mode) throws Exception{
        PBEKeySpec pbeKeySpec;
        PBEParameterSpec pbeParamSpec;
        SecretKeyFactory keyFac;
        pbeKeySpec = new PBEKeySpec(key);
          keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        // Iteration count
        int count = 20;

        // Create PBE parameter set
        pbeParamSpec = new PBEParameterSpec(salt, count);
        // Initialize PBE Cipher with key and parameters
        if (mode==true)
            pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);   
            pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
        return pbeCipher.doFinal(text);

    static char[] key;
    static byte[] salt = {
            (byte)0xd7, (byte)0x73, (byte)0x22, (byte)0x5c,
            (byte)0x6e, (byte)0xc2, (byte)0xee, (byte)0x89