AES加密 前端js后端Java解决方案,加密字节数组

1、参考

前后端AES加解密,java使用CipherOutputStream加密输出时,前端分段解密方案-CSDN博客

使用crypto-js对文件上传下载进行加密处理_cryptojs如何加密文件流-CSDN博客

AES解密报错,Input length must be multiple of 16 when decrypting with padded cipher-CSDN博客

2、html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>AES文件加密 前端js后端Java解决方案</title>
</head>
<h1>AES</h1>
<div>
    <input type="file">
</div>

<body></body>
<script src="../script/jq/jquery-2.1.1.min.js"></script>
<script src="./crypto-js-4.2.0/crypto-js.js"></script>
<script>
    $(function () {
        addEventListener();
    });

    function addEventListener() {
        let input = document.querySelector('input');
        input.addEventListener('change', function (e) {
            let file = e.target.files[0];
            let reader = new FileReader()
            reader.readAsArrayBuffer(file);  //readAsText(file,encoding)
            reader.onload = async (e) => {
                let bytes01 = e.target.result;
                console.log("====bytes01", bytes01);
                let dataStr = encrypt_bytes(bytes01);
                save(dataStr, file);
            }
        })
    }

    function encrypt_bytes(bytes) {
        let keyHex = CryptoJS.enc.Utf8.parse("123456789_123456");
        let bytes02 = CryptoJS.lib.WordArray.create(bytes);
        let encrypted = CryptoJS.AES.encrypt(bytes02, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        console.log("====encrypted", encrypted);
        let dataStr = encrypted.toString();  //base64编码字符串
        console.log("====dataStr", dataStr);
        return dataStr;
    }

    function save(dataStr, file) {
        let blob2 = new Blob([dataStr], { type: file.type });
        // 创建一个URL对象
        let url = URL.createObjectURL(blob2);
        // 创建一个a标签并设置下载属性
        let a = document.createElement("a");
        a.href = url;
        a.download = "hello.txt";
        // 模拟点击a标签来下载文件
        a.click();
        // 释放URL对象
        URL.revokeObjectURL(url);
    }
</script>

</html>

3、java

import cn.hutool.core.io.FileUtil;
import org.jeecg.common.util.encryption.AesUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

public class Test05_Cipher {
    private static String path = "C:\\Users\\xxxxx\\Downloads\\hello (40).txt";
    public static void main(String[] args) throws Exception {
        byte[] bytes01 = FileUtil.readBytes(path);
        byte[] decodedBytes = Base64.getDecoder().decode(bytes01);
        byte[] decrypt = AesUtil.decrypt(decodedBytes);
        String a11 = new String(decrypt, StandardCharsets.UTF_8);
        System.out.println(a11);
    }
}

AesUtil

import org.apache.shiro.codec.Base64;

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

public class AesUtil {
    private static final String secret_key = "123456789_123456";
    private static final String cipher_algorithm = "AES/ECB/PKCS5Padding";

    public static void main(String args[]) throws Exception {
        {
            String a1 = "Cipher在使用时需以参数方式指定transformation";
            byte[] encrypt = encrypt(a1.getBytes(StandardCharsets.UTF_8));
            byte[] decrypt = decrypt(encrypt);
            System.out.printf("===== \n\t%s \n\t%s%n", a1, new String(decrypt));
        }
        {
            String b2 = "transformation的格式为algorithm/mode/padding";
            String encrypt = encryptToBase64(b2);
            String decrypt = decryptByBase64(encrypt);
            System.out.printf("===== \n\t%s \n\t%s%n", b2, decrypt);
        }
    }

    public static String encryptToBase64(String data) {
        try {
            byte[] bytes = encrypt(data.getBytes(StandardCharsets.UTF_8));
            return java.util.Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            return data;
        }
    }

    public static String decryptByBase64(String base64) {
        try {
            byte[] decode_bytes = java.util.Base64.getDecoder().decode(base64);
            byte[] decrypt_bytes = decrypt(decode_bytes);
            return new String(decrypt_bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return base64;
        }
    }

    public static byte[] encrypt(byte[] bytes) throws Exception {
        return doFinal(bytes, Cipher.ENCRYPT_MODE);
    }

    public static byte[] decrypt(byte[] bytes) throws Exception {
        return doFinal(bytes, Cipher.DECRYPT_MODE);
    }

    public static byte[] doFinal(byte[] bytes, int decryptMode) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(secret_key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(decryptMode, secretKey);
        return cipher.doFinal(bytes);
    }
}
posted @ 2024-05-08 09:31  一只桔子2233  阅读(27)  评论(0编辑  收藏  举报