加密 解密网站:
Online AES Encryption and Decryption Tool
Select Mode:ECB
Enter Secret Key -:6547897657895678
package com.ais.util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AESEncryptpaddingUtil {
/**
* Logger for this class
*/
private static Logger logger = LoggerFactory.getLogger(AESEncryptpaddingUtil.class);
/*******************************************************************
* AES加密算法
* @author moyun
* 加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定 此处使用AES-128-CBC加密模式,key需要为16位。
* */
//加密
public static String encrypt(String sSrc, String sKey, String IV) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return Base64.encodeBase64String(encrypted);//此处使用BAES64做转码功能,同时能起到2次
}
public static String encrypt(String sSrc, String sKey) throws Exception {
return encrypt(sSrc, sKey, sKey);
}
//解密
public static String decrypt(String sSrc, String sKey, String IV) throws Exception {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = Base64.decodeBase64(sSrc);//先用bAES64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
logger.info(e.toString());
return null;
}
}
public static String decrypt(String sSrc, String sKey) throws Exception {
// if iv is null use sKey as iv
return decrypt(sSrc, sKey, sKey);
}
public static void main(String[] args) throws Exception {
String pwd = "SFAR23004";
String epwd = encrypt(pwd, "6547897657895678");
System.out.println(epwd);
System.out.println(decrypt(epwd, "6547897657895678"));
System.out.println(decrypt("FaTr1tzrmEbfFUJwEATs1g==", "dvyYRQlnPRCMdQSedvyYRQlnPRCMdQSe"));
}
}