安装crypto-js

npm install crypto-js

微信小程序直接导入

const CryptoJS = require('../../common/crypto-js/crypto-js'); //引用AES源码js

封装

import CryptoJS from "crypto-js";

//32位密钥
const keyStr = '16aef158550545688ae8ab0835aeb5dd';

//如果是16位密钥则不需要下列操作
let key = CryptoJS.SHA1(CryptoJS.SHA1(keyStr)).toString().substring(0, 32);
let realKey = CryptoJS.enc.Hex.parse(key);

//偏移量 没啥用 不太懂
const IV = '';

let tools = {
     //加密
       encrypt(word) {
         let encrypted = CryptoJS.AES.encrypt(word, realKey, {
           mode: CryptoJS.mode.ECB,
           padding: CryptoJS.pad.Pkcs7
         });
         
         // 如果加密后的密文,需要16进制返回的,使用 
                 //return encrypted.ciphertext.toString()
         // 如果加密后的密文,使用的是base64格式的, 使用直接使用 
                  //return encrypted.toString()
                  
         return encrypted.ciphertext.toString();
       },
       //解密
       decrypt(word) {
           
        // 将16进制 转换为Base64字符串
        var contentHexStr = CryptoJS.enc.Hex.parse(word);
        var srcs = CryptoJS.enc.Base64.stringify(contentHexStr);
        
        let decrypt = CryptoJS.AES.decrypt(srcs, realKey, {
           mode: CryptoJS.mode.ECB,
           padding: CryptoJS.pad.Pkcs7
         });
         return CryptoJS.enc.Utf8.stringify(decrypt).toString();
       }

};

export default tools;

调用

import tools from '../../common/js/utils/crypto-js';

let a = tools.encrypt("{\"fLoyaltyId\":\"7004900004135957810\",\"signType\":\"0\"}");
let b = tools.decrypt(a);

后端工具类

package com.lf.gas_platform.common.utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


/*
 * AES对称加密和解密
 */
