@push.rocks/smartcrypto 2.5.0 → 3.0.0
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/.smartconfig.json +0 -1
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/index.d.ts +1 -2
- package/dist_ts/index.js +1 -3
- package/dist_ts/smartcrypto.classes.keypair.d.ts +1 -0
- package/dist_ts/smartcrypto.classes.keypair.js +34 -15
- package/dist_ts/smartcrypto.classes.privatekey.d.ts +26 -3
- package/dist_ts/smartcrypto.classes.privatekey.js +93 -14
- package/dist_ts/smartcrypto.classes.publickey.d.ts +20 -7
- package/dist_ts/smartcrypto.classes.publickey.js +59 -45
- package/dist_ts/smartcrypto.classes.smartcrypto.js +1 -2
- package/dist_ts/smartcrypto.der.d.ts +44 -0
- package/dist_ts/smartcrypto.der.js +196 -0
- package/dist_ts/smartcrypto.internal.d.ts +1 -0
- package/dist_ts/smartcrypto.internal.js +4 -3
- package/dist_ts/smartcrypto.openssh.d.ts +8 -0
- package/dist_ts/smartcrypto.openssh.js +51 -0
- package/dist_ts/smartcrypto.pem.d.ts +16 -0
- package/dist_ts/smartcrypto.pem.js +50 -0
- package/dist_ts/smartcrypto.pkcs8.d.ts +4 -6
- package/dist_ts/smartcrypto.pkcs8.js +33 -95
- package/dist_ts/smartcrypto.rsa.d.ts +30 -0
- package/dist_ts/smartcrypto.rsa.js +153 -0
- package/package.json +2 -7
- package/readme.md +46 -8
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/index.ts +4 -4
- package/ts/smartcrypto.classes.keypair.ts +34 -17
- package/ts/smartcrypto.classes.privatekey.ts +111 -19
- package/ts/smartcrypto.classes.publickey.ts +83 -78
- package/ts/smartcrypto.classes.smartcrypto.ts +0 -1
- package/ts/smartcrypto.der.ts +235 -0
- package/ts/smartcrypto.internal.ts +5 -2
- package/ts/smartcrypto.openssh.ts +98 -0
- package/ts/smartcrypto.pem.ts +61 -0
- package/ts/smartcrypto.pkcs8.ts +63 -121
- package/ts/smartcrypto.rsa.ts +234 -0
- package/dist_ts/smartcrypto.plugins.d.ts +0 -4
- package/dist_ts/smartcrypto.plugins.js +0 -7
- package/ts/smartcrypto.plugins.ts +0 -9
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import * as plugins from './smartcrypto.plugins.js';
|
|
2
1
|
import { PublicKey } from './smartcrypto.classes.publickey.js';
|
|
3
2
|
import { PrivateKey } from './smartcrypto.classes.privatekey.js';
|
|
4
|
-
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
3
|
+
import { SmartCryptoError, createSmartCryptoError } from './smartcrypto.errors.js';
|
|
4
|
+
import { getWebCrypto } from './smartcrypto.internal.js';
|
|
5
|
+
import { decodePrivateKeyInfo, zeroRsaPrivateKeyComponents } from './smartcrypto.rsa.js';
|
|
5
6
|
|
|
6
7
|
export type TRsaModulusLength = 2048 | 3072 | 4096;
|
|
7
8
|
|
|
@@ -14,27 +15,43 @@ const rsaModulusLengths: readonly TRsaModulusLength[] = [2048, 3072, 4096];
|
|
|
14
15
|
|
|
15
16
|
export class KeyPair {
|
|
16
17
|
// STATIC
|
|
18
|
+
/** Generates an RSA key pair with public exponent 65537 via WebCrypto. */
|
|
17
19
|
public static async createNewKeyPair(optionsArg: IKeyPairOptions = {}): Promise<KeyPair> {
|
|
18
20
|
const modulusLength = optionsArg.modulusLength ?? 2048;
|
|
19
21
|
if (!rsaModulusLengths.includes(modulusLength)) {
|
|
20
22
|
throw createSmartCryptoError('INVALID_ARGUMENT');
|
|
21
23
|
}
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
})
|
|
24
|
+
const subtle = getWebCrypto().subtle;
|
|
25
|
+
let privateKeyInfo: Uint8Array | undefined;
|
|
26
|
+
try {
|
|
27
|
+
const generatedKeyPair = await subtle.generateKey(
|
|
28
|
+
{
|
|
29
|
+
name: 'RSASSA-PKCS1-v1_5',
|
|
30
|
+
modulusLength,
|
|
31
|
+
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
|
32
|
+
hash: 'SHA-256',
|
|
33
|
+
},
|
|
34
|
+
true,
|
|
35
|
+
['sign', 'verify'],
|
|
35
36
|
);
|
|
36
|
-
|
|
37
|
-
|
|
37
|
+
privateKeyInfo = new Uint8Array(await subtle.exportKey('pkcs8', generatedKeyPair.privateKey));
|
|
38
|
+
const components = decodePrivateKeyInfo(privateKeyInfo);
|
|
39
|
+
try {
|
|
40
|
+
return new KeyPair({
|
|
41
|
+
privateKey: new PrivateKey(components),
|
|
42
|
+
publicKey: new PublicKey(components),
|
|
43
|
+
});
|
|
44
|
+
} finally {
|
|
45
|
+
zeroRsaPrivateKeyComponents(components);
|
|
46
|
+
}
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (error instanceof SmartCryptoError) {
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
|
|
52
|
+
} finally {
|
|
53
|
+
privateKeyInfo?.fill(0);
|
|
54
|
+
}
|
|
38
55
|
}
|
|
39
56
|
|
|
40
57
|
// INSTANCE
|
|
@@ -1,16 +1,44 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
1
|
+
import { SmartCryptoError, createSmartCryptoError } from './smartcrypto.errors.js';
|
|
2
|
+
import { getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
|
|
3
|
+
import { encodeOpenSshRsaPrivateKey } from './smartcrypto.openssh.js';
|
|
4
|
+
import { decodeFirstPemBlock, encodePem } from './smartcrypto.pem.js';
|
|
3
5
|
import { decryptPrivateKeyInfo, encryptPrivateKeyInfo } from './smartcrypto.pkcs8.js';
|
|
6
|
+
import {
|
|
7
|
+
bitLengthOf,
|
|
8
|
+
copyRsaPrivateKeyComponents,
|
|
9
|
+
decodePrivateKeyInfo,
|
|
10
|
+
decodeRsaPrivateKey,
|
|
11
|
+
encodePrivateKeyInfo,
|
|
12
|
+
encodeRsaPrivateKey,
|
|
13
|
+
type IRsaPrivateKeyComponents,
|
|
14
|
+
} from './smartcrypto.rsa.js';
|
|
15
|
+
|
|
16
|
+
const pkcs1PrivatePemType = 'RSA PRIVATE KEY';
|
|
17
|
+
const pkcs8PrivatePemType = 'PRIVATE KEY';
|
|
4
18
|
|
|
5
19
|
export class PrivateKey {
|
|
6
20
|
// STATIC
|
|
21
|
+
/** Parses an unencrypted RSA private-key PEM; the same as `fromPemString()`. */
|
|
7
22
|
public static createFromPrivateKey(pemString: string) {
|
|
8
|
-
|
|
9
|
-
return new PrivateKey(privateKey);
|
|
23
|
+
return PrivateKey.fromPemString(pemString);
|
|
10
24
|
}
|
|
11
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Parses the first PEM block of `pemString` as an unencrypted PKCS#1
|
|
28
|
+
* (`RSA PRIVATE KEY`) or PKCS#8 (`PRIVATE KEY`) RSA private key.
|
|
29
|
+
* Fails with `INVALID_KEY`.
|
|
30
|
+
*/
|
|
12
31
|
public static fromPemString(pemString: string) {
|
|
13
|
-
|
|
32
|
+
const pemBlock = decodeFirstPemBlock(pemString, [pkcs1PrivatePemType, pkcs8PrivatePemType]);
|
|
33
|
+
try {
|
|
34
|
+
return new PrivateKey(
|
|
35
|
+
pemBlock.type === pkcs1PrivatePemType
|
|
36
|
+
? decodeRsaPrivateKey(pemBlock.body)
|
|
37
|
+
: decodePrivateKeyInfo(pemBlock.body),
|
|
38
|
+
);
|
|
39
|
+
} finally {
|
|
40
|
+
pemBlock.body.fill(0);
|
|
41
|
+
}
|
|
14
42
|
}
|
|
15
43
|
|
|
16
44
|
/**
|
|
@@ -25,21 +53,34 @@ export class PrivateKey {
|
|
|
25
53
|
): Promise<PrivateKey> {
|
|
26
54
|
const privateKeyInfo = await decryptPrivateKeyInfo(pemString, passphraseArg);
|
|
27
55
|
try {
|
|
28
|
-
return new PrivateKey(
|
|
29
|
-
}
|
|
30
|
-
|
|
56
|
+
return new PrivateKey(decodePrivateKeyInfo(privateKeyInfo));
|
|
57
|
+
} finally {
|
|
58
|
+
privateKeyInfo.fill(0);
|
|
31
59
|
}
|
|
32
60
|
}
|
|
33
61
|
|
|
34
62
|
// INSTANCE
|
|
35
|
-
|
|
63
|
+
private readonly components: IRsaPrivateKeyComponents;
|
|
64
|
+
private signingKey?: Promise<CryptoKey>;
|
|
36
65
|
|
|
37
|
-
|
|
38
|
-
|
|
66
|
+
/** Creates a private key from its RFC 8017 integers. Fails with `INVALID_KEY`. */
|
|
67
|
+
constructor(componentsArg: IRsaPrivateKeyComponents) {
|
|
68
|
+
this.components = copyRsaPrivateKeyComponents(componentsArg);
|
|
39
69
|
}
|
|
40
70
|
|
|
71
|
+
/** The RSA modulus length in bits. */
|
|
72
|
+
public get modulusLength(): number {
|
|
73
|
+
return bitLengthOf(this.components.modulus);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Writes an unencrypted PKCS#1 `-----BEGIN RSA PRIVATE KEY-----` PEM (64-column lines, CRLF). */
|
|
41
77
|
public toPemString(): string {
|
|
42
|
-
|
|
78
|
+
const der = encodeRsaPrivateKey(this.components);
|
|
79
|
+
try {
|
|
80
|
+
return encodePem(pkcs1PrivatePemType, der);
|
|
81
|
+
} finally {
|
|
82
|
+
der.fill(0);
|
|
83
|
+
}
|
|
43
84
|
}
|
|
44
85
|
|
|
45
86
|
/**
|
|
@@ -48,15 +89,66 @@ export class PrivateKey {
|
|
|
48
89
|
* PBKDF2-HMAC-SHA256 (600,000 iterations) and AES-256-CBC via WebCrypto.
|
|
49
90
|
*/
|
|
50
91
|
public async toEncryptedPemString(passphraseArg: string): Promise<string> {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
92
|
+
const privateKeyInfo = encodePrivateKeyInfo(this.components);
|
|
93
|
+
try {
|
|
94
|
+
return await encryptPrivateKeyInfo(privateKeyInfo, passphraseArg);
|
|
95
|
+
} finally {
|
|
96
|
+
privateKeyInfo.fill(0);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Signs `dataArg` with RSASSA-PKCS1-v1_5 over SHA-256 (JWS `RS256`) via
|
|
102
|
+
* WebCrypto and returns the signature bytes.
|
|
103
|
+
*/
|
|
104
|
+
public async createRs256Signature(dataArg: Uint8Array): Promise<Uint8Array> {
|
|
105
|
+
if (!(dataArg instanceof Uint8Array)) {
|
|
106
|
+
throw createSmartCryptoError('INVALID_ARGUMENT');
|
|
107
|
+
}
|
|
108
|
+
const subtle = getWebCrypto().subtle;
|
|
109
|
+
const signingKey = await this.getSigningKey();
|
|
110
|
+
try {
|
|
111
|
+
return new Uint8Array(
|
|
112
|
+
await subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, signingKey, toArrayBuffer(dataArg)),
|
|
113
|
+
);
|
|
114
|
+
} catch {
|
|
115
|
+
throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
|
|
116
|
+
}
|
|
57
117
|
}
|
|
58
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Writes an unencrypted OpenSSH private key
|
|
121
|
+
* (`-----BEGIN OPENSSH PRIVATE KEY-----`, `openssh-key-v1`) with the comment
|
|
122
|
+
* `user@host`, as `ssh-keygen` does.
|
|
123
|
+
*/
|
|
59
124
|
public toOpenSSH(): string {
|
|
60
|
-
return
|
|
125
|
+
return encodeOpenSshRsaPrivateKey(this.components, 'user@host');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private async getSigningKey(): Promise<CryptoKey> {
|
|
129
|
+
this.signingKey ??= this.importSigningKey();
|
|
130
|
+
return await this.signingKey;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
private async importSigningKey(): Promise<CryptoKey> {
|
|
134
|
+
const privateKeyInfo = encodePrivateKeyInfo(this.components);
|
|
135
|
+
const privateKeyInfoBuffer = toArrayBuffer(privateKeyInfo);
|
|
136
|
+
try {
|
|
137
|
+
return await getWebCrypto().subtle.importKey(
|
|
138
|
+
'pkcs8',
|
|
139
|
+
privateKeyInfoBuffer,
|
|
140
|
+
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
|
|
141
|
+
false,
|
|
142
|
+
['sign'],
|
|
143
|
+
);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (error instanceof SmartCryptoError) {
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
throw createSmartCryptoError('INVALID_KEY');
|
|
149
|
+
} finally {
|
|
150
|
+
privateKeyInfo.fill(0);
|
|
151
|
+
new Uint8Array(privateKeyInfoBuffer).fill(0);
|
|
152
|
+
}
|
|
61
153
|
}
|
|
62
154
|
}
|
|
@@ -1,17 +1,41 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { bytesEqual, getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
|
|
2
|
+
import { encodeOpenSshRsaPublicKey } from './smartcrypto.openssh.js';
|
|
3
|
+
import { decodeBase64, decodeFirstPemBlock, encodePem } from './smartcrypto.pem.js';
|
|
4
|
+
import {
|
|
5
|
+
bitLengthOf,
|
|
6
|
+
copyRsaPublicKeyComponents,
|
|
7
|
+
decodeRsaPublicKey,
|
|
8
|
+
decodeSubjectPublicKeyInfo,
|
|
9
|
+
encodeRsaPublicKey,
|
|
10
|
+
encodeSubjectPublicKeyInfo,
|
|
11
|
+
type IRsaPublicKeyComponents,
|
|
12
|
+
} from './smartcrypto.rsa.js';
|
|
13
|
+
|
|
14
|
+
const spkiPemType = 'PUBLIC KEY';
|
|
15
|
+
const pkcs1PublicPemType = 'RSA PUBLIC KEY';
|
|
16
|
+
const canonicalPublicKeyErrorPrefix = 'Invalid canonical RSA public key:';
|
|
2
17
|
|
|
3
18
|
const canonicalPublicKeyError = (messageArg: string): Error =>
|
|
4
|
-
new Error(
|
|
19
|
+
new Error(`${canonicalPublicKeyErrorPrefix} ${messageArg}`);
|
|
5
20
|
|
|
6
21
|
export class PublicKey {
|
|
7
22
|
// STATIC
|
|
23
|
+
/** Parses an SPKI or PKCS#1 RSA public-key PEM; despite its name it reads a public key. */
|
|
8
24
|
public static createFromPrivateKey(pemString: string) {
|
|
9
|
-
|
|
10
|
-
return new PublicKey(privateKey);
|
|
25
|
+
return PublicKey.fromPemString(pemString);
|
|
11
26
|
}
|
|
12
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Parses the first PEM block of `pemString` as an SPKI (`PUBLIC KEY`) or
|
|
30
|
+
* PKCS#1 (`RSA PUBLIC KEY`) RSA public key. Fails with `INVALID_KEY`.
|
|
31
|
+
*/
|
|
13
32
|
public static fromPemString(pemString: string) {
|
|
14
|
-
|
|
33
|
+
const pemBlock = decodeFirstPemBlock(pemString, [spkiPemType, pkcs1PublicPemType]);
|
|
34
|
+
return new PublicKey(
|
|
35
|
+
pemBlock.type === spkiPemType
|
|
36
|
+
? decodeSubjectPublicKeyInfo(pemBlock.body)
|
|
37
|
+
: decodeRsaPublicKey(pemBlock.body),
|
|
38
|
+
);
|
|
15
39
|
}
|
|
16
40
|
|
|
17
41
|
/**
|
|
@@ -45,30 +69,27 @@ export class PublicKey {
|
|
|
45
69
|
throw canonicalPublicKeyError('PEM body is malformed');
|
|
46
70
|
}
|
|
47
71
|
|
|
72
|
+
let der: Uint8Array;
|
|
48
73
|
try {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const publicKeyAsn1 = plugins.nodeForge.asn1.fromDer(pemMessage.body, true);
|
|
58
|
-
const publicKey = plugins.nodeForge.pki.publicKeyFromAsn1(publicKeyAsn1);
|
|
59
|
-
if (publicKey.n.bitLength() < 2_048) {
|
|
74
|
+
der = decodeBase64(flattenedBase64);
|
|
75
|
+
} catch {
|
|
76
|
+
throw canonicalPublicKeyError('PEM body is not canonical base64');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
const components = spkiMatch ? decodeSubjectPublicKeyInfo(der) : decodeRsaPublicKey(der);
|
|
81
|
+
if (bitLengthOf(components.modulus) < 2_048) {
|
|
60
82
|
throw canonicalPublicKeyError('RSA modulus must contain at least 2048 bits');
|
|
61
83
|
}
|
|
62
|
-
const
|
|
63
|
-
?
|
|
64
|
-
:
|
|
65
|
-
|
|
66
|
-
if (canonicalDer !== pemMessage.body) {
|
|
84
|
+
const canonicalDer = spkiMatch
|
|
85
|
+
? encodeSubjectPublicKeyInfo(components)
|
|
86
|
+
: encodeRsaPublicKey(components);
|
|
87
|
+
if (!bytesEqual(canonicalDer, der)) {
|
|
67
88
|
throw canonicalPublicKeyError('public-key DER is not canonical');
|
|
68
89
|
}
|
|
69
|
-
return new PublicKey(
|
|
90
|
+
return new PublicKey(components);
|
|
70
91
|
} catch (error) {
|
|
71
|
-
if (error instanceof Error && error.message.startsWith(
|
|
92
|
+
if (error instanceof Error && error.message.startsWith(canonicalPublicKeyErrorPrefix)) {
|
|
72
93
|
throw error;
|
|
73
94
|
}
|
|
74
95
|
throw canonicalPublicKeyError('PEM does not encode a valid RSA public key');
|
|
@@ -76,79 +97,63 @@ export class PublicKey {
|
|
|
76
97
|
}
|
|
77
98
|
|
|
78
99
|
// INSTANCE
|
|
79
|
-
|
|
100
|
+
private readonly components: IRsaPublicKeyComponents;
|
|
101
|
+
private verificationKey?: Promise<CryptoKey>;
|
|
80
102
|
|
|
81
|
-
|
|
82
|
-
|
|
103
|
+
/** Creates a public key from its modulus and public exponent. Fails with `INVALID_KEY`. */
|
|
104
|
+
constructor(componentsArg: IRsaPublicKeyComponents) {
|
|
105
|
+
this.components = copyRsaPublicKeyComponents(componentsArg);
|
|
83
106
|
}
|
|
84
107
|
|
|
108
|
+
/** The RSA modulus length in bits. */
|
|
109
|
+
public get modulusLength(): number {
|
|
110
|
+
return bitLengthOf(this.components.modulus);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Writes an SPKI `-----BEGIN PUBLIC KEY-----` PEM (64-column lines, CRLF). */
|
|
85
114
|
public toPemString(): string {
|
|
86
|
-
return
|
|
115
|
+
return encodePem(spkiPemType, encodeSubjectPublicKeyInfo(this.components));
|
|
87
116
|
}
|
|
88
117
|
|
|
89
118
|
/**
|
|
90
|
-
* Verifies RSASSA-PKCS1-v1_5
|
|
91
|
-
*
|
|
92
|
-
*
|
|
119
|
+
* Verifies an RSASSA-PKCS1-v1_5 signature over SHA-256 with WebCrypto. The
|
|
120
|
+
* platform verifier compares the complete encoded message, so a signature
|
|
121
|
+
* whose DigestInfo names another algorithm or carries extra elements fails.
|
|
122
|
+
* Malformed input and invalid signatures resolve to `false`.
|
|
93
123
|
*/
|
|
94
|
-
public
|
|
124
|
+
public async verifyRs256Signature(dataArg: Uint8Array, signatureArg: Uint8Array): Promise<boolean> {
|
|
95
125
|
if (!(dataArg instanceof Uint8Array) || !(signatureArg instanceof Uint8Array)) {
|
|
96
126
|
return false;
|
|
97
127
|
}
|
|
128
|
+
if (signatureArg.byteLength !== Math.ceil(this.modulusLength / 8)) {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
const subtle = getWebCrypto().subtle;
|
|
98
132
|
try {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
plugins.nodeForge.util.createBuffer(dataArg.slice()).getBytes(),
|
|
105
|
-
'raw',
|
|
106
|
-
);
|
|
107
|
-
const digestInfo = plugins.nodeForge.asn1.create(
|
|
108
|
-
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
109
|
-
plugins.nodeForge.asn1.Type.SEQUENCE,
|
|
110
|
-
true,
|
|
111
|
-
[
|
|
112
|
-
plugins.nodeForge.asn1.create(
|
|
113
|
-
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
114
|
-
plugins.nodeForge.asn1.Type.SEQUENCE,
|
|
115
|
-
true,
|
|
116
|
-
[
|
|
117
|
-
plugins.nodeForge.asn1.create(
|
|
118
|
-
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
119
|
-
plugins.nodeForge.asn1.Type.OID,
|
|
120
|
-
false,
|
|
121
|
-
plugins.nodeForge.asn1.oidToDer(
|
|
122
|
-
plugins.nodeForge.pki.oids.sha256,
|
|
123
|
-
).getBytes(),
|
|
124
|
-
),
|
|
125
|
-
plugins.nodeForge.asn1.create(
|
|
126
|
-
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
127
|
-
plugins.nodeForge.asn1.Type.NULL,
|
|
128
|
-
false,
|
|
129
|
-
'',
|
|
130
|
-
),
|
|
131
|
-
],
|
|
132
|
-
),
|
|
133
|
-
plugins.nodeForge.asn1.create(
|
|
134
|
-
plugins.nodeForge.asn1.Class.UNIVERSAL,
|
|
135
|
-
plugins.nodeForge.asn1.Type.OCTETSTRING,
|
|
136
|
-
false,
|
|
137
|
-
messageDigest.digest().getBytes(),
|
|
138
|
-
),
|
|
139
|
-
],
|
|
140
|
-
);
|
|
141
|
-
return this.forgePublicKey.verify(
|
|
142
|
-
plugins.nodeForge.asn1.toDer(digestInfo).getBytes(),
|
|
143
|
-
plugins.nodeForge.util.createBuffer(signatureArg.slice()).getBytes(),
|
|
144
|
-
'NONE',
|
|
133
|
+
return await subtle.verify(
|
|
134
|
+
{ name: 'RSASSA-PKCS1-v1_5' },
|
|
135
|
+
await this.getVerificationKey(),
|
|
136
|
+
toArrayBuffer(signatureArg),
|
|
137
|
+
toArrayBuffer(dataArg),
|
|
145
138
|
);
|
|
146
139
|
} catch {
|
|
147
140
|
return false;
|
|
148
141
|
}
|
|
149
142
|
}
|
|
150
143
|
|
|
144
|
+
/** Writes an OpenSSH `ssh-rsa` public key line with the comment `user@host`. */
|
|
151
145
|
public toOpenSSH(): string {
|
|
152
|
-
return
|
|
146
|
+
return encodeOpenSshRsaPublicKey(this.components, 'user@host');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private getVerificationKey(): Promise<CryptoKey> {
|
|
150
|
+
this.verificationKey ??= getWebCrypto().subtle.importKey(
|
|
151
|
+
'spki',
|
|
152
|
+
toArrayBuffer(encodeSubjectPublicKeyInfo(this.components)),
|
|
153
|
+
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
|
|
154
|
+
false,
|
|
155
|
+
['verify'],
|
|
156
|
+
);
|
|
157
|
+
return this.verificationKey;
|
|
153
158
|
}
|
|
154
159
|
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
2
|
+
import { concatBytes } from './smartcrypto.internal.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A strict DER reader and writer for the few ASN.1 types that key formats use.
|
|
6
|
+
* Only definite, minimally encoded lengths and single-byte tags are accepted,
|
|
7
|
+
* so every accepted encoding has exactly one byte representation.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const derTags = {
|
|
11
|
+
integer: 0x02,
|
|
12
|
+
bitString: 0x03,
|
|
13
|
+
octetString: 0x04,
|
|
14
|
+
null: 0x05,
|
|
15
|
+
oid: 0x06,
|
|
16
|
+
sequence: 0x30,
|
|
17
|
+
contextSpecificConstructed0: 0xa0,
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
export interface IDerElement {
|
|
21
|
+
tag: number;
|
|
22
|
+
content: Uint8Array;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const invalidKey = () => createSmartCryptoError('INVALID_KEY');
|
|
26
|
+
|
|
27
|
+
/** Reads the element starting at `offsetArg` and returns it with the offset just past it. */
|
|
28
|
+
const readElementAt = (
|
|
29
|
+
bytesArg: Uint8Array,
|
|
30
|
+
offsetArg: number,
|
|
31
|
+
): { element: IDerElement; end: number } => {
|
|
32
|
+
if (offsetArg + 2 > bytesArg.byteLength) {
|
|
33
|
+
throw invalidKey();
|
|
34
|
+
}
|
|
35
|
+
const tag = bytesArg[offsetArg];
|
|
36
|
+
if ((tag & 0x1f) === 0x1f) {
|
|
37
|
+
throw invalidKey();
|
|
38
|
+
}
|
|
39
|
+
const lengthByte = bytesArg[offsetArg + 1];
|
|
40
|
+
let offset = offsetArg + 2;
|
|
41
|
+
let length = lengthByte;
|
|
42
|
+
if (lengthByte & 0x80) {
|
|
43
|
+
const lengthOctets = lengthByte & 0x7f;
|
|
44
|
+
if (lengthOctets < 1 || lengthOctets > 4 || offset + lengthOctets > bytesArg.byteLength) {
|
|
45
|
+
throw invalidKey();
|
|
46
|
+
}
|
|
47
|
+
if (bytesArg[offset] === 0) {
|
|
48
|
+
throw invalidKey();
|
|
49
|
+
}
|
|
50
|
+
length = 0;
|
|
51
|
+
for (let index = 0; index < lengthOctets; index++) {
|
|
52
|
+
length = length * 0x100 + bytesArg[offset + index];
|
|
53
|
+
}
|
|
54
|
+
if (length < 0x80) {
|
|
55
|
+
throw invalidKey();
|
|
56
|
+
}
|
|
57
|
+
offset += lengthOctets;
|
|
58
|
+
}
|
|
59
|
+
const end = offset + length;
|
|
60
|
+
if (end > bytesArg.byteLength) {
|
|
61
|
+
throw invalidKey();
|
|
62
|
+
}
|
|
63
|
+
return { element: { tag, content: bytesArg.subarray(offset, end) }, end };
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** Decodes exactly one DER element that spans all of `bytesArg`. */
|
|
67
|
+
export const decodeDerElement = (bytesArg: Uint8Array): IDerElement => {
|
|
68
|
+
const { element, end } = readElementAt(bytesArg, 0);
|
|
69
|
+
if (end !== bytesArg.byteLength) {
|
|
70
|
+
throw invalidKey();
|
|
71
|
+
}
|
|
72
|
+
return element;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** Decodes the concatenated elements inside a constructed element's content. */
|
|
76
|
+
export const decodeDerChildren = (contentArg: Uint8Array): IDerElement[] => {
|
|
77
|
+
const children: IDerElement[] = [];
|
|
78
|
+
let offset = 0;
|
|
79
|
+
while (offset < contentArg.byteLength) {
|
|
80
|
+
const { element, end } = readElementAt(contentArg, offset);
|
|
81
|
+
children.push(element);
|
|
82
|
+
offset = end;
|
|
83
|
+
}
|
|
84
|
+
return children;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const requireTag = (elementArg: IDerElement | undefined, tagArg: number): IDerElement => {
|
|
88
|
+
if (!elementArg || elementArg.tag !== tagArg) {
|
|
89
|
+
throw invalidKey();
|
|
90
|
+
}
|
|
91
|
+
return elementArg;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
export const readDerSequence = (
|
|
95
|
+
elementArg: IDerElement | undefined,
|
|
96
|
+
minLengthArg: number,
|
|
97
|
+
maxLengthArg: number,
|
|
98
|
+
): IDerElement[] => {
|
|
99
|
+
const children = decodeDerChildren(requireTag(elementArg, derTags.sequence).content);
|
|
100
|
+
if (children.length < minLengthArg || children.length > maxLengthArg) {
|
|
101
|
+
throw invalidKey();
|
|
102
|
+
}
|
|
103
|
+
return children;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Reads a non-negative INTEGER and returns its magnitude without leading zero
|
|
108
|
+
* bytes (zero yields an empty array). Negative values are rejected.
|
|
109
|
+
*/
|
|
110
|
+
export const readDerUnsignedInteger = (elementArg: IDerElement | undefined): Uint8Array => {
|
|
111
|
+
const content = requireTag(elementArg, derTags.integer).content;
|
|
112
|
+
if (content.byteLength < 1 || content[0] & 0x80) {
|
|
113
|
+
throw invalidKey();
|
|
114
|
+
}
|
|
115
|
+
if (content[0] === 0 && content.byteLength > 1 && !(content[1] & 0x80)) {
|
|
116
|
+
throw invalidKey();
|
|
117
|
+
}
|
|
118
|
+
return content.slice(content[0] === 0 ? 1 : 0);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/** Reads a non-negative INTEGER that fits into 31 bits. */
|
|
122
|
+
export const readDerSmallInteger = (elementArg: IDerElement | undefined): number => {
|
|
123
|
+
const magnitude = readDerUnsignedInteger(elementArg);
|
|
124
|
+
if (magnitude.byteLength > 4 || (magnitude.byteLength === 4 && magnitude[0] & 0x80)) {
|
|
125
|
+
throw invalidKey();
|
|
126
|
+
}
|
|
127
|
+
return magnitude.reduce((valueArg, byteArg) => valueArg * 0x100 + byteArg, 0);
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
export const readDerOctetString = (elementArg: IDerElement | undefined): Uint8Array =>
|
|
131
|
+
requireTag(elementArg, derTags.octetString).content.slice();
|
|
132
|
+
|
|
133
|
+
/** Reads a BIT STRING without unused trailing bits. */
|
|
134
|
+
export const readDerBitString = (elementArg: IDerElement | undefined): Uint8Array => {
|
|
135
|
+
const content = requireTag(elementArg, derTags.bitString).content;
|
|
136
|
+
if (content.byteLength < 1 || content[0] !== 0) {
|
|
137
|
+
throw invalidKey();
|
|
138
|
+
}
|
|
139
|
+
return content.slice(1);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
export const readDerNull = (elementArg: IDerElement | undefined): void => {
|
|
143
|
+
if (requireTag(elementArg, derTags.null).content.byteLength !== 0) {
|
|
144
|
+
throw invalidKey();
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
export const readDerOid = (elementArg: IDerElement | undefined): string => {
|
|
149
|
+
const content = requireTag(elementArg, derTags.oid).content;
|
|
150
|
+
if (content.byteLength < 1 || content[content.byteLength - 1] & 0x80) {
|
|
151
|
+
throw invalidKey();
|
|
152
|
+
}
|
|
153
|
+
const arcs: number[] = [];
|
|
154
|
+
let value = 0;
|
|
155
|
+
let arcStart = true;
|
|
156
|
+
for (const byte of content) {
|
|
157
|
+
if (arcStart && byte === 0x80) {
|
|
158
|
+
throw invalidKey();
|
|
159
|
+
}
|
|
160
|
+
if (value > (Number.MAX_SAFE_INTEGER - 0x7f) / 0x80) {
|
|
161
|
+
throw invalidKey();
|
|
162
|
+
}
|
|
163
|
+
value = value * 0x80 + (byte & 0x7f);
|
|
164
|
+
arcStart = !(byte & 0x80);
|
|
165
|
+
if (arcStart) {
|
|
166
|
+
arcs.push(value);
|
|
167
|
+
value = 0;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const first = arcs[0];
|
|
171
|
+
const leadingArcs = first < 40 ? [0, first] : first < 80 ? [1, first - 40] : [2, first - 80];
|
|
172
|
+
return [...leadingArcs, ...arcs.slice(1)].join('.');
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// ========================================
|
|
176
|
+
// Encoding
|
|
177
|
+
// ========================================
|
|
178
|
+
const encodeLength = (lengthArg: number): Uint8Array => {
|
|
179
|
+
if (lengthArg < 0x80) {
|
|
180
|
+
return new Uint8Array([lengthArg]);
|
|
181
|
+
}
|
|
182
|
+
const lengthBytes: number[] = [];
|
|
183
|
+
for (let remaining = lengthArg; remaining > 0; remaining = Math.floor(remaining / 0x100)) {
|
|
184
|
+
lengthBytes.unshift(remaining & 0xff);
|
|
185
|
+
}
|
|
186
|
+
return new Uint8Array([0x80 | lengthBytes.length, ...lengthBytes]);
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export const encodeDerElement = (tagArg: number, contentArg: Uint8Array): Uint8Array =>
|
|
190
|
+
concatBytes(new Uint8Array([tagArg]), encodeLength(contentArg.byteLength), contentArg);
|
|
191
|
+
|
|
192
|
+
export const encodeDerSequence = (...childrenArg: Uint8Array[]): Uint8Array =>
|
|
193
|
+
encodeDerElement(derTags.sequence, concatBytes(...childrenArg));
|
|
194
|
+
|
|
195
|
+
/** Encodes an unsigned magnitude as a minimal non-negative INTEGER. */
|
|
196
|
+
export const encodeDerUnsignedInteger = (magnitudeArg: Uint8Array): Uint8Array => {
|
|
197
|
+
let start = 0;
|
|
198
|
+
while (start < magnitudeArg.byteLength && magnitudeArg[start] === 0) {
|
|
199
|
+
start++;
|
|
200
|
+
}
|
|
201
|
+
const magnitude = magnitudeArg.subarray(start);
|
|
202
|
+
if (magnitude.byteLength === 0 || magnitude[0] & 0x80) {
|
|
203
|
+
return encodeDerElement(derTags.integer, concatBytes(new Uint8Array([0]), magnitude));
|
|
204
|
+
}
|
|
205
|
+
return encodeDerElement(derTags.integer, magnitude);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
export const encodeDerSmallInteger = (valueArg: number): Uint8Array => {
|
|
209
|
+
const magnitude: number[] = [];
|
|
210
|
+
for (let remaining = valueArg; remaining > 0; remaining = Math.floor(remaining / 0x100)) {
|
|
211
|
+
magnitude.unshift(remaining & 0xff);
|
|
212
|
+
}
|
|
213
|
+
return encodeDerUnsignedInteger(new Uint8Array(magnitude));
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
export const encodeDerOctetString = (bytesArg: Uint8Array): Uint8Array =>
|
|
217
|
+
encodeDerElement(derTags.octetString, bytesArg);
|
|
218
|
+
|
|
219
|
+
export const encodeDerBitString = (bytesArg: Uint8Array): Uint8Array =>
|
|
220
|
+
encodeDerElement(derTags.bitString, concatBytes(new Uint8Array([0]), bytesArg));
|
|
221
|
+
|
|
222
|
+
export const encodeDerNull = (): Uint8Array => encodeDerElement(derTags.null, new Uint8Array(0));
|
|
223
|
+
|
|
224
|
+
export const encodeDerOid = (oidArg: string): Uint8Array => {
|
|
225
|
+
const arcs = oidArg.split('.').map(Number);
|
|
226
|
+
const content: number[] = [];
|
|
227
|
+
for (const arc of [arcs[0] * 40 + arcs[1], ...arcs.slice(2)]) {
|
|
228
|
+
const arcBytes = [arc & 0x7f];
|
|
229
|
+
for (let remaining = Math.floor(arc / 0x80); remaining > 0; remaining = Math.floor(remaining / 0x80)) {
|
|
230
|
+
arcBytes.unshift(0x80 | (remaining & 0x7f));
|
|
231
|
+
}
|
|
232
|
+
content.push(...arcBytes);
|
|
233
|
+
}
|
|
234
|
+
return encodeDerElement(derTags.oid, new Uint8Array(content));
|
|
235
|
+
};
|