import * as crypto from "crypto";

/**
 * 非标3DES加解密
 */
export class Des3Util {
  /**
   * 加密
   */
  static encrypt(data: string | object, key: string, iv: string) {
    const cipher = crypto.createCipheriv("des-ede3-cbc", key, iv);

    let encrypted: string = null;

    if (typeof data === "string") {
      encrypted = cipher.update(data, "utf8", "base64");
    } else {
      let json = JSON.stringify(data, (k, v) => {
        return k === "imageInfo" ? undefined : v;
      });

      encrypted = cipher.update(json, "utf8", "base64");
    }

    encrypted += cipher.final("base64");

    return encrypted;
  }

  /**
   * 解密
   */
  static decrypt(data: string, key: string, iv: string) {
    const decipher = crypto.createDecipheriv("des-ede3-cbc", key, iv);
    let decrypted = decipher.update(data, "base64", "utf8");
    decrypted += decipher.final("utf8");

    return decrypted;
  }
}
