Node Java相互使用AES-128-GCM对数据进行加密解密实现

在这里插入图片描述

Node代码

let crypto = require('crypto');

//偏移量 16位
const iv = "0123456789ABCDEF";
//密钥
const key = "0123456789ABCDEF";


//加密
function encodeAes(word) {
    if (!word) {
        return ''
    }
    if (typeof word != 'string') {
        word = JSON.stringify(word)
    }

    const md5 = crypto.createHash('md5');
    const result = md5.update(key).digest();
    const cipher = crypto.createCipheriv('aes-128-gcm', result, iv);
    const encrypted = cipher.update(word, 'utf8');
    const finalstr = cipher.final();
    const tag = cipher.getAuthTag();
    const res = Buffer.concat([encrypted, finalstr, tag]);
    return res.toString('base64');
}

//解密
function decodeAes(word) {
    if (!word) {
        return ''
    }
    const md5 = crypto.createHash('md5');
    const result = md5.update(key).digest();
    const decipher = crypto.createDecipheriv('aes-128-gcm', result, iv);
    const b = Buffer.from(word, 'base64')
    decipher.setAuthTag(b.subarray(b.length - 16));
    const str = decipher.update(Buffer.from(b.subarray(0, b.length - 16), 'hex'));
    const fin = decipher.final();
    const decryptedStr = new TextDecoder('utf8').decode(Buffer.concat([str, fin]))
    try {
        return JSON.parse(decryptedStr);
    } catch (e) {
        return decryptedStr
    }
}


let encodeStr = encodeAes('hello word');
console.log('加密后:' + encodeStr);
let decodeStr = decodeAes(encodeStr);
console.log('解密后:' + decodeStr);

Java代码

import java.security.MessageDigest;

import java.security.Security;

import java.util.Base64;

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * @Description 
 * @Date 13:43 2020/12/8
 **/
public class AesGcmUtil {

    
    /**
     * @Description  16位的密钥
     * @Date 13:43 2020/12/8
     **/
    public static final String KEY = "0123456789ABCDEF";

    private static final String IV = "0123456789ABCDEF";

    private static final String ALGORITHMSTR = "AES/GCM/NoPadding";

    private static final String DEFAULT_CODING = "utf-8";

    /**
     * 如果报错java.security.NoSuchProviderException: no such provider: BC,那么需要加上这一段,同时需要bcprov-jdk15on.jar
     */
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * @Description 加密
     * @Date 14:25 2020/12/7
     **/
    public static String aesEncrypt(String content) throws Exception {
        byte[] input = content.getBytes(DEFAULT_CODING);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(KEY.getBytes(DEFAULT_CODING));
        SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
        IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes(DEFAULT_CODING));
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, skc, ivspec);
        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
        int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
        ctLength += cipher.doFinal(cipherText, ctLength);
        return Base64.getEncoder().encodeToString(cipherText);
    }


    /**
     * @Description 解密
     * @Date 14:26 2020/12/7
     **/
    public static String aesDecrypt(String tmp) throws Exception {
        byte[] keyb = KEY.getBytes(DEFAULT_CODING);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(keyb);
        SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
        IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes(DEFAULT_CODING));
        Cipher dcipher = Cipher.getInstance(ALGORITHMSTR, "BC");
        dcipher.init(Cipher.DECRYPT_MODE, skey, ivspec);
        byte[] clearbyte = dcipher.doFinal(Base64.getDecoder().decode(tmp));
        return new String(clearbyte, DEFAULT_CODING);
    }

    public static void main(String[] args) throws Exception {
        String origin = "这是Java端的加密解密";
        String encryptstr = aesEncrypt(origin);
        System.out.println(encryptstr);
        String decryptstr = aesDecrypt(encryptstr);
        System.out.println(decryptstr);

    }


}

就 先 说 到 这 \color{#008B8B}{ 就先说到这}
在 下 A p o l l o \color{#008B8B}{在下Apollo} Apollo
一 个 爱 分 享 J a v a 、 生 活 的 小 人 物 , \color{#008B8B}{一个爱分享Java、生活的小人物,} Java
咱 们 来 日 方 长 , 有 缘 江 湖 再 见 , 告 辞 ! \color{#008B8B}{咱们来日方长,有缘江湖再见,告辞!}

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
好的,这个问题涉及到JS和Java加密解密实现,我会尽力回答。首先,AES-GCM是一种高级加密标准(Advanced Encryption Standard)的加密模式,它是一种块加密模式,可以提供加密和认证功能。而PKCS5Padding是一种填充模式,它可以把不满足块大小的数据填充到块大小,以满足加密算法的要求。 在Node.js中,可以使用node-forge库提供的API实现AES-GCM加密,示例代码如下: ```javascript const forge = require('node-forge'); // 加密 function encrypt(plaintext, key, iv) { const cipher = forge.cipher.createCipher('AES-GCM', key); cipher.start({ iv: iv }); cipher.update(forge.util.createBuffer(plaintext)); cipher.finish(); return { ciphertext: cipher.output.toHex(), tag: cipher.mode.tag.toHex() }; } const plaintext = 'Hello, world!'; const key = forge.random.getBytesSync(32); const iv = forge.random.getBytesSync(12); const encrypted = encrypt(plaintext, key, iv); console.log(encrypted); ``` 在Java中,可以使用javax.crypto库提供的API实现AES/GCM/PKCS5Padding解密,示例代码如下: ```java import javax.crypto.Cipher; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Decryptor { public static String decrypt(String ciphertext, String key, String iv, String tag) throws Exception { byte[] ct = hexStringToByteArray(ciphertext); byte[] k = hexStringToByteArray(key); byte[] i = hexStringToByteArray(iv); byte[] t = hexStringToByteArray(tag); Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(k, "AES"); GCMParameterSpec gcmSpec = new GCMParameterSpec(t.length * 8, i); cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec); cipher.update(ct); cipher.updateAAD(t); byte[] pt = cipher.doFinal(); return new String(pt); } private static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } } ``` 以上代码仅供参考,具体实现需要根据实际情况进行调整。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值