react crypto-js 实现前端加密与解密

章琛
2023-12-01

一、安装 crypto-js 

npm install crypto-js

二、react 前端加密

import CryptoJS  from "crypto-js"

let result = ""
const key = CryptoJS.enc.Base64.parse( 'YCFIyMTG5NTYxYzlmZTA2OA==')
var iv =  CryptoJS.enc.Base64.parse('YCFyMTG5NTYxYzlmZTA2OA==')
// 手机号加密
result = CryptoJS.AES.encrypt('18888888888',key,{ 
             iv: iv,
             mode: CryptoJS.mode.CBC,  
             padding: CryptoJS.pad.Pkcs7  
        });
result = result.ciphertext.toString()

三、后端解密


import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * ReCaptcha 解密
 * @author :cfyang
 * @date:2020-05-08
 */
public class ReCaptchaUtil {

    private static String key = "YCFIyMTG5NTYxYzlmZTA2OA==";
    private static String iv = "YCFIyMTG5NTYxYzlmZTA2OA==";


    // 解密
    public static String AES_CBC_Decrypt(String crypto) throws Exception{
        byte[] data = parseHexStr2Byte(crypto);
        String keyStr = new String(new BASE64Decoder().decodeBuffer(key), "UTF-8");
        byte[] key = keyStr.getBytes();
        String ivStr = new String(new BASE64Decoder().decodeBuffer(iv), "UTF-8");
        byte[] iv = ivStr.getBytes();
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, key, iv);
        return new String(cipher.doFinal(data));
    }
    private static Cipher getCipher(int mode, byte[] key, byte[] iv) throws Exception{
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        //因为AES的加密块大小是128bit(16byte), 所以key是128、192、256bit无关
        //System.out.println("cipher.getBlockSize(): " + cipher.getBlockSize());

        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        cipher.init(mode, secretKeySpec, new IvParameterSpec(iv));

        return cipher;
    }







    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    private 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;
    }


    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
}

 

 类似资料: