@virtru/dsp-sdk 0.4.0 → 0.5.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.
Files changed (49) hide show
  1. package/.rush/temp/chunked-rush-logs/dsp-sdk._phase_build.chunks.jsonl +4 -2
  2. package/.rush/temp/chunked-rush-logs/dsp-sdk._phase_test.chunks.jsonl +355 -13
  3. package/.rush/temp/package-deps__phase_build.json +17 -9
  4. package/.rush/temp/shrinkwrap-deps.json +148 -150
  5. package/CHANGELOG.json +42 -0
  6. package/CHANGELOG.md +15 -1
  7. package/README.md +14 -8
  8. package/dist/src/lib/fips-crypto/asymmetric.d.ts +35 -0
  9. package/dist/src/lib/fips-crypto/asymmetric.js +116 -0
  10. package/dist/src/lib/fips-crypto/key-format.d.ts +51 -0
  11. package/dist/src/lib/fips-crypto/key-format.js +233 -0
  12. package/dist/src/lib/fips-crypto/keys.d.ts +26 -0
  13. package/dist/src/lib/fips-crypto/keys.js +123 -0
  14. package/dist/src/lib/fips-crypto/primitives.d.ts +41 -0
  15. package/dist/src/lib/fips-crypto/primitives.js +105 -0
  16. package/dist/src/lib/fips-crypto/symmetric.d.ts +61 -0
  17. package/dist/src/lib/fips-crypto/symmetric.js +152 -0
  18. package/dist/src/lib/fips-crypto-service.d.ts +5 -0
  19. package/dist/src/lib/fips-crypto-service.js +44 -0
  20. package/dist/src/lib/utils.d.ts +8 -2
  21. package/dist/src/lib/utils.js +8 -9
  22. package/dist/tests/fips-crypto.unit.test.d.ts +1 -0
  23. package/dist/tests/fips-crypto.unit.test.js +258 -0
  24. package/dist/tests/setup-unit.d.ts +7 -0
  25. package/dist/tests/setup-unit.js +70 -0
  26. package/lib-commonjs/src/lib/fips-crypto/asymmetric.js +126 -0
  27. package/lib-commonjs/src/lib/fips-crypto/key-format.js +243 -0
  28. package/lib-commonjs/src/lib/fips-crypto/keys.js +134 -0
  29. package/lib-commonjs/src/lib/fips-crypto/primitives.js +112 -0
  30. package/lib-commonjs/src/lib/fips-crypto/symmetric.js +162 -0
  31. package/lib-commonjs/src/lib/fips-crypto-service.js +57 -0
  32. package/lib-commonjs/src/lib/utils.js +8 -9
  33. package/lib-commonjs/tests/fips-crypto.unit.test.js +260 -0
  34. package/lib-commonjs/tests/setup-unit.js +72 -0
  35. package/package.json +12 -7
  36. package/public/virtru.wasm +0 -0
  37. package/src/lib/fips-crypto/asymmetric.ts +162 -0
  38. package/src/lib/fips-crypto/key-format.ts +287 -0
  39. package/src/lib/fips-crypto/keys.ts +190 -0
  40. package/src/lib/fips-crypto/primitives.ts +197 -0
  41. package/src/lib/fips-crypto/symmetric.ts +213 -0
  42. package/src/lib/fips-crypto-service.ts +58 -0
  43. package/src/lib/utils.test.ts +11 -8
  44. package/src/lib/utils.ts +14 -13
  45. package/temp/build/lint/_eslint-5eVG3S6w.json +9 -1
  46. package/tests/fips-crypto.unit.test.ts +412 -0
  47. package/tests/setup-unit.ts +108 -0
  48. package/tsconfig.json +1 -1
  49. package/vitest.config.ts +22 -6
