Node Crype 对应 Java中的DES/CBC/PKCS5Padding 的加解密

简介

node中经常遇到需要和java项目对接的情况, 或者是java的加密jar包给你, 需要用node写加解密、验签的情况

今天带来 使用node crypte 对应 java的 DES解密

代码

const crypto = require('crypto');

/*
 * @brief 加密数据
 * @param[in] encodeParam 加密相关参数
 * @return 密文
 */
function crypto_encode(encodeParam) {
  try {
    let plain = encodeParam.plainText.toString();
    //encrypt
    const iv = new Buffer(encodeParam.iv ? encodeParam.iv : 0);
    const cipher = crypto.createCipheriv(
      encodeParam.algorithm,
      encodeParam.key,
      iv
    );
    cipher.setAutoPadding(encodeParam.autoPadding); //default true
    let cipherText = cipher.update(plain, 'utf8', 'base64');
    cipherText += cipher.final('base64');
    console.log(
      'crypto data success: algorithm(%s),plainText(%s),cipherText(%s)',
      encodeParam.algorithm,
      plain,
      cipherText
    );
    return cipherText;
  } catch (err) {
    console.log('crypto data failed: ' + err);
    return null;
  }
}

/*
 * @brief 解密数据
 * @param[in] decodeParam 解密相关参数
 */
function decrypt_decode(decodeParam) {
  try {
    let cipherText = decodeParam.cipherText.toString();
    //decrypt
    const iv = new Buffer(decodeParam.iv ? decodeParam.iv : 0);
    const decipher = crypto.createDecipheriv(
      decodeParam.algorithm,
      decodeParam.key,
      iv
    );
    decipher.setAutoPadding(decodeParam.autoPadding); //default true
    let plainText = decipher.update(cipherText, 'base64', 'utf-8');
    plainText += decipher.final('utf-8');
    console.log(
      'decrypt data success: algorithm(%s),plainText(%s),cipherText(%s)',
      decodeParam.algorithm,
      plainText,
      cipherText
    );
    return plainText;
  } catch (err) {
    console.log('deCrypto data failed: ' + err);
    return null;
  }
}

// test
const DES_KEY = 'example123456';
const DES_IV = [0x21, 0x55, 0x36, 110, 0x40, 0xac, 0xad, 0xdf];
// crypto_encode des-cbc
crypto_encode({
  algorithm: 'des-cbc',
  autoPadding: true,
  key: new Buffer(DES_KEY.slice(0, 8), 'utf-8'),
  plainText: '18654551606',
  iv: DES_IV,
});

// decrypt_decode des-cbc
decrypt_decode({
  algorithm: 'des-cbc',
  autoPadding: true,
  key: new Buffer(DES_KEY.slice(0, 8), 'utf-8'),
  cipherText: '2Wf2baQKdbWpMiAckLnueA==',
  iv: DES_IV,
});

 

感谢您的阅读!如果文章中有任何错误,或者您有更好的理解和建议,欢迎和我联系!

你可能感兴趣的:(Node,Crype,对应)