-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRSAWrapper.ts
86 lines (78 loc) · 2.8 KB
/
RSAWrapper.ts
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { CASRSAKeyPairResult, decryptCiphertextRsa, encryptPlaintextRsa, generateRsaKeys, signRsa, verifyRsa } from "../../index";
export class RSAWrapper {
/**
* Generates an RSA key pair based of parameter sent in 1024, 2048, and 4096 are supported.
* @param keySize
* @returns CASRSAKeyPairResult
*/
public generateKeys(keySize: number): CASRSAKeyPairResult {
if (keySize !== 1024 && keySize !== 2048 && keySize !== 4096) {
throw new Error("You must provide an appropriate key size to generate RSA keys");
}
return generateRsaKeys(keySize);
}
/**
* Encrypts a plaintext byte array with a RSA public key
* @param publicKey
* @param plaintext
* @returns Array<number>
*/
public encrypt(publicKey: string, plaintext: Array<number>): Array<number> {
if (!publicKey) {
throw new Error("You must provide a public key to encrypt with RSA");
}
if (!plaintext || plaintext.length === 0) {
throw new Error("You must provide an array of plaintext bytes to encrypt with RSA");
}
return encryptPlaintextRsa(publicKey, plaintext);
}
/**
* Decrypts a ciphertext with an RSA private key.
* @param privateKey
* @param ciphertext
* @returns Array<number>
*/
public decrypt(privateKey: string, ciphertext: Array<number>): Array<number> {
if (!privateKey) {
throw new Error("You must provide a private key to encrypt with RSA");
}
if (!ciphertext || ciphertext.length === 0) {
throw new Error("You must provide an array of ciphertext bytes to encrypt with RSA");
}
return decryptCiphertextRsa(privateKey, ciphertext);
}
/**
* Signs a byte array with an RSA private key for verification.
* @param privateKey
* @param hash
* @returns Array<number>
*/
public sign(privateKey: string, dataToSign: Array<number>): Array<number> {
if (!privateKey) {
throw new Error("You must provide a private key to sign with RSA");
}
if (!dataToSign || dataToSign.length === 0) {
throw new Error("You must provide an allocated hash to sign with RSA");
}
return signRsa(privateKey, dataToSign);
}
/**
* Verifies signed data by the corresponding private key with an RSA public key.
* @param publicKey
* @param hash
* @param signature
* @returns boolean
*/
public verify(publicKey: string, hash: Array<number>, signature: Array<number>): boolean {
if (!publicKey) {
throw new Error("You must provide a public key to verify with RSA");
}
if (!hash || hash.length === 0) {
throw new Error("You must provide an allocated hash to verify with RSA");
}
if (!signature || signature.length === 0) {
throw new Error("You must provide and allocated signature to verify with RSA");
}
return verifyRsa(publicKey, hash, signature);
}
}