rsa.ts
1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// @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();
}
}