Java和javascript中使用AES加密

案例代码

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
 * @author sovereign君
 * @date 2024/3/30
 * @ClassName AESExample
 */
public class AESExample {
    public static void main(String[] args) throws Exception {
        // 初始化密钥和IV(初始化向量)
        String key = "0123456789ABCDEF";  // 16字节密钥
        String initVector = "ABCDEF9876543210"; // 16字节IV

        // 要加密的字符串
        String originalString = "sovereign";

        System.out.println("原始字符串: " + originalString);

        // 加密
        String encryptedString = encrypt(key, initVector, originalString);
        System.out.println("加密后的字符串: " + encryptedString);
        
        // 解密
        String decryptedString = decrypt(key, initVector, encryptedString);
        System.out.println("解密后的字符串: " + decryptedString);
    }

    public static String encrypt(String key, String initVector, String value) throws Exception {
        //1 表示加密 2 是解密
        Cipher cipher = getCipher(1,key, initVector);
        byte[] encrypted = cipher.doFinal(value.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }
    public static String decrypt(String key, String initVector, String encrypted) throws Exception {
        Cipher cipher = getCipher(2,key, initVector);
        byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));
        return new String(original);
    }
    //创建密码器
    public static Cipher getCipher(int enOrdecrypt,String key,String initVector) throws Exception{
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8));
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher instance = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        instance.init(enOrdecrypt,secretKeySpec,ivParameterSpec);
        return instance;
    }
}

前端javascript需要使用 crypto-js ,所以我在vue项目中使用,安装依赖

npm install crypto-js

直接在项目根目录创建一个test.js文件

案例代码

const crypto =require('crypto-js');

const secret='0123456789ABCDEF'
const initVector='ABCDEF9876543210'
const message='jun'
const encrypted='PpdK6OoS0E7iQnM0AliUKA=='

// 将密钥和初始化向量从字符串转换为字节
const keyBytes = crypto.enc.Utf8.parse(secret);
const initVectorBytes = crypto.enc.Utf8.parse(initVector);

const encrypt=crypto.AES.encrypt(message,keyBytes,{iv:initVectorBytes,mode:crypto.mode.CBC}).toString()
console.log(encrypt)
const decrypt=crypto.AES.decrypt(encrypted,keyBytes,{iv:initVectorBytes,mode:crypto.mode.CBC,padding: crypto.pad.Pkcs7,}).toString(crypto.enc.Utf8)
console.log(decrypt)

 这样Java和javascript加密的数据两个语言都能互相加密

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值