cjson.js 1.3 KB
/**
 * Created by lintry on 16/7/18.
 */
"use strict";

function CryptoJSON(sKey, sIv) {
  const path = require('path'),
    util = require('util'),
    crypto_utils = require('./crypto-utils');

  if (!(this instanceof CryptoJSON)) {
    return new CryptoJSON(sKey, sIv);
  }


  function convert(source, type, key, iv) {
    key = key || sKey;
    iv = iv || sIv;
    var method = crypto_utils[!!type ? 'AESEncode': 'AESDecode'];
    if (source) {
      if (util.isString(source)) {
        return method(source, key, iv);
      }
      var target = util.isArray(source)? [] : {};
      for (let k in source) {
        var v = source[k];
        if (!v) {
          target[k] = v;
        }
        else if (typeof v === 'object') {
          target[k] = convert(v, type, key, iv);
        } else {
          target[k] = method(v, key, iv);
        }
      }
      return target;
    } else {
      return null;
    }
  }

  /**
   * 加密对象
   * @param obj
   * @param key
   * @param iv
   * @returns {*}
   */
  this.encode = function (obj, key, iv) {
    return convert(obj, 1, key, iv);
  };

  /**
   * 解密对象
   * @param crypto_obj
   * @param key
   * @param iv
   * @returns {*}
   */
  this.decode = function (crypto_obj, key, iv) {
    return convert(crypto_obj, 0, key, iv);
  };
}

module.exports = CryptoJSON;