您好,登錄后才能下訂單哦!
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* @version V1.0
* @desc AES 加密工具類
*/
public class AESUtils {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默認的加密算法
private static final String PASSWORD_KEY = "123456";//解密秘鑰
/**
* AES 加密操作
*
* @param content 待加密內容
* @param password 加密密碼
* @return 返回Base64轉碼后的加密數據
*/
public static String encrypt(String content) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 創建密碼器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(PASSWORD_KEY));// 初始化為加密模式的密碼器
byte[] result = cipher.doFinal(byteContent);// 加密
return Base64.encodeBase64String(result);//通過Base64轉碼返回
} catch (Exception ex) {
Logger.getLogger(AESUtils.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* AES 解密操作
*
* @param content
* @param password
* @return
*/
public static String decrypt(String content) {
try {
//實例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//使用密鑰初始化,設置為解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(PASSWORD_KEY));
//執行操作
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, "utf-8");
} catch (Exception ex) {
Logger.getLogger(AESUtils.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* 生成加密秘鑰
*
* @return
*/
private static SecretKeySpec getSecretKey(final String password) {
//返回生成指定算法密鑰生成器的 KeyGenerator 對象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
secureRandom.setSeed(password.getBytes());
//AES 要求密鑰長度為 128
kg.init(128, secureRandom);
//生成一個密鑰
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 轉換為AES專用密鑰
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(AESUtils.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static void main(String[] args) {
String s = "oFWN75fxFHQ";
System.out.println("s:" + s);
String s1 = AESUtils.encrypt(s);
System.out.println("s1:" + s1);
System.out.println("s2:"+AESUtils.decrypt(s1));
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。