@@ -0,0 +1,258 @@
1
+ /*
2
+ * Copyright (c) Virtru Corporation. All rights reserved.
3
+ *
4
+ * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
5
+ */
6
+ import { expect, test, beforeAll, afterAll, describe } from 'vitest';
7
+ import { Binary, } from '@opentdf/sdk/singlecontainer';
8
+ import { FipsCryptoService, unwrapPublicKey, unwrapPrivateKey, importPrivateKey, exportPrivateKeyPem, } from '../src/lib/fips-crypto-service';
9
+ describe('FIPS CryptoService - Methods', () => {
10
+ // RSA key slots are finite in the WASM keystore. Each describe group that
11
+ // uses RSA keys creates ONE shared key pair in beforeAll and releases it in
12
+ // afterAll so slots are reclaimed before the next group starts.
13
+ describe('sign and verify (asymmetric)', () => {
14
+ let keyPair;
15
+ beforeAll(async () => {
16
+ keyPair = await FipsCryptoService.generateSigningKeyPair();
17
+ }, 60000);
18
+ afterAll(() => {
19
+ unwrapPublicKey(keyPair.publicKey).release();
20
+ });
21
+ test('should sign and verify with RS256', async () => {
22
+ const data = new Uint8Array([1, 2, 3, 4, 5]);
23
+ const signature = await FipsCryptoService.sign(data, keyPair.privateKey, 'RS256');
24
+ const isValid = await FipsCryptoService.verify(data, signature, keyPair.publicKey, 'RS256');
25
+ expect(isValid).toBe(true);
26
+ });
27
+ test('should reject tampered data', async () => {
28
+ const data = new Uint8Array([1, 2, 3, 4, 5]);
29
+ const signature = await FipsCryptoService.sign(data, keyPair.privateKey, 'RS256');
30
+ const tamperedData = new Uint8Array([1, 2, 3, 4, 6]);
31
+ const isValid = await FipsCryptoService.verify(tamperedData, signature, keyPair.publicKey, 'RS256');
32
+ expect(isValid).toBe(false);
33
+ });
34
+ test('should throw error for ES256 (EC not supported)', async () => {
35
+ await expect(FipsCryptoService.sign(new Uint8Array([1, 2, 3, 4]), keyPair.privateKey, 'ES256')).rejects.toThrow('not supported in FIPS mode');
36
+ });
37
+ test('encryption key pair (RSA-OAEP) should not be usable for signing', async () => {
38
+ // Catches algorithm mismatch: if generateKeyPair() incorrectly used
39
+ // RSASSA-PKCS1-v1_5 params, signing would succeed here instead of throwing.
40
+ const encKeyPair = await FipsCryptoService.generateKeyPair();
41
+ await expect(FipsCryptoService.sign(new Uint8Array([1, 2, 3]), encKeyPair.privateKey, 'RS256')).rejects.toThrow();
42
+ unwrapPublicKey(encKeyPair.publicKey).release();
43
+ unwrapPrivateKey(encKeyPair.privateKey).release();
44
+ });
45
+ });
46
+ describe('hmac and verifyHmac', () => {
47
+ test('should compute and verify HMAC-SHA256', async () => {
48
+ const crypto = FipsCryptoService;
49
+ const keyBytes = await crypto.randomBytes(32);
50
+ const symKey = await crypto.importSymmetricKey(keyBytes);
51
+ const data = new Uint8Array([1, 2, 3, 4, 5]);
52
+ const signature = await crypto.hmac(data, symKey);
53
+ const isValid = await crypto.verifyHmac(data, signature, symKey);
54
+ expect(isValid).toBe(true);
55
+ });
56
+ test('should reject invalid signature', async () => {
57
+ const crypto = FipsCryptoService;
58
+ const symKey = await crypto.generateKey(32);
59
+ const data = new Uint8Array([1, 2, 3, 4]);
60
+ const signature = await crypto.hmac(data, symKey);
61
+ signature[0] ^= 1; // Flip a bit
62
+ const isValid = await crypto.verifyHmac(data, signature, symKey);
63
+ expect(isValid).toBe(false);
64
+ });
65
+ test('should reject signature with wrong key', async () => {
66
+ const crypto = FipsCryptoService;
67
+ const symKey1 = await crypto.importSymmetricKey(await crypto.randomBytes(32));
68
+ const symKey2 = await crypto.importSymmetricKey(await crypto.randomBytes(32));
69
+ const data = new Uint8Array([1, 2, 3, 4]);
70
+ const signature = await crypto.hmac(data, symKey1);
71
+ const isValid = await crypto.verifyHmac(data, signature, symKey2);
72
+ expect(isValid).toBe(false);
73
+ });
74
+ });
75
+ describe('digest', () => {
76
+ test('should compute SHA-256 hash', async () => {
77
+ const data = new Uint8Array([1, 2, 3, 4]);
78
+ const hash = await FipsCryptoService.digest('SHA-256', data);
79
+ expect(hash).toBeInstanceOf(Uint8Array);
80
+ expect(hash.byteLength).toBe(32);
81
+ });
82
+ test('should produce consistent hashes', async () => {
83
+ const data = new Uint8Array([1, 2, 3, 4]);
84
+ const hash1 = await FipsCryptoService.digest('SHA-256', data);
85
+ const hash2 = await FipsCryptoService.digest('SHA-256', data);
86
+ expect(hash1).toEqual(hash2);
87
+ });
88
+ test('should throw error for SHA-384 (not supported)', async () => {
89
+ await expect(FipsCryptoService.digest('SHA-384', new Uint8Array([1, 2, 3, 4]))).rejects.toThrow('not supported in FIPS mode');
90
+ });
91
+ });
92
+ describe('EC placeholder methods', () => {
93
+ test('should throw error for generateECKeyPair', async () => {
94
+ await expect(FipsCryptoService.generateECKeyPair()).rejects.toThrow('not supported in FIPS mode');
95
+ });
96
+ test('should throw error for deriveKeyFromECDH', async () => {
97
+ await expect(FipsCryptoService.deriveKeyFromECDH({}, {}, {
98
+ hash: 'SHA-256',
99
+ salt: new Uint8Array(),
100
+ })).rejects.toThrow('not supported in FIPS mode');
101
+ });
102
+ });
103
+ describe('exportPublicKeyPem', () => {
104
+ let keyPair;
105
+ beforeAll(async () => {
106
+ keyPair = await FipsCryptoService.generateKeyPair();
107
+ }, 60000);
108
+ afterAll(() => {
109
+ unwrapPublicKey(keyPair.publicKey).release();
110
+ });
111
+ test('should export generated public key to PEM', async () => {
112
+ const pem = await FipsCryptoService.exportPublicKeyPem(keyPair.publicKey);
113
+ expect(pem).toContain('-----BEGIN PUBLIC KEY-----');
114
+ expect(pem).toContain('-----END PUBLIC KEY-----');
115
+ });
116
+ });
117
+ describe('importPublicKey', () => {
118
+ let keyPair;
119
+ let importedKey;
120
+ beforeAll(async () => {
121
+ const crypto = FipsCryptoService;
122
+ keyPair = await crypto.generateKeyPair(2048);
123
+ const pem = await crypto.exportPublicKeyPem(keyPair.publicKey);
124
+ importedKey = await crypto.importPublicKey(pem, { usage: 'encrypt' });
125
+ }, 60000);
126
+ afterAll(() => {
127
+ unwrapPublicKey(keyPair.publicKey).release();
128
+ unwrapPublicKey(importedKey).release();
129
+ });
130
+ test('should import PEM and detect RSA-2048', () => {
131
+ expect(importedKey.algorithm).toBe('rsa:2048');
132
+ });
133
+ });
134
+ describe('exportPublicKeyJwk', () => {
135
+ let keyPair;
136
+ beforeAll(async () => {
137
+ keyPair = await FipsCryptoService.generateKeyPair(2048);
138
+ }, 60000);
139
+ afterAll(() => {
140
+ unwrapPublicKey(keyPair.publicKey).release();
141
+ });
142
+ test('should export public key to JWK', async () => {
143
+ const jwk = await FipsCryptoService.exportPublicKeyJwk(keyPair.publicKey);
144
+ expect(jwk.kty).toBe('RSA');
145
+ expect(jwk.n).toBeDefined();
146
+ expect(jwk.e).toBeDefined();
147
+ expect(typeof jwk.n).toBe('string');
148
+ expect(typeof jwk.e).toBe('string');
149
+ });
150
+ test('should produce a JWK that round-trips back to SPKI', async () => {
151
+ const jwk = await FipsCryptoService.exportPublicKeyJwk(keyPair.publicKey);
152
+ const webKey = await globalThis.crypto.subtle.importKey('jwk', jwk, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, true, ['verify']);
153
+ const spki = await globalThis.crypto.subtle.exportKey('spki', webKey);
154
+ expect(spki.byteLength).toBeGreaterThan(0);
155
+ });
156
+ });
157
+ describe('encrypt and decrypt (symmetric AES-GCM)', () => {
158
+ test('should round-trip encrypt/decrypt', async () => {
159
+ const key = await FipsCryptoService.generateKey();
160
+ const iv = Binary.fromArrayBuffer((await FipsCryptoService.randomBytes(12)).buffer);
161
+ const plaintext = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
162
+ const { payload: cipher, authTag } = await FipsCryptoService.encrypt(Binary.fromArrayBuffer(plaintext.buffer), key, iv);
163
+ const { payload: recovered } = await FipsCryptoService.decrypt(cipher, key, iv, undefined, authTag);
164
+ expect(new Uint8Array(recovered.asArrayBuffer())).toEqual(plaintext);
165
+ });
166
+ test('should produce different ciphertext for different IVs', async () => {
167
+ const key = await FipsCryptoService.generateKey();
168
+ const plaintext = Binary.fromArrayBuffer(new Uint8Array([1, 2, 3, 4]).buffer);
169
+ const iv1 = Binary.fromArrayBuffer((await FipsCryptoService.randomBytes(12)).buffer);
170
+ const iv2 = Binary.fromArrayBuffer((await FipsCryptoService.randomBytes(12)).buffer);
171
+ const { payload: cipher1 } = await FipsCryptoService.encrypt(plaintext, key, iv1);
172
+ const { payload: cipher2 } = await FipsCryptoService.encrypt(plaintext, key, iv2);
173
+ expect(new Uint8Array(cipher1.asArrayBuffer())).not.toEqual(new Uint8Array(cipher2.asArrayBuffer()));
174
+ });
175
+ });
176
+ describe('encryptWithPublicKey and decryptWithPrivateKey (RSA-OAEP)', () => {
177
+ let keyPair;
178
+ beforeAll(async () => {
179
+ keyPair = await FipsCryptoService.generateKeyPair();
180
+ }, 60000);
181
+ afterAll(() => {
182
+ unwrapPublicKey(keyPair.publicKey).release();
183
+ });
184
+ test('should round-trip RSA encrypt/decrypt', async () => {
185
+ const plaintext = new Uint8Array([10, 20, 30, 40, 50]);
186
+ const encrypted = await FipsCryptoService.encryptWithPublicKey(Binary.fromArrayBuffer(plaintext.buffer), keyPair.publicKey);
187
+ const decrypted = await FipsCryptoService.decryptWithPrivateKey(encrypted, keyPair.privateKey);
188
+ expect(new Uint8Array(decrypted.asArrayBuffer())).toEqual(plaintext);
189
+ });
190
+ test('should produce different ciphertext each call (RSA-OAEP is randomized)', async () => {
191
+ const payload = Binary.fromArrayBuffer(new Uint8Array([1, 2, 3]).buffer);
192
+ const enc1 = await FipsCryptoService.encryptWithPublicKey(payload, keyPair.publicKey);
193
+ const enc2 = await FipsCryptoService.encryptWithPublicKey(payload, keyPair.publicKey);
194
+ expect(new Uint8Array(enc1.asArrayBuffer())).not.toEqual(new Uint8Array(enc2.asArrayBuffer()));
195
+ });
196
+ test('signing key pair (RSASSA-PKCS1-v1_5) should not be usable for encryption', async () => {
197
+ // Catches algorithm mismatch: if generateSigningKeyPair() incorrectly used
198
+ // RSA-OAEP params, encryption would succeed here instead of throwing.
199
+ const signingKp = await FipsCryptoService.generateSigningKeyPair();
200
+ await expect(FipsCryptoService.encryptWithPublicKey(Binary.fromArrayBuffer(new Uint8Array([1, 2, 3]).buffer), signingKp.publicKey)).rejects.toThrow();
201
+ unwrapPublicKey(signingKp.publicKey).release();
202
+ unwrapPrivateKey(signingKp.privateKey).release();
203
+ });
204
+ });
205
+ describe('importPrivateKey and exportPrivateKeyPem', () => {
206
+ let privKey;
207
+ beforeAll(async () => {
208
+ const kp = await globalThis.crypto.subtle.generateKey({
209
+ name: 'RSASSA-PKCS1-v1_5',
210
+ modulusLength: 2048,
211
+ publicExponent: new Uint8Array([1, 0, 1]),
212
+ hash: 'SHA-256',
213
+ }, true, ['sign', 'verify']);
214
+ const pkcs8 = await globalThis.crypto.subtle.exportKey('pkcs8', kp.privateKey);
215
+ const b64 = btoa(String.fromCharCode(...new Uint8Array(pkcs8)));
216
+ const pem = `-----BEGIN PRIVATE KEY-----\n${b64
217
+ .match(/.{1,64}/g)
218
+ .join('\n')}\n-----END PRIVATE KEY-----`;
219
+ privKey = await importPrivateKey(pem, {
220
+ usage: 'sign',
221
+ extractable: true,
222
+ });
223
+ }, 60000);
224
+ afterAll(() => {
225
+ unwrapPrivateKey(privKey).release();
226
+ });
227
+ test('should import PKCS#8 PEM private key', () => {
228
+ expect(privKey.algorithm).toBe('rsa:2048');
229
+ });
230
+ test('should export imported private key back to PEM', async () => {
231
+ const exported = await exportPrivateKeyPem(privKey);
232
+ expect(exported).toContain('-----BEGIN PRIVATE KEY-----');
233
+ expect(exported).toContain('-----END PRIVATE KEY-----');
234
+ });
235
+ });
236
+ describe('splitSymmetricKey and mergeSymmetricKeys', () => {
237
+ test('splitSymmetricKey with 1 share returns the same key (single-KAS identity)', async () => {
238
+ const key = await FipsCryptoService.generateKey();
239
+ const shares = await FipsCryptoService.splitSymmetricKey(key, 1);
240
+ expect(shares).toHaveLength(1);
241
+ expect(shares[0]).toBe(key);
242
+ });
243
+ test('mergeSymmetricKeys with 1 share returns the same key (single-KAS identity)', async () => {
244
+ const key = await FipsCryptoService.generateKey();
245
+ const merged = await FipsCryptoService.mergeSymmetricKeys([key]);
246
+ expect(merged).toBe(key);
247
+ });
248
+ test('splitSymmetricKey with 2 shares throws (multi-KAS not yet supported)', async () => {
249
+ const key = await FipsCryptoService.generateKey();
250
+ await expect(FipsCryptoService.splitSymmetricKey(key, 2)).rejects.toThrow('not yet supported in FIPS mode');
251
+ });
252
+ test('mergeSymmetricKeys with 2 shares throws (multi-KAS not yet supported)', async () => {
253
+ const key1 = await FipsCryptoService.generateKey();
254
+ const key2 = await FipsCryptoService.generateKey();
255
+ await expect(FipsCryptoService.mergeSymmetricKeys([key1, key2])).rejects.toThrow('not yet supported in FIPS mode');
256
+ });
257
+ });
258
+ });
@@ -0,0 +1,7 @@
1
+ declare global {
2
+ interface Window {
3
+ Module: unknown;
4
+ VirtruFipsWasmLib?: unknown;
5
+ }
6
+ }
7
+ export {};
@@ -0,0 +1,70 @@
1
+ /*
2
+ * Copyright (c) Virtru Corporation. All rights reserved.
3
+ *
4
+ * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
5
+ */
6
+ import { Buffer } from 'buffer';
7
+ import { access, readFile } from 'node:fs/promises';
8
+ import path from 'node:path';
9
+ import { TextEncoder, TextDecoder } from 'node:util';
10
+ globalThis.Buffer = Buffer;
11
+ if (!globalThis.TextEncoder) {
12
+ globalThis.TextEncoder = TextEncoder;
13
+ }
14
+ if (!globalThis.TextDecoder) {
15
+ globalThis.TextDecoder = TextDecoder;
16
+ }
17
+ if (typeof window !== 'undefined' && !window.Module) {
18
+ window.Module = {};
19
+ }
20
+ // Prefer the copied local WASM artifact used by package scripts.
21
+ const copiedWasmFilePath = path.resolve(process.cwd(), 'public/virtru.wasm');
22
+ // Fallback for direct local runs when copy-wasm has not been executed.
23
+ const sourceWasmFilePath = path.resolve(process.cwd(), '../fips-crypto-js/src/utils/virtru.wasm');
24
+ let resolvedWasmFilePath = copiedWasmFilePath;
25
+ try {
26
+ await access(copiedWasmFilePath);
27
+ }
28
+ catch {
29
+ resolvedWasmFilePath = sourceWasmFilePath;
30
+ }
31
+ const originalFetch = globalThis.fetch;
32
+ globalThis.fetch = async function (input, init) {
33
+ const url = typeof input === 'string'
34
+ ? input
35
+ : input instanceof URL
36
+ ? input.href
37
+ : input.url;
38
+ if (url && url.includes('virtru.wasm')) {
39
+ const wasmBytes = await readFile(resolvedWasmFilePath);
40
+ return new Response(wasmBytes, {
41
+ status: 200,
42
+ headers: {
43
+ 'content-type': 'application/wasm',
44
+ },
45
+ });
46
+ }
47
+ return originalFetch(input, init);
48
+ };
49
+ await import('@virtru-private/fips-crypto-js');
50
+ const isFipsReady = (candidate) => {
51
+ return (!!candidate &&
52
+ typeof candidate === 'object' &&
53
+ 'isInitialized' in candidate &&
54
+ candidate.isInitialized === true &&
55
+ 'generateKey' in candidate &&
56
+ typeof candidate.generateKey === 'function');
57
+ };
58
+ if (!isFipsReady(window.VirtruFipsWasmLib)) {
59
+ await new Promise((resolve, reject) => {
60
+ const timeout = setTimeout(() => reject(new Error('Timeout waiting for VirtruCrypto WASM initialization in unit setup.')), 10000);
61
+ const onReady = () => {
62
+ clearTimeout(timeout);
63
+ resolve();
64
+ };
65
+ window.addEventListener('wasmReady', onReady, { once: true });
66
+ });
67
+ }
68
+ if (!isFipsReady(window.VirtruFipsWasmLib)) {
69
+ throw new Error('VirtruCrypto was loaded but not initialized in unit setup.');
70
+ }
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) Virtru Corporation. All rights reserved.
4
+ *
5
+ * Your use of this file is governed by the Virtu Terms of Service <https://www.virtru.com/terms-of-service/>.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.generateKeyPair = generateKeyPair;
9
+ exports.generateSigningKeyPair = generateSigningKeyPair;
10
+ exports.encryptWithPublicKey = encryptWithPublicKey;
11
+ exports.decryptWithPrivateKey = decryptWithPrivateKey;
12
+ exports.sign = sign;
13
+ exports.verify = verify;
14
+ exports.generateECKeyPair = generateECKeyPair;
15
+ exports.deriveKeyFromECDH = deriveKeyFromECDH;
16
+ const singlecontainer_1 = require("@opentdf/sdk/singlecontainer");
17
+ const singlecontainer_2 = require("@opentdf/sdk/singlecontainer");
18
+ const sdk_1 = require("@opentdf/sdk");
19
+ const primitives_1 = require("./primitives");
20
+ const keys_1 = require("./keys");
21
+ // ─── Key Generation ───────────────────────────────────────────────────────────
22
+ const ENC_DEC_METHODS = ['encrypt', 'decrypt'];
23
+ const SIGN_VERIFY_METHODS = ['sign', 'verify'];
24
+ const RSA_OAEP_PARAMS = {
25
+ name: 'RSA-OAEP',
26
+ modulusLength: 2048,
27
+ publicExponent: [1, 0, 1],
28
+ hash: 'SHA-256',
29
+ };
30
+ const RS256_PARAMS = {
31
+ name: 'RSASSA-PKCS1-v1_5',
32
+ modulusLength: 2048,
33
+ publicExponent: [1, 0, 1],
34
+ hash: 'SHA-256',
35
+ };
36
+ /**
37
+ * Generate an RSA key pair for encryption/decryption (RSA-OAEP).
38
+ *
39
+ * VirtruCrypto generates a single combined keypair handle. Both the PublicKey
40
+ * and PrivateKey opaque wrappers reference the same VirtruCryptoKey — the
41
+ * handle already carries all necessary usages. No export/re-import needed.
42
+ */
43
+ async function generateKeyPair(_size) {
44
+ const crypto = await (0, primitives_1.getVirtruCrypto)();
45
+ const combined = await crypto.generateKey(RSA_OAEP_PARAMS, true, ENC_DEC_METHODS);
46
+ return (0, keys_1.wrapKeyPair)(combined, combined, 'rsa:2048');
47
+ }
48
+ /**
49
+ * Generate an RSA key pair for signing/verification (RSASSA-PKCS1-v1_5).
50
+ */
51
+ async function generateSigningKeyPair() {
52
+ const crypto = await (0, primitives_1.getVirtruCrypto)();
53
+ const combined = await crypto.generateKey(RS256_PARAMS, true, SIGN_VERIFY_METHODS);
54
+ return (0, keys_1.wrapKeyPair)(combined, combined, 'rsa:2048');
55
+ }
56
+ // ─── RSA Encrypt / Decrypt ────────────────────────────────────────────────────
57
+ /**
58
+ * Encrypt with RSA-OAEP public key.
59
+ * Accepts Binary payload or a SymmetricKey for key-wrapping.
60
+ */
61
+ async function encryptWithPublicKey(payload, publicKey) {
62
+ const crypto = await (0, primitives_1.getVirtruCrypto)();
63
+ let payloadBytes;
64
+ if ((0, keys_1.isSymmetricKey)(payload)) {
65
+ payloadBytes = await crypto.exportKey('raw', (0, keys_1.unwrapSymmetricKey)(payload));
66
+ }
67
+ else {
68
+ payloadBytes = new Uint8Array(payload.asArrayBuffer());
69
+ }
70
+ const vKey = (0, keys_1.unwrapPublicKey)(publicKey);
71
+ const encrypted = await crypto.encrypt(RSA_OAEP_PARAMS, vKey, payloadBytes);
72
+ return singlecontainer_1.Binary.fromArrayBuffer(encrypted.buffer);
73
+ }
74
+ /**
75
+ * Decrypt with RSA-OAEP private key.
76
+ */
77
+ async function decryptWithPrivateKey(encryptedPayload, privateKey) {
78
+ const crypto = await (0, primitives_1.getVirtruCrypto)();
79
+ const vKey = (0, keys_1.unwrapPrivateKey)(privateKey);
80
+ const payloadBytes = new Uint8Array(encryptedPayload.asArrayBuffer());
81
+ const decrypted = await crypto.decrypt(RSA_OAEP_PARAMS, vKey, payloadBytes);
82
+ return singlecontainer_1.Binary.fromArrayBuffer(decrypted.buffer);
83
+ }
84
+ // ─── Sign / Verify ────────────────────────────────────────────────────────────
85
+ /**
86
+ * Sign data with an RSA private key (RS256 only).
87
+ * VirtruCrypto requires pre-hashed data, so the data is SHA-256 hashed first.
88
+ */
89
+ async function sign(data, privateKey, algorithm) {
90
+ if (algorithm !== 'RS256') {
91
+ throw new sdk_1.ConfigurationError(`Signing algorithm '${algorithm}' not supported in FIPS mode. Only RS256 is supported.`);
92
+ }
93
+ const crypto = await (0, primitives_1.getVirtruCrypto)();
94
+ const vKey = (0, keys_1.unwrapPrivateKey)(privateKey);
95
+ // VirtruCrypto signs a pre-computed hash, not raw data
96
+ const hash = await crypto.digest({ name: 'SHA-256' }, data);
97
+ const sig = await crypto.sign(RS256_PARAMS, vKey, new Uint8Array(hash));
98
+ return new Uint8Array(sig);
99
+ }
100
+ /**
101
+ * Verify an RS256 signature.
102
+ * VirtruCrypto requires pre-hashed data.
103
+ */
104
+ async function verify(data, signature, publicKey, algorithm) {
105
+ if (algorithm !== 'RS256') {
106
+ throw new sdk_1.ConfigurationError(`Verification algorithm '${algorithm}' not supported in FIPS mode. Only RS256 is supported.`);
107
+ }
108
+ const crypto = await (0, primitives_1.getVirtruCrypto)();
109
+ const vKey = (0, keys_1.unwrapPublicKey)(publicKey);
110
+ const hash = await crypto.digest({ name: 'SHA-256' }, data);
111
+ try {
112
+ return await crypto.verify(RS256_PARAMS, vKey, signature, new Uint8Array(hash));
113
+ }
114
+ catch (e) {
115
+ if (e === 'Signature verification error')
116
+ return false;
117
+ throw e;
118
+ }
119
+ }
120
+ // ─── EC Stubs (unsupported in FIPS mode) ─────────────────────────────────────
121
+ async function generateECKeyPair(_curve) {
122
+ throw new sdk_1.ConfigurationError('EC key generation is not supported in FIPS mode.');
123
+ }
124
+ async function deriveKeyFromECDH(_privateKey, _publicKey, _hkdfParams) {
125
+ throw new sdk_1.ConfigurationError('ECDH key derivation is not supported in FIPS mode.');
126
+ }