Java 的 AES 加密工具类:

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class AESUtil {

    private static final String ALGORITHM = 'AES';
    private static final int KEY_SIZE = 128;

    public static String encrypt(String content, String password) {
        try {
            Key key = generateKey(password);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encrypted = cipher.doFinal(content.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String decrypt(String content, String password) {
        try {
            Key key = generateKey(password);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decrypted = cipher.doFinal(Base64.decodeBase64(content));
            return new String(decrypted);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static Key generateKey(String password) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom secureRandom = new SecureRandom(password.getBytes());
        keyGenerator.init(KEY_SIZE, secureRandom);
        return new SecretKeySpec(keyGenerator.generateKey().getEncoded(), ALGORITHM);
    }

}

Vue 的 AES 解密工具类:

import CryptoJS from 'crypto-js'

export default {
  decrypt (content, password) {
    try {
      const key = CryptoJS.enc.Utf8.parse(password)
      const decrypted = CryptoJS.AES.decrypt(content, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
      return decrypted.toString(CryptoJS.enc.Utf8)
    } catch (e) {
      throw new Error(e)
    }
  }
}

使用说明:

  1. Java 加密: 使用 AESUtil.encrypt(content, password) 方法进行加密,其中 content 是要加密的字符串,password 是加密密钥。
  2. Vue 解密: 使用 decrypt(content, password) 方法进行解密,其中 content 是加密后的字符串,password 是加密密钥。
  3. 注意: 加密和解密的密钥必须保持一致。

其他说明:

  • 代码中使用了 Base64 编码对加密后的数据进行编码,方便传输和存储。
  • Vue 的代码中使用了 crypto-js 库进行 AES 解密。
  • 代码中使用 ECB 模式和 Pkcs7 填充。

示例:

// Java 加密
String encrypted = AESUtil.encrypt('Hello world', 'mysecretkey');

// Vue 解密
const decrypted = decrypt(encrypted, 'mysecretkey');

console.log(decrypted); // 输出 'Hello world'

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

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