AES对称加密算法

package cn.jsonlu.passguard.utils;


import org.apache.commons.codec.binary.Base64;

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

/**
 * @author JsonLu
 * @email jsonlu@qq.com
 * @since 2016/1/5 17:34
 */
public class AESUtil {

    /**
     * 密钥
     */
    public static final String KEY = "0123456789012345";

    /**
     * @param input
     * @param key
     * @return
     */
    public static String encrypt(String input, String key) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return new String(Base64.encodeBase64(crypted));
    }

    /**
     * @param input
     * @param key
     * @return
     */
    public static String decrypt(String input, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.decodeBase64(input));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return new String(output);
    }

    public static void main(String[] args) {
        String key = "1234567891234567";
        String data = "i_love_coder";
        System.out.println(AESUtil.decrypt(AESUtil.encrypt(data, key), key));
        System.out.println(AESUtil.encrypt(data, key));
    }
}

 

posted @ 2016-02-24 09:47  JsonLu  阅读(439)  评论(0编辑  收藏  举报