1. 程式人生 > 實用技巧 >AES加解密程式碼

AES加解密程式碼

package com.albedo.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AES 加密
 */
public class AESUtils {
    //字元編碼
    public
static final String CHARSET_UTF8 = "UTF-8"; //加密演算法DES public static final String AES = "AES"; /** * 生成key * * @param password * @return * @throws Exception */ private static Key generateKey(String password) throws Exception { // 建立AES的Key生產者 KeyGenerator kgen = KeyGenerator.getInstance(AES);
//由於SecureRandom在不同作業系統底層生成機制不同,所以,為統一化,使用seed方法, // 這樣能保證每次相同的password能夠生成相同的隨機數 SecureRandom random=SecureRandom.getInstance("SHA1PRNG"); random.setSeed(password.getBytes(CHARSET_UTF8)); // 利用使用者密碼作為隨機數初始化出 kgen.init(128, random); // 根據使用者密碼,生成一個金鑰 SecretKey secretKey = kgen.generateKey();
// 返回基本編碼格式的金鑰,如果此金鑰不支援編碼,則返回 byte[] enCodeFormat = secretKey.getEncoded(); // 轉換為AES專用金鑰 return new SecretKeySpec(enCodeFormat, AES); } /** * AES加密字串 * * @param content 需要被加密的字串 * @param password 加密需要的密碼 * @return 密文 */ public static String encrypt(String content, String password) throws Exception { // 建立密碼器 Cipher cipher = Cipher.getInstance(AES); byte[] byteContent = content.getBytes(CHARSET_UTF8); Key key = generateKey(password); // 初始化為加密模式的密碼器 cipher.init(Cipher.ENCRYPT_MODE, key); // 加密 byte[] result = cipher.doFinal(byteContent); return new String(Base64.getEncoder().encode(result)); } /** * 解密AES加密過的字串 * * @param content AES加密過過的內容 * @param password 加密時的密碼 * @return 明文 */ public static String decrypt(String content, String password) throws Exception { Key key = generateKey(password); Cipher cipher = Cipher.getInstance(AES); cipher.init(Cipher.DECRYPT_MODE, key); return new String(cipher.doFinal(Base64.getDecoder().decode(content.getBytes(CHARSET_UTF8))), CHARSET_UTF8); } }