使用java,实现最简单的AES加密解密

话不多说,直接上代码:

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

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

public class Test {

    public static final String CHARSET_NAME = "utf-8";
    public static final String PADDING = "AES/ECB/PKCS5Padding";
    public static final String AES = "AES";

    // 加密
    public static String encrypt(String content, String password) throws Exception {
        byte[] raw = password.getBytes(CHARSET_NAME);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(PADDING);//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(content.getBytes(CHARSET_NAME));
        return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
    }

    // 解密
    public static String decrypt(String content, String password) throws Exception {
        byte[] raw = password.getBytes(CHARSET_NAME);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(PADDING);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] encrypted1 = new BASE64Decoder().decodeBuffer(content);//先用base64解密
        byte[] original = cipher.doFinal(encrypted1);
        return new String(original, CHARSET_NAME);
    }

    public static void main(String[] args) throws Exception {
        String password = "12bde4db586449a5";//必须是16位密钥
        System.out.println(encrypt("123", password));
        System.out.println(decrypt(encrypt("123", password), password));
    }
}