@hg-ts/rsa 0.5.17 → 0.5.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +9 -9
- package/src/index.ts +3 -0
- package/src/rsa.base-key.ts +75 -0
- package/src/rsa.key-pair.ts +57 -0
- package/src/rsa.private-key.ts +45 -0
- package/src/rsa.public-key.ts +65 -0
- package/src/rsa.test.ts +113 -0
- package/src/utils.ts +40 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hg-ts/rsa",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.18",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -18,12 +18,12 @@
|
|
|
18
18
|
"test:dev": "vitest watch"
|
|
19
19
|
},
|
|
20
20
|
"devDependencies": {
|
|
21
|
-
"@hg-ts-config/typescript": "0.5.
|
|
22
|
-
"@hg-ts/exception": "0.5.
|
|
23
|
-
"@hg-ts/linter": "0.5.
|
|
24
|
-
"@hg-ts/tests": "0.5.
|
|
25
|
-
"@hg-ts/types": "0.5.
|
|
26
|
-
"@hg-ts/validation": "0.5.
|
|
21
|
+
"@hg-ts-config/typescript": "0.5.18",
|
|
22
|
+
"@hg-ts/exception": "0.5.18",
|
|
23
|
+
"@hg-ts/linter": "0.5.18",
|
|
24
|
+
"@hg-ts/tests": "0.5.18",
|
|
25
|
+
"@hg-ts/types": "0.5.18",
|
|
26
|
+
"@hg-ts/validation": "0.5.18",
|
|
27
27
|
"@types/node": "22.19.1",
|
|
28
28
|
"@types/node-forge": "^1",
|
|
29
29
|
"@vitest/coverage-v8": "4.0.14",
|
|
@@ -36,8 +36,8 @@
|
|
|
36
36
|
"vitest": "4.0.14"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
|
-
"@hg-ts/exception": "0.5.
|
|
40
|
-
"@hg-ts/validation": "0.5.
|
|
39
|
+
"@hg-ts/exception": "0.5.18",
|
|
40
|
+
"@hg-ts/validation": "0.5.18",
|
|
41
41
|
"reflect-metadata": "*",
|
|
42
42
|
"tslib": "*",
|
|
43
43
|
"vitest": "*"
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import forge from 'node-forge';
|
|
2
|
+
|
|
3
|
+
export abstract class RSABaseKey {
|
|
4
|
+
private readonly mdDigestLength: number;
|
|
5
|
+
|
|
6
|
+
protected abstract key: forge.pki.rsa.PrivateKey | forge.pki.rsa.PublicKey;
|
|
7
|
+
|
|
8
|
+
public constructor() {
|
|
9
|
+
this.mdDigestLength = this.getMd().digestLength;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
protected prepareToEncrypt(data: string | Uint8Array): string[] {
|
|
13
|
+
const input = this.formatDecryptedInputToString(data);
|
|
14
|
+
|
|
15
|
+
return this.splitInput(input, this.maxLength);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
protected prepareToDecrypt(data: string | Uint8Array): string[] {
|
|
19
|
+
const encryptedLength = this.keyLength * 2;
|
|
20
|
+
const encrypted = typeof data === 'string' ? data : Buffer.from(data).toString('hex');
|
|
21
|
+
|
|
22
|
+
return this.splitInput(encrypted, encryptedLength)
|
|
23
|
+
.map(chunk => Buffer
|
|
24
|
+
.from(chunk, 'hex')
|
|
25
|
+
.toString('binary'),
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
protected formatDecryptedInputToString(data: string | Uint8Array): string {
|
|
30
|
+
if (typeof data === 'string') {
|
|
31
|
+
return data;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return Buffer.from(data).toString('hex');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
protected formatSignature(data: string | Uint8Array): string {
|
|
38
|
+
if (typeof data === 'string') {
|
|
39
|
+
return data;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return Buffer.from(data).toString('binary');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
protected formatEncrypted(data: string[]): Uint8Array {
|
|
46
|
+
const chunks = data.map(chunk => Buffer.from(chunk, 'binary').toString('hex'));
|
|
47
|
+
|
|
48
|
+
return Buffer.from(chunks.join(''), 'hex');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
protected getMd(): forge.md.MessageDigest {
|
|
52
|
+
return forge.md.sha256.create();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
protected get maxLength(): number {
|
|
56
|
+
return this.keyLength - (this.mdDigestLength * 2) - 2;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
protected get keyLength(): number {
|
|
60
|
+
return Math.ceil(this.key.n.bitLength() / 8);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private splitInput(value: string, length: number): string[] {
|
|
64
|
+
const chars = value.split('');
|
|
65
|
+
const chunks: string[] = [];
|
|
66
|
+
|
|
67
|
+
while (chars.length > 0) {
|
|
68
|
+
const chunk = chars.splice(0, length);
|
|
69
|
+
|
|
70
|
+
chunks.push(chunk.join(''));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return chunks;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import forge from 'node-forge';
|
|
2
|
+
import { RSAPrivateKey } from './rsa.private-key.js';
|
|
3
|
+
import { RSAPublicKey } from './rsa.public-key.js';
|
|
4
|
+
|
|
5
|
+
export type RSAKeyPairOptions = {
|
|
6
|
+
seed?: string;
|
|
7
|
+
bits?: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class RSAKeyPair {
|
|
11
|
+
private readonly publicRsaKey: RSAPublicKey;
|
|
12
|
+
private readonly privateRsaKey: RSAPrivateKey;
|
|
13
|
+
|
|
14
|
+
public constructor(options: RSAKeyPairOptions = {}) {
|
|
15
|
+
const keyPair = this.generateKeys(options);
|
|
16
|
+
|
|
17
|
+
this.privateRsaKey = new RSAPrivateKey(keyPair.privateKey);
|
|
18
|
+
this.publicRsaKey = new RSAPublicKey(keyPair.publicKey);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
public encrypt(value: string | Uint8Array): Uint8Array {
|
|
22
|
+
return this.publicRsaKey.encrypt(value);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
public decrypt(value: string | Uint8Array): string {
|
|
26
|
+
return this.privateRsaKey.decrypt(value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
public sign(value: string): Uint8Array {
|
|
30
|
+
return this.privateRsaKey.sign(value);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
public verify(signature: string | Uint8Array, value: string): boolean {
|
|
34
|
+
return this.publicRsaKey.verify(signature, value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
public get publicKey(): string {
|
|
38
|
+
return this.publicRsaKey.toString();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
public get privateKey(): string {
|
|
42
|
+
return this.privateRsaKey.toString();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private generateKeys(options: RSAKeyPairOptions): forge.pki.rsa.KeyPair {
|
|
46
|
+
const { seed } = options;
|
|
47
|
+
if (!seed) {
|
|
48
|
+
return forge.pki.rsa.generateKeyPair({ bits: options.bits });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const prng = forge.random.createInstance();
|
|
52
|
+
prng.seedFileSync = (): string => seed;
|
|
53
|
+
prng.seedFile = (): string => seed;
|
|
54
|
+
|
|
55
|
+
return forge.pki.rsa.generateKeyPair({ prng, bits: options.bits });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import forge from 'node-forge';
|
|
2
|
+
import { RSABaseKey } from './rsa.base-key.js';
|
|
3
|
+
|
|
4
|
+
export class RSAPrivateKey extends RSABaseKey {
|
|
5
|
+
protected readonly key: forge.pki.rsa.PrivateKey;
|
|
6
|
+
|
|
7
|
+
public constructor(key: forge.pki.rsa.PrivateKey) {
|
|
8
|
+
super();
|
|
9
|
+
this.key = key;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
public decrypt(encrypted: string | Uint8Array): string {
|
|
13
|
+
const md = this.getMd();
|
|
14
|
+
|
|
15
|
+
const chunks = this.prepareToDecrypt(encrypted);
|
|
16
|
+
|
|
17
|
+
const decryptedChunks = chunks.map(chunk => this.key.decrypt(chunk, 'RSAES-PKCS1-V1_5', { md }));
|
|
18
|
+
|
|
19
|
+
return decryptedChunks.join('');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
public sign(value: string): Uint8Array {
|
|
23
|
+
const hash = this.getMd();
|
|
24
|
+
hash.update(value);
|
|
25
|
+
|
|
26
|
+
const pss = forge.pss.create({
|
|
27
|
+
md: this.getMd(),
|
|
28
|
+
mgf: forge.mgf.mgf1.create(this.getMd()),
|
|
29
|
+
saltLength: 20,
|
|
30
|
+
});
|
|
31
|
+
const signedId = this.key.sign(hash, pss);
|
|
32
|
+
|
|
33
|
+
return Buffer.from(signedId, 'binary');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
public override toString(): string {
|
|
37
|
+
return forge.pki.privateKeyToPem(this.key);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
public static fromString(pemKey: string): RSAPrivateKey {
|
|
41
|
+
const key = forge.pki.privateKeyFromPem(pemKey);
|
|
42
|
+
|
|
43
|
+
return new RSAPrivateKey(key);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { z } from '@hg-ts/validation';
|
|
2
|
+
import forge from 'node-forge';
|
|
3
|
+
import { RSABaseKey } from './rsa.base-key.js';
|
|
4
|
+
|
|
5
|
+
const schema = z.string().transform((value, ctx) => {
|
|
6
|
+
try {
|
|
7
|
+
const publicKey = forge.pki.publicKeyFromPem(value);
|
|
8
|
+
|
|
9
|
+
return forge.pki.publicKeyToPem(publicKey);
|
|
10
|
+
} catch (error) {
|
|
11
|
+
ctx.issues.push({
|
|
12
|
+
message: 'Invalid public key',
|
|
13
|
+
fatal: true,
|
|
14
|
+
code: 'invalid_format',
|
|
15
|
+
input: value,
|
|
16
|
+
format: 'RSA Public Key',
|
|
17
|
+
});
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
}).pipe(z.string());
|
|
21
|
+
|
|
22
|
+
export class RSAPublicKey extends RSABaseKey {
|
|
23
|
+
protected readonly key: forge.pki.rsa.PublicKey;
|
|
24
|
+
|
|
25
|
+
public static schema = schema;
|
|
26
|
+
|
|
27
|
+
public constructor(key: forge.pki.rsa.PublicKey) {
|
|
28
|
+
super();
|
|
29
|
+
this.key = key;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
public encrypt(value: string | Uint8Array): Uint8Array {
|
|
33
|
+
const md = this.getMd();
|
|
34
|
+
const chunks = this.prepareToEncrypt(value);
|
|
35
|
+
|
|
36
|
+
const encryptedChunks = chunks.map(chunk => this.key.encrypt(chunk, 'RSAES-PKCS1-V1_5', { md }));
|
|
37
|
+
|
|
38
|
+
return this.formatEncrypted(encryptedChunks);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
public verify(signature: string | Uint8Array, value: string): boolean {
|
|
42
|
+
const hash = this.getMd();
|
|
43
|
+
hash.update(value);
|
|
44
|
+
|
|
45
|
+
const pss = forge.pss.create({
|
|
46
|
+
md: this.getMd(),
|
|
47
|
+
mgf: forge.mgf.mgf1.create(this.getMd()),
|
|
48
|
+
saltLength: 20,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const formattedSignature = this.formatSignature(signature);
|
|
52
|
+
|
|
53
|
+
return this.key.verify(hash.digest().bytes(), formattedSignature, pss);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
public override toString(): string {
|
|
57
|
+
return forge.pki.publicKeyToPem(this.key);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
public static fromString(pemKey: string): RSAPublicKey {
|
|
61
|
+
const key = forge.pki.publicKeyFromPem(pemKey);
|
|
62
|
+
|
|
63
|
+
return new RSAPublicKey(key);
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/rsa.test.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Describe,
|
|
3
|
+
expect,
|
|
4
|
+
ExpectException,
|
|
5
|
+
Suite,
|
|
6
|
+
Test,
|
|
7
|
+
} from '@hg-ts/tests';
|
|
8
|
+
import { z } from '@hg-ts/validation';
|
|
9
|
+
|
|
10
|
+
import { RSAKeyPair } from './rsa.key-pair.js';
|
|
11
|
+
import { RSAPrivateKey } from './rsa.private-key.js';
|
|
12
|
+
import { RSAPublicKey } from './rsa.public-key.js';
|
|
13
|
+
|
|
14
|
+
@Describe()
|
|
15
|
+
export class RsaTest extends Suite {
|
|
16
|
+
@Test()
|
|
17
|
+
public async signature(): Promise<void> {
|
|
18
|
+
const rsa = new RSAKeyPair({ bits: 512 });
|
|
19
|
+
const value = Math.random().toString();
|
|
20
|
+
|
|
21
|
+
const signature = rsa.sign(value);
|
|
22
|
+
expect(rsa.verify(Buffer.from(signature).toString('binary'), value)).toBeTruthy();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
@Test()
|
|
26
|
+
public async signatureBuffer(): Promise<void> {
|
|
27
|
+
const rsa = new RSAKeyPair({ bits: 512 });
|
|
28
|
+
const value = Math.random().toString();
|
|
29
|
+
|
|
30
|
+
const signature = rsa.sign(value);
|
|
31
|
+
expect(rsa.verify(Buffer.from(signature), value)).toBeTruthy();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
@Test()
|
|
35
|
+
public async encryption(): Promise<void> {
|
|
36
|
+
const rsa = new RSAKeyPair({ bits: 1024 });
|
|
37
|
+
const value = Math.random().toString();
|
|
38
|
+
|
|
39
|
+
const encrypted = rsa.encrypt(value);
|
|
40
|
+
expect(rsa.decrypt(Buffer.from(encrypted).toString('hex'))).toBe(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
@Test()
|
|
44
|
+
public async encryptionBuffer(): Promise<void> {
|
|
45
|
+
const rsa = new RSAKeyPair({ bits: 1024 });
|
|
46
|
+
const value = Buffer.from(Math.random().toString(), 'utf-8');
|
|
47
|
+
|
|
48
|
+
const encrypted = rsa.encrypt(value);
|
|
49
|
+
expect(Buffer.from(rsa.decrypt(encrypted), 'hex')).toMatchObject(value);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
@Test()
|
|
53
|
+
public async longMessageEncryption(): Promise<void> {
|
|
54
|
+
const rsa = new RSAKeyPair({ bits: 1024 });
|
|
55
|
+
const rsaToTest = new RSAKeyPair({ bits: 1024 });
|
|
56
|
+
const value = rsaToTest.publicKey;
|
|
57
|
+
|
|
58
|
+
const encrypted = rsa.encrypt(value);
|
|
59
|
+
expect(rsa.decrypt(encrypted)).toBe(value);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
@Test()
|
|
63
|
+
public async longMessageSignature(): Promise<void> {
|
|
64
|
+
const rsa = new RSAKeyPair({ bits: 512 });
|
|
65
|
+
const value = rsa.publicKey;
|
|
66
|
+
|
|
67
|
+
const signature = rsa.sign(value);
|
|
68
|
+
expect(rsa.verify(signature, value)).toBeTruthy();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
@Test()
|
|
72
|
+
public async seeded(): Promise<void> {
|
|
73
|
+
const seed = Math.random().toString();
|
|
74
|
+
const rsa1 = new RSAKeyPair({ seed, bits: 512 });
|
|
75
|
+
const rsa2 = new RSAKeyPair({ seed, bits: 512 });
|
|
76
|
+
|
|
77
|
+
expect(rsa1.privateKey).toBe(rsa2.privateKey);
|
|
78
|
+
expect(rsa1.publicKey).toBe(rsa2.publicKey);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
@Test()
|
|
82
|
+
public async privateKeyFromString(): Promise<void> {
|
|
83
|
+
const rsa = new RSAKeyPair({ bits: 512 });
|
|
84
|
+
const rsaFromString = RSAPrivateKey.fromString(rsa.privateKey);
|
|
85
|
+
|
|
86
|
+
expect(rsaFromString.toString()).toBe(rsa.privateKey.toString());
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
@Test()
|
|
90
|
+
public async publicKeyFromString(): Promise<void> {
|
|
91
|
+
const rsa = new RSAKeyPair({ bits: 512 });
|
|
92
|
+
const rsaFromString = RSAPublicKey.fromString(rsa.publicKey);
|
|
93
|
+
|
|
94
|
+
expect(rsaFromString.toString()).toBe(rsa.publicKey.toString());
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
@Test()
|
|
98
|
+
public async publicKeyValidationsValid(): Promise<void> {
|
|
99
|
+
const rsa = new RSAKeyPair({ bits: 512 });
|
|
100
|
+
|
|
101
|
+
RSAPublicKey.schema.parse(rsa.publicKey.toString());
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
@Test()
|
|
105
|
+
@ExpectException(z.ZodError)
|
|
106
|
+
public async publicKeyValidationsFails(): Promise<void> {
|
|
107
|
+
// Тут убран одир случайный символ из ключа
|
|
108
|
+
RSAPublicKey.schema.parse(`-----BEGIN PUBLIC KEY-----
|
|
109
|
+
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALnfPJr6J2UXwvZhbPWolBw4UJHAEMd
|
|
110
|
+
/FvIyIYADhT/k+2TIFixs4pxM5VaGMP7Tny+5WAouv9ulh4tACPxKoMCAwEAAQ==
|
|
111
|
+
-----END PUBLIC KEY-----`);
|
|
112
|
+
}
|
|
113
|
+
}
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import forge from 'node-forge';
|
|
2
|
+
|
|
3
|
+
export function chunkString(value: string, length: number): string[] {
|
|
4
|
+
const chars = value.split('');
|
|
5
|
+
const chunks: string[] = [];
|
|
6
|
+
|
|
7
|
+
while (chars.length > 0) {
|
|
8
|
+
const chunk = chars.splice(0, length);
|
|
9
|
+
|
|
10
|
+
chunks.push(chunk.join(''));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
return chunks;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function getMd(): forge.md.MessageDigest {
|
|
17
|
+
return forge.md.sha256.create();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function getKeyLength(key: forge.pki.rsa.PrivateKey | forge.pki.rsa.PublicKey): number {
|
|
21
|
+
return Math.ceil(key.n.bitLength() / 8);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function getMaxLength(
|
|
25
|
+
key: forge.pki.rsa.PrivateKey | forge.pki.rsa.PublicKey,
|
|
26
|
+
md: forge.md.MessageDigest,
|
|
27
|
+
): number {
|
|
28
|
+
const keyLength = getKeyLength(key);
|
|
29
|
+
|
|
30
|
+
return keyLength - (md.digestLength * 2) - 2;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
export function getEncryptedLength(
|
|
35
|
+
key: forge.pki.rsa.PrivateKey | forge.pki.rsa.PublicKey,
|
|
36
|
+
): number {
|
|
37
|
+
const keyLength = getKeyLength(key);
|
|
38
|
+
|
|
39
|
+
return keyLength * 2;
|
|
40
|
+
}
|