JS加解密和后台互通

13 篇文章 0 订阅
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>稻壳阅读器</title>
    <script type="text/javascript" src="${res!}/jquery/jquery-2.2.3.min.js"></script>
    <script type="text/javascript" src="${res!}/aes/aes.js"></script>
    <script type="text/javascript" src="${res!}/aes/pad-zeropadding.js"></script>
    <script>
        /*$(function () {
            var data = $("#data").val();
            var key = CryptoJS.enc.Latin1.parse('abcdef0123456789');
            var iv = CryptoJS.enc.Latin1.parse('0123456789abcdef');

            //加密
            var encrypted = CryptoJS.AES.encrypt(data, key, {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.ZeroPadding
            });
            $("#encrypt").val(encrypted.toString());
            console.log(encrypted.toString())
            //解密
            var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv, padding: CryptoJS.pad.ZeroPadding});
            console.log(decrypted.toString(CryptoJS.enc.Utf8));
            $("#p2").text("解密结果:"+decrypted.toString(CryptoJS.enc.Utf8));
        })*/
        var key = CryptoJS.enc.Latin1.parse('abcdef0123456789');
        var iv = CryptoJS.enc.Latin1.parse('0123456789abcdef');
        function encryptData(){
            var data = $("#data").val();
            var encrypted = CryptoJS.AES.encrypt(data, key, {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.ZeroPadding
            });
            console.log("加密结果:" + encrypted.toString());
            $("#encrypt").val(encrypted);
        }
        function decryptData(){
            var encrypted = $("#encrypt").val();
            var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv, padding: CryptoJS.pad.ZeroPadding});
            console.log("解密结果:" + decrypted.toString(CryptoJS.enc.Utf8));
            $("#decrypt").val(decrypted.toString(CryptoJS.enc.Utf8));
        }
    </script>
</head>
<body class="layui-layout-body" style="background-color: #f2f2f2">
<div class="layui-row">
    <div class="layui-col-md12">
        <input style="width: 500px;" type="text" id="data" value="doc阅读加密"/>
        <button class="layui-btn">测试数据</button>
    </div>
</div>
<div class="layui-row">
    <div class="layui-col-md12">
        <input style="width: 500px;" type="text" id="encrypt" value=""/>
        <button class="layui-btn" onclick="encryptData()">加密数据</button>
    </div>
</div>
<div class="layui-row">
    <div class="layui-col-md5">
        <input style="width: 500px;" type="text" id="decrypt" value=""/>
        <button class="layui-btn" onclick="decryptData()">解密数据</button>
    </div>
</div>
<div class="layui-row">
    <div class="layui-col-md5">
        <input style="width: 500px;" type="text" id="upload" value=""/>
        <button class="layui-btn" onclick="updateEncryptData()">上传加密数据</button>
    </div>
</div>
</body>
</html>

Java语言实现

public class AESTest {

    //static String data = "123456RWEQR";
    static String key = "abcdef0123456789";  //16位
    static String iv = "0123456789abcdef";  //16位

    public static void main(String args[]) throws Exception {
       System.out.println(encryptAES("123456"));
        System.out.println(decryptAES(encryptAES("123456")));
    }

    public static String encryptAES(String data) throws Exception {

        try {

            Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding");   //参数分别代表 算法名称/加密模式/数据填充方式
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);

            return new sun.misc.BASE64Encoder().encode(encrypted);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String decryptAES(String data) throws Exception {
        try {
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);

            Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

 

AES三中数据填充方式

PKCS7Padding
Java不支持此方式
PKCS7Padding是缺几个字节就补几个字节的0

PKCS5Padding
JS不支持此方式
PKCS5Padding是缺几个字节就补充几个字节的几,例如缺8个字节,就补充8个字节的8

NOPadding
不补充字节

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript 可以使用多种加解密算法,以下是一些常用的方法: 1. Base64 编码/解码 Base64 是一种将二进制数据编码为 ASCII 字符的方法,通常用于在网络上传输数据。JavaScript 中可以使用 `btoa()` 方法进行编码,使用 `atob()` 方法进行解码。 示例: ```javascript const str = 'Hello World!'; const encodedStr = btoa(str); // 编码为 "SGVsbG8gV29ybGQh" const decodedStr = atob(encodedStr); // 解码为 "Hello World!" ``` 2. MD5 加密 MD5 是一种常见的哈希算法,可以将任意长度的数据转换为固定长度的摘要。JavaScript 中可以使用第三方库(如 crypto-js)进行 MD5 加密。 示例: ```javascript const CryptoJS = require('crypto-js'); const str = 'Hello World!'; const hash = CryptoJS.MD5(str).toString(); // 加密为 "b10a8db164e0754105b7a99be72e3fe5" ``` 3. AES 加密/解密 AES 是一种常见的对称加密算法,可以使用同一个密钥进行加密和解密。JavaScript 中可以使用第三方库(如 crypto-js)进行 AES 加密和解密。 示例: ```javascript const CryptoJS = require('crypto-js'); const key = CryptoJS.enc.Utf8.parse('1234567890123456'); // 密钥需为 16、24 或 32 个字符 const plaintext = 'Hello World!'; const ciphertext = CryptoJS.AES.encrypt(plaintext, key, { iv: key, // 初始向量需为密钥相同的值 }).toString(); // 加密为 "U2FsdGVkX19oY3FAdlO5JwT5ys7YBz/64j9K9t9g8Ls=" const decryptedText = CryptoJS.AES.decrypt(ciphertext, key, { iv: key, }).toString(CryptoJS.enc.Utf8); // 解密为 "Hello World!" ``` 注意:以上示例仅供参考,请勿将加解密算法用于安全性要求较高的场景,以免造成安全问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值