// Collection of code snippets by Arne VajhÃ¸j 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class TrippleDES {
    static {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 
    }
    public static String encrypt(String s) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
        Cipher crypt = Cipher.getInstance("DESede/ECB/PKCS7Padding");
        SecretKey key = new SecretKeySpec("MySecretKeyxxxxx".getBytes(), "DESede");
        crypt.init(Cipher.ENCRYPT_MODE, key);
        byte[] plain = s.getBytes("UTF-8");
        byte[] cipher = crypt.doFinal(plain, 0, plain.length);
        return toHex(cipher);
    }
    public static String decrypt(String s) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
        Cipher crypt = Cipher.getInstance("DESede/ECB/PKCS7Padding");
        SecretKey key = new SecretKeySpec("MySecretKeyxxxxx".getBytes(), "DESede");
        crypt.init(Cipher.DECRYPT_MODE, key);
        byte[] cipher = fromHex(s);
        byte[] plain = crypt.doFinal(cipher, 0, cipher.length);
        return new String(plain, "UTF-8");
    }
    private static String toHex(byte[] ba) {
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < ba.length; i++) {
            sb.append(Integer.toHexString((ba[i] >> 4) & 0x0F));
            sb.append(Integer.toHexString(ba[i] & 0x0F));
        }
        return sb.toString();
    }
    private static byte[] fromHex(String s) {
        int n = s.length() / 2;
        byte[] res = new byte[n];
        for(int i = 0; i < n; i++) {
            res[i] = (byte)(Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16));
        }
        return res;
    }
    public static void main(String[] args) throws Exception {
        String p1 = "Dette er en lille test ABC ÆØÅ 123 !!!!";
        System.out.println(p1);
        String c = encrypt(p1);
        System.out.println(c);
        String p2 = decrypt(c);
        System.out.println(p2);
    }
}
