Skip to content
File

Blob: src/workerd/api/tests/crypto-impl-asymmetric-test.js

javascript113 lines
1// Copyright (c) 2023 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5import * as assert from 'node:assert';
6 
7export const rsa_reject_infinite_loop_test = {
8 async test(ctrl, env, ctx) {
9 // Check that parameters that may cause an infinite loop in RSA key generation are rejected.
10 await assert.rejects(
11 crypto.subtle.generateKey(
12 {
13 name: 'RSASSA-PKCS1-v1_5',
14 hash: 'SHA-256',
15 modulusLength: 1024,
16 publicExponent: new Uint8Array([1]),
17 },
18 false,
19 ['sign', 'verify']
20 ),
21 { message: 'The "publicExponent" must be either 3 or 65537, but got 1.' }
22 );
23 
24 await assert.rejects(
25 crypto.subtle.generateKey(
26 {
27 name: 'RSA-PSS',
28 hash: 'SHA-256',
29 modulusLength: 1024,
30 publicExponent: new Uint8Array([1]),
31 },
32 false,
33 ['sign', 'verify']
34 ),
35 { message: 'The "publicExponent" must be either 3 or 65537, but got 1.' }
36 );
37 },
38};
39 
40export const eddsa_test = {
41 async test(ctrl, env, ctx) {
42 // Test EDDSA ED25519 generateKey
43 const edKey = await crypto.subtle.generateKey(
44 {
45 name: 'NODE-ED25519',
46 namedCurve: 'NODE-ED25519',
47 },
48 false,
49 ['sign', 'verify']
50 );
51 assert.ok(edKey.publicKey.algorithm.name == 'NODE-ED25519');
52 },
53};
54 
55export const publicExponent_type_test = {
56 async test(ctrl, env, ctx) {
57 const key = await crypto.subtle.generateKey(
58 {
59 name: 'RSA-PSS',
60 hash: 'SHA-256',
61 modulusLength: 1024,
62 publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
63 },
64 false,
65 ['sign', 'verify']
66 );
67 
68 // Check that a Uint8Array is used for publicExponent. Without the
69 // crypto_preserve_public_exponent feature flag, this would incorrectly return an ArrayBuffer.
70 assert.ok(
71 key.publicKey.algorithm.publicExponent[Symbol.toStringTag] == 'Uint8Array'
72 );
73 },
74};
75 
76export const ecdhJwkTest = {
77 async test() {
78 const publicJwk = {
79 kty: 'EC',
80 crv: 'P-256',
81 alg: 'THIS CAN BE ANYTHING',
82 x: 'Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0',
83 y: 'HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw',
84 };
85 
86 // The import should succeed with no errors.
87 // Refs: https://github.com/cloudflare/workerd/issues/1403
88 await crypto.subtle.importKey(
89 'jwk',
90 publicJwk,
91 { name: 'ECDH', namedCurve: 'P-256' },
92 true,
93 []
94 );
95 },
96};
97 
98export const rsaAlgTest = {
99 async test() {
100 const v3 = { kty: 'RSA' };
101 Object.defineProperty(v3, 'alg', {
102 writable: true,
103 configurable: true,
104 value: 1024n,
105 });
106 const v7 = { name: 'RSA-OAEP', hash: 'SHA-1' };
107 const v8 = [];
108 await assert.rejects(crypto.subtle.importKey('jwk', v3, v7, 6, v8), {
109 message: /Unrecognized or unimplemented algorithm "1024"/,
110 });
111 },
112};