/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.kneet.v3.common.security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public final class AesUtil {

    /**
     * hex to byte[] : 16진수 문자?�을 바이??배열�?�?��?�다.
     *
     * @param hex hex string
     * @return
     */
    public byte[] hexToByteArray(String hex) {
        if ( hex == null || hex.length() == 0 ) {
            return null;
        }

        byte[] ba = new byte[hex.length() / 2];
        for ( int i = 0; i < ba.length; i++ ) {
            ba[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
        return ba;
    }

    /**
     * byte[] to hex : unsigned byte(바이?? 배열??16진수 문자?�로 바꾼??
     *
     * @param ba byte[]
     * @return
     */
    public String byteArrayToHex(byte[] ba) {
        if ( ba == null || ba.length == 0 ) {
            return null;
        }

        StringBuffer sb = new StringBuffer(ba.length * 2);
        String hexNumber;
        for ( int x = 0; x < ba.length; x++ ) {
            hexNumber = "0" + Integer.toHexString(0xff & ba[x]);

            sb.append(hexNumber.substring(hexNumber.length() - 2));
        }
        return sb.toString();
    }

    /**
     * AES 방식???�호??
     *
     * @param message
     * @return
     * @throws Exception
     */
    public String encrypt(String message, String key) throws Exception {
        // KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // kgen.init(128);
        // use key coss2
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");

        // Instantiate the cipher
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        byte[] encrypted = cipher.doFinal(message.getBytes());
        return byteArrayToHex(encrypted);
    }

    /**
     * AES 방식??복호??
     *
     * @param message
     * @return
     * @throws Exception
     */
    public String decrypt(String encrypted, String key) throws Exception {
        // KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // kgen.init(128);
        // use key coss2
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] original = cipher.doFinal(hexToByteArray(encrypted));
        String originalString = new String(original);
        return originalString;
    }

    public void main(String[] args) throws Exception {
        String key = "0987654321098765";
        String token = encrypt("apple", key);
        System.out.println(token);
        String ret = decrypt(token, key);
        System.out.println(ret);
    }
}
