TripleDES Encrypter Class In Java

I forgot where I got this class from because I lost the URL source but I do remember it was from someone’s blog that also posted the same class, just a C# version to have it work with the Java class.

If anyone knows, do leave a comment so I can update the post and mention the one who made this class.

This class contains both methods to encrypt and decrypt using Triple DES.

public class TripleDESEncrypter {
 
    private String key;
    private String initializationVector;
 
    public TripleDESEncrypter(String key, String initializationVector) {
        this.key = key; // 24 ascii character
        this.initializationVector = initializationVector;   // 8 ascii character
    }
 
    public String encryptText(String plainText) throws Exception {
        //---- Use specified 3DES key and IV from other source --------------
        byte[] plaintext = plainText.getBytes();
        byte[] tdesKeyData = key.getBytes();
 
        // byte[] myIV = initializationVector.getBytes();
 
        Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
        IvParameterSpec ivspec = new IvParameterSpec(initializationVector.getBytes());
 
        c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
        byte[] cipherText = c3des.doFinal(plaintext);
 
        return new sun.misc.BASE64Encoder().encode(cipherText);
    }
 
    public String decryptText(String cipherText)throws Exception{
        byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(cipherText);
        Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        byte[] tdesKeyData = key.getBytes();
        SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
        IvParameterSpec ivspec = new IvParameterSpec(initializationVector.getBytes());
        decipher.init(Cipher.DECRYPT_MODE, myKey, ivspec);
        byte[] plainText = decipher.doFinal(encData);
        return new String(plainText);
    }    
 
}

Here is a sample code on how to use the class.

TripleDESEncrypter triple = new TripleDESEncrypter("string key value", "init vector string value");
System.out.println("encrypted = [" + triple.encryptText("key") + "]");
System.out.println("decrypted = [" + triple.decryptText(triple.encryptText("key")) + "]");
Related Posts Plugin for WordPress, Blogger...