Java AES 加密工具类

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtil {
    private static final String ALGORITHM = 'AES';
    private static final String TRANSFORMATION = 'AES/ECB/PKCS5Padding';
    
    public static String encrypt(String plaintext, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    
    public static String decrypt(String ciphertext, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(ciphertext);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}

Vue AES 解密工具类

import CryptoJS from 'crypto-js';

function decrypt(ciphertext, key) {
    let decrypted = CryptoJS.AES.decrypt(ciphertext, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
}

export default {
    decrypt
}

使用说明

  1. Java 加密: 使用 AESUtil.encrypt(plaintext, key) 方法进行加密,其中 plaintext 为明文,key 为加密密钥。
  2. Vue 解密: 使用 decrypt(ciphertext, key) 方法进行解密,其中 ciphertext 为密文,key 为加密密钥。
  3. 密钥一致性: Java 和 Vue 使用的加密密钥必须一致。

代码解析

  • Java 代码使用 javax.crypto 包实现 AES 加密解密,采用 ECB 模式和 PKCS5Padding 填充方式。
  • Vue 代码使用 crypto-js 库实现 AES 解密,同样采用 ECB 模式和 Pkcs7 填充方式。

注意

  • 本示例仅供参考,实际应用中应根据具体需求选择合适的加密算法、模式和填充方式。
  • 密钥应妥善保管,避免泄露。
  • 建议使用更安全的加密模式,例如 GCM 模式。
  • 加密后的密文应进行 Base64 编码,方便传输和存储。
Java & Vue AES 加密解密工具类实现详解

原文地址: https://www.cveoy.top/t/topic/mU0u 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录