Node.js/Java 实现 AES/CBC/PKCS7Padding 对称加密

import java.security.Key;
import java.security.Security;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class AESUtils {

    // 密钥
    public final static String SECREKEY = "9a3a2843cacc9783";

    // 算法名称
    public final static String KEY_ALGORITHM = "AES";

    // 加解密算法/模式/填充方式
    public final static String algorithmStr = "AES/CBC/PKCS7Padding";

    // 偏移量
    private final static String ivParameter = "1357924681012345";

    private static final byte[] iv = ivParameter.getBytes();

    public static byte[] encrypt(byte[] content, byte[] keyBytes) {

        int base = 16;
        byte[] encryptedText = null;

        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }

        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        Key key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);

        try {
            Cipher cipher = Cipher.getInstance(algorithmStr, "BC");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
            encryptedText = cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Base64.encode(encryptedText);
    }

    public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes) {

        int base = 16;
        byte[] encryptedText = null;

        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }

        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        Key key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);

        try {
            Cipher cipher = Cipher.getInstance(algorithmStr, "BC");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
            encryptedText = cipher.doFinal(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return encryptedText;
    }

    /**
     * sign(签名)
     * @param content
     * @param key
     * @return
     * @since JDK 1.8
     */
    public static String sign(String content, String key) {
        byte[] bytes;

        try {
            bytes = encrypt(content.getBytes("utf-8"), key.getBytes("utf-8"));
            return MD5Util.string2MD5(new String(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
import * as crypto from 'crypto';
import * as CryptoJS from 'crypto-js';

/**
 * MD5加密
 * @param text 明文
 * @param secret 密钥
 * @return
 */
export function encryptByMd5(text: string, secret?: string) {
  let hash: any;
  const algorithm: string = 'md5';

  if (secret) {
    hash = crypto.createHmac(algorithm, secret).update(text).digest('hex');
  } else {
    hash = crypto.createHash(algorithm).update(text).digest('hex');
  }

  return hash;
}

/**
 * AES/CBC/PKCS7Padding加密
 * @param content 接口参数拼接URI, key1=value1&key2=value2
 * @param secretKey 密钥
 * @param iv 偏移量
 * @return
 */
export function encryptByAESPKCS7(content: string, secretKey: string, iv: string) {
  iv = CryptoJS.enc.Utf8.parse(iv);
  content = CryptoJS.enc.Utf8.parse(content);
  secretKey = CryptoJS.enc.Utf8.parse(secretKey);

  const ciphertext: any = CryptoJS.AES.encrypt(content, secretKey, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });

  return ciphertext.toString();
  // return encryptByMd5(ciphertext.toString());
}

/**
 * AES/CBC/PKCS7Padding解密
 * @param content 密文
 * @param secretKey 秘钥
 * @param iv 偏移量
 * @return
 */
export function decryptByAESPKCS7(content: string, secretKey: string, iv: string) {
  iv = CryptoJS.enc.Utf8.parse(iv);
  secretKey = CryptoJS.enc.Utf8.parse(secretKey);

  const ciphertext: any = CryptoJS.AES.decrypt(content, secretKey, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });

  return ciphertext.toString(CryptoJS.enc.Utf8);
}

你可能感兴趣的:(杂论,经验分享)