rsa.ts 1.56 KB
// @ts-nocheck
import { JSEncrypt } from './JSEncrypt';

export class RSAHandler {
    private jsEncrypt: JSEncrypt;

    constructor() {
        this.jsEncrypt = new JSEncrypt({ default_key_size: 2048 });
    }

    /**
     * 生成 RSA 密钥对
     * @returns { publicKey: string, privateKey: string }
     */
    generateKeyPair() {
        this.jsEncrypt.getKey();
        return {
            publicKey: this.jsEncrypt.getPublicKey(),
            privateKey: this.jsEncrypt.getPrivateKey()
        };
    }

    /**
     * 设置 RSA 公钥
     * @param publicKey PEM 格式的公钥
     */
    setPublicKey(publicKey: string) {
        this.jsEncrypt.setPublicKey(publicKey);
    }

    /**
     * 设置 RSA 私钥
     * @param privateKey PEM 格式的私钥
     */
    setPrivateKey(privateKey: string) {
        this.jsEncrypt.setPrivateKey(privateKey);
    }

    /**
     * RSA 加密
     * @param data 要加密的数据
     * @returns 加密后的 Base64 字符串
     */
    encrypt(data: string): string {
        return this.jsEncrypt.encrypt(data) || '';
    }

    /**
     * RSA 解密
     * @param encryptedData 加密后的 Base64 字符串
     * @returns 解密后的原始数据
     */
    decrypt(encryptedData: string): string {
        return this.jsEncrypt.decrypt(encryptedData) || '';
    }

    /**
     * 获取当前 RSA 公钥
     */
    getPublicKey(): string {
        return this.jsEncrypt.getPublicKey();
    }

    /**
     * 获取当前 RSA 私钥
     */
    getPrivateKey(): string {
        return this.jsEncrypt.getPrivateKey();
    }
}