AES / ECB加密<没有iv>

cryptoJS插件(aes加密)前端

// 下载

// “npm install crypto-js”或“yarn add crypto-js”

 

// 基本使用

 

// 引入:

const CryptoJS = require("crypto-js")

 

// 基本使用

const testText = '这是一段要加密的文字' // 文本

const secretKey = "ABCDEFGHIJKL_key" // 密钥(十六位,需要和后端密钥保持一致)

 

// 加密过程

const bytes = CryptoJS.AES.encrypt(

toParse(testText),

toParse(secretKey),

{

mode: CryptoJS.mode.ECB, // 加密模式

padding: CryptoJS.pad.Pkcs7

}

)

 

// 序列化,result即加密结果

const result = CryptoJS.enc.Base64.stringify(bytes.ciphertext)

 

function toParse(val) {

return CryptoJS.enc.Utf8.parse(val)

}

 

 

 

 

 

 

后端解密代码样例:

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

/**

 * @param content 前端将加密后的字符转成base64后传给后端

 */

public void decrypt(String content) {

        // 和前端约定的key

        String key = "ABCDEFGHIJKL_key";

        // 解密

        byte[] decrypted = AES_ECB_Decrypt(decryptBASE64(content), key.getBytes());

        String initialString = byteToString(decrypted);

        log.info("解密后:{}",initialString);

}

private byte[] AES_ECB_Decrypt(byte[] content,byte[] keyBytes){

        try {

               SecretKey key = new SecretKeySpec(keyBytes,"AES");

               Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

               cipher.init(Cipher.DECRYPT_MODE,key);

               return cipher.doFinal(content);

        }catch (Exception e){

               log.error("exception:{}",e);

        }

        return null;

}

private byte[] decryptBASE64(String key) {

        return Base64.decodeBase64(key.getBytes());

}

private String byteToString(byte[] bytes){

        return new String(bytes);

}

 

 

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
 
/**
 * aes/ecb加密
 * @param content 需要加密的字符串
 */
public void encrypt(String content) {
        // 和前端约定的key
        String key = "ABCDEFGHIJKL_key";
        // 加密
    byte[] encrypted = AES_ECB_Encrypt(content.getBytes(), key.getBytes());
        String ss = encryptBASE64(encrypted);
        log.info("解密后:{}",ss);
}
 
private byte[] AES_ECB_Encrypt(byte[] content,byte[] keyBytes){
        try {
               SecretKeySpec key = new SecretKeySpec(keyBytes,"AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,key);
        return cipher.doFinal(content);
        }catch (Exception e){
               log.error("exception:{}",e);
        }
        return null;
}
private String encryptBASE64(byte[] key) {
    return new String(Base64.encodeBase64(key));
}
posted @ 2021-10-19 09:48  文字章  阅读(919)  评论(0)    收藏  举报