// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package encrypt;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Random;

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

public class TestSymmetric {
    // generate random IV
    private static Random rng = new SecureRandom();
    private static byte[] genIV(int size) {
        byte[] res = new byte[size];
        rng.nextBytes(res);
        return res;
    }
    // encrypt: byte[] plain + byte[] key -> byte[] cipher
    // decrypt: byte[] cipher + byte[] key -> byte[] plain
    public static byte[] encrypt(String algchainpad, String alg,  int blksize, byte[] plain, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        byte[] iv = genIV(blksize);
        Cipher c = Cipher.getInstance(algchainpad);
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, alg), new IvParameterSpec(iv));
        byte[] temp =  c.doFinal(plain);
        byte[] res = new byte[iv.length + temp.length];
        System.arraycopy(iv, 0, res, 0, iv.length);
        System.arraycopy(temp, 0, res, iv.length, temp.length);
        return res;
    }
    public static byte[] decrypt(String algchainpad, String alg,  int blksize, byte[] cipher, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        byte[] iv = new byte[blksize];
        System.arraycopy(cipher, 0, iv, 0, iv.length);
        byte[] temp = new byte[cipher.length - iv.length];
        System.arraycopy(cipher,  iv.length, temp, 0, temp.length);
        Cipher c = Cipher.getInstance(algchainpad);
        c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, alg), new IvParameterSpec(iv));
        return c.doFinal(temp);
    }
    // Base64 encode: byte[] -> String
    // Base64 decode: String -> byte[]
    private static String encode(byte[] b) {
        return Base64.getEncoder().encodeToString(b);
    }
    private static byte[] decode(String s) {
        return Base64.getDecoder().decode(s);
    }
    // convert String key to byte[] key
    private static byte[] genKey(String key, int keysize) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hash = md.digest(key.getBytes("UTF-8"));
        byte[] res = new byte[keysize];
        System.arraycopy(hash,  0, res,  0, keysize);
        return res;
    }
    // encrypt: String plain + String key -> Base64 String cipher
    // decrypt: Base64 String cipher + String key -> String plain
    public static String encrypt(String algchainpad, String alg, int blksize, String plain, String key, int keysize) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        return encode(encrypt(algchainpad, alg, blksize, plain.getBytes("UTF-8"), genKey(key, keysize)));
    }
    public static String decrypt(String algchainpad, String alg, int blksize, String cipher, String key, int keysize) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        return new String(decrypt(algchainpad, alg, blksize, decode(cipher), genKey(key, keysize)), "UTF-8");
    }
    // test
    private static final String TEXT = "This is some random text to be used to test encryption.";
    private static final String KEY = "This is a very long and super secret key that should really be like 4 times as long as keysize";
    private static void test(String label, String algchainpad, String alg, int keysize, int blksize) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        System.out.println(label + ":");
        System.out.println("  " + TEXT);
        String cipher = encrypt(algchainpad, alg, blksize, TEXT, KEY, keysize);
        System.out.println("  " + cipher);
        String plain = decrypt(algchainpad, alg, blksize, cipher, KEY, keysize);
        System.out.println("  " + plain);
    }
    private static void test2() throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        if(!decrypt("AES/CBC/PKCS5Padding", "AES", 16, "Xc252As4sZuj12tLJtDk2l60tHxu1hk4FTB0l9IK/q96cWd+Uop4lXcId1hGEmm0SN1Xjua4YqVlr3rvT+Mw4hStrnz3h8TEfdENfUMqLMY=", KEY, 16).equals(TEXT)) {
            throw new RuntimeException("Ooops");
        }
    }
    public static void main(String[] args) throws Exception {
        test("AES 128 bit", "AES/CBC/PKCS5Padding", "AES", 16, 16);
        test("AES 192 bit", "AES/CBC/PKCS5Padding", "AES", 24, 16);
        test("AES 256 bit", "AES/CBC/PKCS5Padding", "AES", 32, 16);
        test("3DES 168 bit", "DESede/CBC/PKCS5Padding", "DESede", 24, 8);
        test("Blowfish 256 bit", "Blowfish/CBC/PKCS5Padding", "Blowfish", 32, 8);
        test2();
    }
}
