// crypto.js
import CryptoJS from 'crypto-js';
import { JSEncrypt } from "jsencrypt";
import { getPublicKey } from "@/api/user.js"
export const Crypto = {
    AES: {
        encrypt: function (plaintext, secretKey) {
            return CryptoJS.AES.encrypt(plaintext, CryptoJS.enc.Utf8.parse(secretKey), {
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7,
                iv: ''
            }).ciphertext.toString(CryptoJS.enc.Base64);
        },
        decrypt: function (ciphertext, secretKey) {
            const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey);
            return bytes.toString(CryptoJS.enc.Utf8);
        }
    }
};
export const Encrypt = {
    encrypt: async function (plaintext) {
        let PublicKey = null;
        if (sessionStorage.getItem('PublicKey')) {
            PublicKey = atob(sessionStorage.getItem('PublicKey'));
        } else {
            try {
                let res = await getPublicKey();
                if (res.IsSuccess) {
                    PublicKey = atob(res.Result)
                    sessionStorage.setItem('PublicKey', res.Result)
                } else {
                    return false;
                }
            } catch (err) {
                console.log(err)
            }
        }
        let encryptor = new JSEncrypt()
        encryptor.setPublicKey(PublicKey)
        return encryptor.encrypt(plaintext)

    },

};