public class AESUtil {
    public static byte[] encrypt(String content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance( "AES" );
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
            secureRandom.setSeed(password.getBytes());
            kgen.init(128,secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(byteContent);
            return result;

        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密AES加密过的字符串
     *
     * @param content
     *            AES加密过过的内容
     * @param password
     *            加密时的密码
     * @return 明文
     */
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance( "AES" );
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
            secureRandom.setSeed(password.getBytes());
            kgen.init(128,secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**将16进制转换为二进制
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    public static String AesEncryption(String data, String password){
        byte[] shellEncrypt = encrypt(data, password);
        return parseByte2HexStr(shellEncrypt);
    }
    public static String AesDecrypt(String data, String password){
        byte[] twoStrResult = parseHexStr2Byte(data);
        byte[] decrypt = decrypt(twoStrResult, password);
        return new String(decrypt);
    }


    public static void main(String[] args) throws Exception {
        String password = "26c7fa1b46babbda88d3b977de122c1c";
        String content = "123";

        System.out.println("加密之前:" + content);
        // 加密
        byte[] encrypt = encrypt(content, password);
        System.out.println("加密后的内容:" + new String(encrypt,"UTF-8"));

        String hexStrResult = parseByte2HexStr(encrypt);
        System.out.println("16进制的密文:"  + hexStrResult);
        // 解密data=
//        String hexStrResult="B4631447A3358131A0B8AC229CA30E874BBC75B0C5CB51E363AFCB9489BC6A89E3AD4581F0B446CFD91AC253494452F55AD6D64E3C33E5C7456347B3D50C98059ED33DFF17E12DD4F6CA3F8443550A8E29942656A4046D5F7B0D4AFE66BA1E18C240DDB57683741C21152AD93164D70AA4DF1E34F5A83E4A0A1D1164EF6315E800306811BA2B0F170E2A953347A2C0DD1D9C7074CA6B4B08F1C5C0F956711685BF073C3ADCEB2301DF4D27CD74FB8C24FBCF451057BB1666DC620B7A83B366A0130A84205C63C8EC0963BCBCAD0B1D6F";
//        String password = "27c8fa1a46baabda88d2b977de272c1f";
        byte[] twoStrResult = parseHexStr2Byte(hexStrResult);
        byte[] decrypt = decrypt(twoStrResult, password);
        System.out.println("解密后的内容:" + new String(decrypt));

    }


}

这个是RSA加密跟上面的AES没关系,密钥长度过长可能需要 修改加密的源码 下面是已经修改好的

<template>
	<view>

	</view>
</template>

<script>
	import JSEncrypt from './jsencrypt.min.js';
	export default {
		data() {
			return {

			}
		},
		methods: {

		},
		encryptUnicodeLong: function(publicKey, string) {
			const encrypt = new JSEncrypt();
			encrypt.setPublicKey(publicKey);
			var k = encrypt.getKey();
			//根据key所能编码的最大长度来定分段长度。key size - 11:11字节随机padding使每次加密结果都不同。
			var maxLength = ((k.n.bitLength() + 7) >> 3) - 11;
			try {
				var subStr = "",
					encryptedString = "";
				var subStart = 0,
					subEnd = 0;
				var bitLen = 0,
					tmpPoint = 0;
				for (var i = 0, len = string.length; i < len; i++) {
					//js 是使用 Unicode 编码的,每个字符所占用的字节数不同
					var charCode = string.charCodeAt(i);
					if (charCode <= 0x007f) {
						bitLen += 1;
					} else if (charCode <= 0x07ff) {
						bitLen += 2;
					} else if (charCode <= 0xffff) {
						bitLen += 3;
					} else {
						bitLen += 4;
					}
					//字节数到达上限,获取子字符串加密并追加到总字符串后。更新下一个字符串起始位置及字节计算。
					if (bitLen > maxLength) {
						subStr = string.substring(subStart, subEnd)
						encryptedString += encrypt.encrypt(subStr);
						subStart = subEnd;
						bitLen = bitLen - tmpPoint;
					} else {
						subEnd = i;
						tmpPoint = bitLen;
					}
				}
				subStr = string.substring(subStart, len)
				encryptedString += encrypt.encrypt(subStr);
				return encryptedString;
			} catch (ex) {
				return false;
			}
		},
		getRealLen: function(str) {
			return str.replace(/[^\x00-\xff]/g, '__').length;

		},
		setEncryptList: function(publicKey, str, max) {
			var arr = []

			var s = str,
				reg = /.{40}/g,
				ppstr = s.match(reg);
			ppstr.push(s.substring(ppstr.join('').length));

			for (var nux = 0; nux < ppstr.length; nux++) {
				var Nax = this.getRealLen(ppstr[nux]);
				if (Nax > 116) {
					var list = this.setEncryptList(publicKey, ppstr[nux], Nax)
					for (var nu = 0; nu < list.length; nu++) {
						arr.push(list[nu]);
					}
				} else {

					arr.push(this.setEncrypt(publicKey, ppstr[nux]));
				}

			}
			return arr;
		},
		setEncrypt: function(publicKey, data) {
			const encrypt = new JSEncrypt();
			encrypt.setPublicKey(publicKey);
			return encrypt.encrypt(data);
		},
		setLongEncrypt: function(publicKey, data) {
			// debugger;
			// if(data.length > 117){
			// 	return setEncrypt(publicKey,data)
			// }
			var s = data,
			reg = /.{116}/g,
			rs = s.match(reg);
			if (rs === null) {
				console.log(data, '进入短加密')
				return this.setEncrypt(publicKey, data)
			}
			// debugger;
			rs.push(s.substring(rs.join('').length));
			var arr = [];
			for (var n = 0; n < rs.length; n++) {
				var max = this.getRealLen(rs[n]);

				if (max > 116) {

					var list = this.setEncryptList(publicKey, rs[n], max)
					for (var nu = 0; nu < list.length; nu++) {
						arr.push(list[nu]);
					}
				} else {

					arr.push(this.setEncrypt(publicKey, rs[n]));
				}

			}
			return arr;
		},
		setDecryptArray: function(PrivateKey, ArrayData) {
			var Decrypt = "";
			for (var n = 0; n < ArrayData.length; n++) {
				Decrypt = Decrypt + this.setDecrypt(PrivateKey, ArrayData[n]);
			}
			return Decrypt;
		},
		setDecrypt: function(PrivateKey, data) {
			const encrypt = new JSEncrypt();
			encrypt.setPrivateKey(PrivateKey);

			return encrypt.decrypt(data);
		}
	}
</script>

<style>

</style>

Logo

前往低代码交流专区

更多推荐