Java和aes.js实现AES(CBC)加密与解密实现代码

AES算法可以实现字符串的加解密,本文主要介绍Java和Js(JavaScript)中实现AES(CBC)相互加解密,分别通过Java(bcprov)和aes.js实现方法及示例代码。

1、安装引用AES的加密解密的Jar包(bcprov-jdk16-1.46-sources.jar)

1) 手动下载引用

下载地址https://repo1.maven.org/maven2/org/bouncycastle/bcprov-jdk16/1.46/

2) Maven的pom.xml添加依赖

<dependency>
   <groupId>org.bouncycastle</groupId>
   <artifactId>bcprov-jdk16</artifactId>
   <version>1.46</version>
</dependency>

2、Java的AES加解密实现代码

package demo01;
import java.security.AlgorithmParameters;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
 * AES加密工具  模式:CBC  补码方式:PKCS7Padding
 * @author Administrator
 *
 */
public class AESCBCUtils {
	  public static boolean initialized = false;
	  final Base64.Decoder decoder = Base64.getDecoder();
	  final Base64.Encoder encoder = Base64.getEncoder();
    // 加密
    public static String encrypt(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
    	 initialize();
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(encodingFormat));
       return Base64.getEncoder().encodeToString(encrypted);
        //https://www.cjavapy.com//article/697
        //return parseByte2HexStr(encrypted);// 此处使用BASE64做转码。
    }
    /**BouncyCastle作为安全提供,防止我们加密解密时候因为jdk内置的不支持改模式运行报错。**/
    public static void initialize() {
        if (initialized)
            return;
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }
     public static String decrypt(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
            try {
            	 initialize();
                byte[] raw = sKey.getBytes("utf-8");
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
                IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
                //https://www.cjavapy.com//article/697
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
                byte[] encrypted1 = Base64.getDecoder().decode(sSrc); ///parseHexStr2Byte(sSrc);//先用base64解密
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,encodingFormat);
                return originalString;
            } catch (Exception ex) {
                return null;
            }
    }
    /**
     * 将二进制转换成十六进制
     * 
     * @param buf
     * @return
     */
    private 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();
    }
    /**
     * 将十六进制转换为二进制
     * 
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        } else {
            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;
        }
    }
}

测试:

package demo01;
public class demo {

	public static void main(String[] args) {
		//https://www.cjavapy.com//article/697
		try {
			System.out.println(AESCBCUtils.decrypt("v9BxRJX+ojPDhyJFrglcbA==","utf-8","CJAVAPmXcuAksWmF","V33CQ1428SI8ZNMT"));
			System.out.println(AESCBCUtils.encrypt("137","utf-8","CJAVAPmXcuAksWmF","V33CQ1428SI8ZNMT"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

3、js的aes.js加解密实现代码

aes.js下载引用地址https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js

//加密
function encrypt(e,key,iv) {
       var r =  CryptoJS.enc.Utf8.parse(key),
       var n =  CryptoJS.enc.Utf8.parse(iv),
       var  o =  CryptoJS.enc.Utf8.parse(e),
       var u = {
            iv: n,
            mode:  CryptoJS.mode.CBC,
            padding:  CryptoJS.pad.Pkcs7
        },
        i =  CryptoJS.AES.encrypt(o, r, u);
        return i.toString()
 }
//解密
function decrypt(str, key, iv) {
   var r = CryptoJS.enc.Utf8.parse(iv),
   var  n = CryptoJS.enc.Utf8.parse(key),
   var o = CryptoJS.AES.decrypt(e, n, {
        iv: r,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return CryptoJS.enc.Utf8.stringify(o).toString()
}
Node.js中实现AES(CBC)加密和解密:
安装crypto:npm install crypto
//加密
function encrypt (data, key, iv) {
    iv = iv || "";
    var clearEncoding = 'utf8';
    var cipherEncoding = 'base64';
    var cipherChunks = [];
    var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    cipher.setAutoPadding(true);
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    return cipherChunks.join('');
}
//解密
function decrypt (data, key, iv) {
    if (!data) {
        return "";
    }
    iv = iv || "";
    var clearEncoding = 'utf8';
    var cipherEncoding = 'base64';
    var cipherChunks = [];
    var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    decipher.setAutoPadding(true);
    cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
    cipherChunks.push(decipher.final(clearEncoding));
    return cipherChunks.join('');
}


推荐阅读
cjavapy编程之路首页