首頁 > 軟體

Java實現AES演演算法的範例程式碼

2022-02-18 16:00:36

  使用AES演演算法可用於對資料進行加密碼與解密,使用的時候需要注意兩點:1)被加密的串越長,加密後的字串越長,注意資料庫欄位的設計;2)Linux與Windows環境中可能會出現由於環境差異導致在Windows中測試成功,到Linux上後加密的串無法被正確解密。下列演演算法已在真實環境中進行實測,應用時也務必做好二次驗證避免出現線上事故。

 private static final String ALGORITHM_NAME = "AES";
   //加密因子,可根據您的需要自定義
    private static final String DEFAULT_ENCRYPT_RULE = "AES/CBC/PKCS5Padding";
    private static final String RANDOM_KEY_ALGORITHM = "SHA1PRNG";
    private static final String RANDOM_KEY_ALGORITHM_PROVIDER = "SUN";

    /**
     * AES加密
     * @param content 待加密的內容,為空時為回空
     * @return 加密後的base64格式的結果,出現異常時返回null
     */
    public static String encrypt(String content) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_NAME);
            SecureRandom secureRandom = SecureRandom.getInstance(RANDOM_KEY_ALGORITHM, RANDOM_KEY_ALGORITHM_PROVIDER);
            secureRandom.setSeed(DEFAULT_ENCRYPT_RULE.getBytes());
            keyGenerator.init(128, secureRandom);
            SecretKey originalKey = keyGenerator.generateKey();
            SecretKey secretKey = new SecretKeySpec(originalKey.getEncoded(), ALGORITHM_NAME);
            Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
            String result = new String(Base64.getEncoder().encodeToString(encrypted));
            return  result;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
    }
     * 解密
     * @param encrypted 加密後的base64格式的密文
     * @return 解密後的原文,出現異常時返回null
    public static String decrypt(String encrypted) {
        if (StringUtils.isEmpty(encrypted)) {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encrypted));
            return new String(decrypted, "utf-8");

補充:下面看下Java使用AES演演算法的範例程式碼。

Java中使用AES(CBC,128位元)演演算法加解密。一般加密後都是用一定編碼格式進行傳輸,此處使用Base64演演算法進行編解碼。實現及測試程式碼如下:

AESUtil.java

package gj.secure;
 
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;
public class AESUtil {
    private static final String CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS5Padding";
    private static final String KEY_ALGORITHM = "AES";
    public static byte[] initKey() throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        kg.init(128);
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }
    public static byte[] encrypt(byte[] data, byte[] key, byte[] iv) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
        Key k = new SecretKeySpec(key, KEY_ALGORITHM);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, k, paramSpec);
        return cipher.doFinal(data);
    public static byte[] decrypt(byte[] bytes, byte[] key, byte[] iv) throws Exception {
        cipher.init(Cipher.DECRYPT_MODE, k, paramSpec);
        return cipher.doFinal(bytes);
    public static String encodeToBase64String(String data, byte[] key, byte[] iv) throws Exception {
        return Base64.getEncoder().encodeToString(encrypt(data.getBytes(), key, iv));
    public static String decodeFromBase64String(String data, byte[] key, byte[] iv) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(data);
        return new String(decrypt(bytes, key, iv));
}

測試程式碼:

AESUtilTest.java

package gj.secure;
 
/**
 * created by gj on 2019-12-24 17:17
 **/
public class AESUtilTest {
    public static void main(String[] args) throws Exception {
        byte[] key = AESUtil.initKey();
        byte[] iv = {0x01, 0x23, 0x45, 0x67, 0x89 - 0xFF, 0xAB - 0xFF, 0xCD - 0xFF, 0xEF - 0xFF,
                0x01, 0x23, 0x45, 0x67, 0x89 - 0xFF, 0xAB - 0xFF, 0xCD - 0xFF, 0xEF - 0xFF};
        String content = "areful1997";
        String cipher = AESUtil.encodeToBase64String(content, key, iv);
        System.out.println(cipher);
        String plain = AESUtil.decodeFromBase64String(cipher, key, iv);
        System.out.println(plain);
    }
}

到此這篇關於Java實現AES演演算法的文章就介紹到這了,更多相關Java實現AES演演算法內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com