import JSEncrypt from 'jsencrypt';
import { Base64 } from 'js-base64';

// RSA公钥 
let RSA_PUBLIC_KEY = (import.meta.env.VITE_RSA_PUBLIC_KEY as string) || '';

/**
 * RSA密码加密函数
 * @param password 明文密码
 * @returns 加密后的密码
 */
export const rsaPsw = (password: string): string => {
  try {
    const encrypt = new JSEncrypt();
    const publicKey = RSA_PUBLIC_KEY;
    console.log('publicKey', publicKey);
    encrypt.setPublicKey(publicKey);
    const encrypted = encrypt.encrypt(Base64.encode(password));
    return encrypted || password;
  } catch (error) {
    console.error('RSA encryption failed:', error);
    return password;
  }
};

/**
 * 获取RSA公钥
 * @returns RSA公钥字符串
 */
export const getRSAPublicKey = (): string => {
  return RSA_PUBLIC_KEY;
};

export const setRSAPublicKey = (key: string) => {
  RSA_PUBLIC_KEY = key;
};