AES密码加密
AESUtil
public class AESUtil {
// 密钥
public static String key = "8888888888888888";
private static String charset = "utf-8";
// 偏移量
private static int offset = 16;
private static String transformation = "AES/CBC/NoPadding";
private static String algorithm = "AES";
public static void main(String[] args) {
String s = "123456";
String encrypt = encrypt(s);
System.out.println(encrypt);
String decrypt = decrypt(encrypt);
System.out.println(decrypt);
}
/**
* 加密
* @param content
* @return
*/
public static String encrypt(String content) {
try {
return encrypt(content, key);
} catch (Exception e) {
}
return null;
}
/**
* 解密
* @param content
* @return
*/
public static String decrypt(String content) {
return decrypt(content, key);
}
public static String encrypt(String data, String key) throws Exception {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(key.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
String encode = new Base64().encodeToString(encrypted);
String dest = "";
if (encode!=null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(encode);
dest = m.replaceAll("");
}
return dest;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* AES(256)解密
* @param content 解密内容
* @param key 密钥
* @return
*/
public static String decrypt(String content, String key) {
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), algorithm);
IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset);
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, skey, iv);
byte[] result = cipher.doFinal(new Base64().decode(content));
return new String(result);
} catch (Exception e) {
}
return null;
}