Lightpanda: the headless browser designed for AI and automation
webapi: RSASSA-PKCS1-v1_5 (generateKey, import, export, sign, verify)
orezraey181fe0e6239c
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.htmlindex 7623c6142..e9a2578ee 100644--- a/src/browser/tests/crypto.html+++ b/src/browser/tests/crypto.html@@ -153,13 +153,22 @@});</script>+<script>+ // A throwaway 2048-bit RSA key pair (spki public + pkcs8 private), for the+ // RSA-OAEP and RSASSA-PKCS1-v1_5 import tests.+ {+ const fromB64 = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));+ window.rsaTestKey = {+ spki: fromB64("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2J6+FUn6SF2o4+6vj6jbsGfumBrlZIS7OTRmw3sJOzvinrDRQ3hf+TmCgBSHcGbohHTItgB8mfM1MMbsIggYjbNSs+bRhVmbtMFS3GxBsrNt+YvaEMF0C3sdYi6+gWZqJYrfEF/a8HT2+IZQJ5B7PsIOoVPWlDkaLQBPlQDgK0JJQJ+1mOI8dXHz9PaPXB1v9/w3nUpRV6bdy9Iui453XnoY8ajIKy0bzk12160PxZM4vAvrvdmTY12BwkGsim+7iqNlLjU6fJKb4D0766YfroGDPhxd3sDqxLteQeA64oIcqeQzDq89843DS1VeGwv+nrwNHCy3cAmLVaytk4vECQIDAQAB"),+ pkcs8: fromB64("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDYnr4VSfpIXajj7q+PqNuwZ+6YGuVkhLs5NGbDewk7O+KesNFDeF/5OYKAFIdwZuiEdMi2AHyZ8zUwxuwiCBiNs1Kz5tGFWZu0wVLcbEGys235i9oQwXQLex1iLr6BZmolit8QX9rwdPb4hlAnkHs+wg6hU9aUORotAE+VAOArQklAn7WY4jx1cfP09o9cHW/3/DedSlFXpt3L0i6LjndeehjxqMgrLRvOTXbXrQ/Fkzi8C+u92ZNjXYHCQayKb7uKo2UuNTp8kpvgPTvrph+ugYM+HF3ewOrEu15B4Drighyp5DMOrz3zjcNLVV4bC/6evA0cLLdwCYtVrK2Ti8QJAgMBAAECggEAHW4z1SCf6IURFSawo4wFjQoR2IiO8gE2jqcX7ycgMfQI7haH1+ra3zl5CX3AiPzySkyzmEaopyHr8ByWqGkBLP9YFSke/kcWaJB7eYcbxfOq1WSy0+P0qDqp21UOfPY1JbSgadEcJd8+TrWw3i87D2O+KR0C4lB/xe1s4omj6zxuSMOL3igRtu+pSem3e5Wb/lid2OIAskxgt+RiyRSPsajBunhah4WxhY0NQIt5WK0kiNfpd8vz3qVTnF8t5oPPWLvdHIApDHLOkbeX+0XA5XeJojdPgN/vdInuXYoFp/VF6Jc+nAgCOEDI/+JPQ+Jpoy1FJoB5fZimivPvGbXrIQKBgQDup6Y/+zRYIRCN8VpcUBuvQHLbE17UDTrVrSh8fqPJpAWvNPrYZb+tG23cuPec4FIGoadjwiuFgsXs9lXv0qPxcgTyR6l0RzrDWNmt8HvPRrgEIJEwv+BT+heRUecaXHSvG1vCam06MkjgFLvnCJ7hEVCNf4+irhLCNV+J9TnZ4wKBgQDoXR6WdVCDEHz+PBsfzcINbRxyWLPIJmULcngqpeQ3UyrxWXxXR2BKuVrOZq5Dn9XcmP/zZ9u4eCI2Nst4eLlzQIxXDxsj62Y/5yAc9tw4nzTvxPaKf7orBMrRjYSmj9vOrpYIlVjV+cPRBfjxfRonSDf3kWlUS62GFweeDQo+IwKBgQDiMJ8PEOVhiaUJAvEjgQFcLnctT8SWshtLHZy7scNGf2Cr2EjPBFCQnuiXQ+/bDXhwtJHTqNpa5cD1f9ufO0MKuYgaoPToMgJt1y4o/z45C8uojb1OOO1Cakwf/UJN58bnl8R2FSyE9dfAGaalp7P9mM2B7p6SDu3Uh4WPWY6FBQKBgHINgv4HB0XNygxgJFAwBpfgfp4Bu/z6G47K2QDV/HbLc8CTU9zjQ/hpkpDNBaxbv/VPhBJNYCPjk6dYrfasCxrvC/OPjprK6J1lLPYKlX2VZ75oxzqkBxUmfQbul7XJ1vJT74C3Dau5tMvcSpz98uBlKlNyJGkj3EB8/VguvmBRAoGBAJFSOHauuxGtvw64JnMEkUL9vnjuryyH6CcXgSP6SMY58O2KL/nMEGeAYguwrkl5CdoN2zrWr8/I8cr1UrkKHtzsQHrCYlA6LaZaHDUdxCEIyarO7z18ZXzi32HRol1UFjpQTVg2N9t9rGqC2Hg+hg2D0kGJCwf/t8Uydc2tiTh/"),+ };+ }+</script>+<script id=rsa-oaep-import type=module>const state = await testing.async();- const fromB64 = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));- // A throwaway 2048-bit RSA key pair (spki public + pkcs8 private) for the- // import path: encrypt with the imported public key, decrypt with the private.- const spki = fromB64("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2J6+FUn6SF2o4+6vj6jbsGfumBrlZIS7OTRmw3sJOzvinrDRQ3hf+TmCgBSHcGbohHTItgB8mfM1MMbsIggYjbNSs+bRhVmbtMFS3GxBsrNt+YvaEMF0C3sdYi6+gWZqJYrfEF/a8HT2+IZQJ5B7PsIOoVPWlDkaLQBPlQDgK0JJQJ+1mOI8dXHz9PaPXB1v9/w3nUpRV6bdy9Iui453XnoY8ajIKy0bzk12160PxZM4vAvrvdmTY12BwkGsim+7iqNlLjU6fJKb4D0766YfroGDPhxd3sDqxLteQeA64oIcqeQzDq89843DS1VeGwv+nrwNHCy3cAmLVaytk4vECQIDAQAB");- const pkcs8 = fromB64("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDYnr4VSfpIXajj7q+PqNuwZ+6YGuVkhLs5NGbDewk7O+KesNFDeF/5OYKAFIdwZuiEdMi2AHyZ8zUwxuwiCBiNs1Kz5tGFWZu0wVLcbEGys235i9oQwXQLex1iLr6BZmolit8QX9rwdPb4hlAnkHs+wg6hU9aUORotAE+VAOArQklAn7WY4jx1cfP09o9cHW/3/DedSlFXpt3L0i6LjndeehjxqMgrLRvOTXbXrQ/Fkzi8C+u92ZNjXYHCQayKb7uKo2UuNTp8kpvgPTvrph+ugYM+HF3ewOrEu15B4Drighyp5DMOrz3zjcNLVV4bC/6evA0cLLdwCYtVrK2Ti8QJAgMBAAECggEAHW4z1SCf6IURFSawo4wFjQoR2IiO8gE2jqcX7ycgMfQI7haH1+ra3zl5CX3AiPzySkyzmEaopyHr8ByWqGkBLP9YFSke/kcWaJB7eYcbxfOq1WSy0+P0qDqp21UOfPY1JbSgadEcJd8+TrWw3i87D2O+KR0C4lB/xe1s4omj6zxuSMOL3igRtu+pSem3e5Wb/lid2OIAskxgt+RiyRSPsajBunhah4WxhY0NQIt5WK0kiNfpd8vz3qVTnF8t5oPPWLvdHIApDHLOkbeX+0XA5XeJojdPgN/vdInuXYoFp/VF6Jc+nAgCOEDI/+JPQ+Jpoy1FJoB5fZimivPvGbXrIQKBgQDup6Y/+zRYIRCN8VpcUBuvQHLbE17UDTrVrSh8fqPJpAWvNPrYZb+tG23cuPec4FIGoadjwiuFgsXs9lXv0qPxcgTyR6l0RzrDWNmt8HvPRrgEIJEwv+BT+heRUecaXHSvG1vCam06MkjgFLvnCJ7hEVCNf4+irhLCNV+J9TnZ4wKBgQDoXR6WdVCDEHz+PBsfzcINbRxyWLPIJmULcngqpeQ3UyrxWXxXR2BKuVrOZq5Dn9XcmP/zZ9u4eCI2Nst4eLlzQIxXDxsj62Y/5yAc9tw4nzTvxPaKf7orBMrRjYSmj9vOrpYIlVjV+cPRBfjxfRonSDf3kWlUS62GFweeDQo+IwKBgQDiMJ8PEOVhiaUJAvEjgQFcLnctT8SWshtLHZy7scNGf2Cr2EjPBFCQnuiXQ+/bDXhwtJHTqNpa5cD1f9ufO0MKuYgaoPToMgJt1y4o/z45C8uojb1OOO1Cakwf/UJN58bnl8R2FSyE9dfAGaalp7P9mM2B7p6SDu3Uh4WPWY6FBQKBgHINgv4HB0XNygxgJFAwBpfgfp4Bu/z6G47K2QDV/HbLc8CTU9zjQ/hpkpDNBaxbv/VPhBJNYCPjk6dYrfasCxrvC/OPjprK6J1lLPYKlX2VZ75oxzqkBxUmfQbul7XJ1vJT74C3Dau5tMvcSpz98uBlKlNyJGkj3EB8/VguvmBRAoGBAJFSOHauuxGtvw64JnMEkUL9vnjuryyH6CcXgSP6SMY58O2KL/nMEGeAYguwrkl5CdoN2zrWr8/I8cr1UrkKHtzsQHrCYlA6LaZaHDUdxCEIyarO7z18ZXzi32HRol1UFjpQTVg2N9t9rGqC2Hg+hg2D0kGJCwf/t8Uydc2tiTh/");+ // Encrypt with the imported public key, decrypt with the private.+ const { spki, pkcs8 } = rsaTestKey;const publicKey = await crypto.subtle.importKey("spki", spki, { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);const privateKey = await crypto.subtle.importKey("pkcs8", pkcs8, { name: "RSA-OAEP", hash: "SHA-256" }, false, ["decrypt"]);// Hash names match case-insensitively and are reported in canonical form.@@ -404,6 +413,255 @@});</script>+<script id=rsassa-sign-verify type=module>+ const state = await testing.async();+ const subtle = crypto.subtle;+ const algo = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };+ const b64 = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf)));+ const data = new TextEncoder().encode("lightpanda rsassa");++ // PKCS #1 v1.5 signatures are deterministic: this key signs `data` with+ // SHA-256 into exactly what OpenSSL (and Chrome) produce.+ const expected = "YxvJD9uFamAy2GThpElvfytCcmRnlmcCl36q5MwolJh+cjT0rsSPoWcNU5u/fPEaZ4XNfnIsTKPktylb2tDmflEjpSjm83Fbcgcky2whEpfrdFoUK2Yu+WaXQBSAxGA6pcx7Gi+KCYvBdmVu81EVLFzNk67uwWyZLYLZYpq884b6rLFVWGCJz463JnzM20SmxecH+pxMotoN4obkAqc3X75Me5PRbgboF6i2nFmC0pUbdolKv+oF4ndsiUlbTOj7p7JY0RM5tube/ZZDi1cGLBNib3aSPEFUDAt7JKMZrZTfXgkZ780QMw/C5rwhRZupdeSUP9ChTNBLDxb0NKFuEQ==";+ const privateKey = await subtle.importKey("pkcs8", rsaTestKey.pkcs8, algo, false, ["sign"]);+ const publicKey = await subtle.importKey("spki", rsaTestKey.spki, algo, false, ["verify"]);+ const signature = await subtle.sign("RSASSA-PKCS1-v1_5", privateKey, data);+ // The name matches case-insensitively, and the hash is the key's.+ const lowerName = await subtle.sign({ name: "rsassa-pkcs1-v1_5" }, privateKey, data);+ const sha512Key = await subtle.importKey("pkcs8", rsaTestKey.pkcs8, { ...algo, hash: "sha-512" }, false, ["sign"]);+ const sha512Public = await subtle.importKey("spki", rsaTestKey.spki, { ...algo, hash: "SHA-512" }, false, ["verify"]);+ const sha512Signature = await subtle.sign(algo, sha512Key, data);++ const tampered = new Uint8Array(signature.slice(0));+ tampered[10] ^= 1;+ const results = {+ valid: await subtle.verify(algo, publicKey, signature, data),+ lowerName: await subtle.verify({ name: "rsassa-pkcs1-v1_5" }, publicKey, signature, data),+ otherData: await subtle.verify(algo, publicKey, signature, new TextEncoder().encode("lightpanda rsassb")),+ tampered: await subtle.verify(algo, publicKey, tampered, data),+ // A signature of the wrong length is invalid, not an error.+ truncated: await subtle.verify(algo, publicKey, signature.slice(0, 255), data),+ empty: await subtle.verify(algo, publicKey, new Uint8Array(0), data),+ tooLong: await subtle.verify(algo, publicKey, new Uint8Array(512), data),+ // Each key verifies with its own hash only.+ sha512Valid: await subtle.verify(algo, sha512Public, sha512Signature, data),+ sha512WithSha256: await subtle.verify(algo, sha512Public, signature, data),+ };++ // A generated pair: the private half signs, the public half verifies.+ const pair = await subtle.generateKey(+ { ...algo, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) },+ true,+ ["sign", "verify"],+ );+ const generatedSignature = await subtle.sign(algo, pair.privateKey, data);+ const generatedValid = await subtle.verify(algo, pair.publicKey, generatedSignature, data);+ // Only "sign" asked for: the public key has no usages.+ const signOnly = await subtle.generateKey(+ { ...algo, modulusLength: 1024, publicExponent: new Uint8Array([3]) },+ true,+ ["sign"],+ );++ state.resolve();+ await state.done(() => {+ testing.expectEqual(expected, b64(signature));+ testing.expectEqual(expected, b64(lowerName));+ testing.expectEqual(true, results.valid);+ testing.expectEqual(true, results.lowerName);+ testing.expectEqual(false, results.otherData);+ testing.expectEqual(false, results.tampered);+ testing.expectEqual(false, results.truncated);+ testing.expectEqual(false, results.empty);+ testing.expectEqual(false, results.tooLong);+ testing.expectEqual(true, results.sha512Valid);+ testing.expectEqual(false, results.sha512WithSha256);+ testing.expectEqual(false, b64(sha512Signature) === expected);+ testing.expectEqual("RSASSA-PKCS1-v1_5", privateKey.algorithm.name);+ testing.expectEqual("SHA-512", sha512Key.algorithm.hash.name);+ testing.expectEqual(2048, publicKey.algorithm.modulusLength);+ testing.expectEqual(128, generatedSignature.byteLength);+ testing.expectEqual(true, generatedValid);+ testing.expectEqual("RSASSA-PKCS1-v1_5", pair.publicKey.algorithm.name);+ testing.expectEqual("SHA-256", pair.publicKey.algorithm.hash.name);+ testing.expectEqual("sign", pair.privateKey.usages.join(","));+ testing.expectEqual("verify", pair.publicKey.usages.join(","));+ testing.expectEqual("3", signOnly.publicKey.algorithm.publicExponent.join(","));+ testing.expectEqual("", signOnly.publicKey.usages.join(","));+ });+</script>++<script id=rsassa-export type=module>+ const state = await testing.async();+ const subtle = crypto.subtle;+ const algo = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };+ const hex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");+ const data = new TextEncoder().encode("exported key path");+ const { privateKey, publicKey } = await subtle.generateKey(+ { ...algo, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) },+ true,+ ["sign", "verify"],+ );+ const roundTrip = async (priv, pub) => subtle.verify(algo, pub, await subtle.sign(algo, priv, data), data);++ // DER: spki and pkcs8 survive an import/export round trip byte for byte.+ const spki = await subtle.exportKey("spki", publicKey);+ const pkcs8 = await subtle.exportKey("pkcs8", privateKey);+ const spkiKey = await subtle.importKey("spki", spki, algo, true, ["verify"]);+ const pkcs8Key = await subtle.importKey("pkcs8", pkcs8, algo, true, ["sign"]);++ // JWK: "sig" keys whose `alg` is RS<bits of the hash>.+ const publicJwk = await subtle.exportKey("jwk", publicKey);+ const privateJwk = await subtle.exportKey("jwk", privateKey);+ const jwkPublicKey = await subtle.importKey("jwk", publicJwk, algo, true, ["verify"]);+ const jwkPrivateKey = await subtle.importKey("jwk", privateJwk, algo, true, ["sign"]);+ const withUse = await subtle.importKey("jwk", { ...publicJwk, use: "sig" }, algo, true, ["verify"]);+ const algs = [];+ for (const hash of ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]) {+ const key = await subtle.importKey("jwk", { kty: "RSA", n: publicJwk.n, e: publicJwk.e }, { ...algo, hash }, true, ["verify"]);+ const { alg } = await subtle.exportKey("jwk", key);+ await subtle.importKey("jwk", { kty: "RSA", n: publicJwk.n, e: publicJwk.e, alg }, { ...algo, hash }, true, ["verify"]);+ algs.push(alg);+ }++ // A key travels as a wrapped JWK and still signs once unwrapped.+ const wrapper = await subtle.generateKey({ name: "AES-GCM", length: 128 }, true, ["wrapKey", "unwrapKey"]);+ const gcm = { name: "AES-GCM", iv: new Uint8Array(12) };+ const wrapped = await subtle.wrapKey("jwk", privateKey, wrapper, gcm);+ const unwrapped = await subtle.unwrapKey("jwk", wrapped, wrapper, gcm, algo, false, ["sign"]);++ const results = {+ spkiAgain: hex(await subtle.exportKey("spki", spkiKey)),+ pkcs8Again: hex(await subtle.exportKey("pkcs8", pkcs8Key)),+ privateJwkAgain: JSON.stringify(await subtle.exportKey("jwk", jwkPrivateKey)),+ viaSpki: await roundTrip(privateKey, spkiKey),+ viaPkcs8: await roundTrip(pkcs8Key, publicKey),+ viaJwk: await roundTrip(jwkPrivateKey, jwkPublicKey),+ viaUse: await roundTrip(privateKey, withUse),+ viaUnwrap: await roundTrip(unwrapped, publicKey),+ };++ state.resolve();+ await state.done(() => {+ testing.expectEqual(hex(spki), results.spkiAgain);+ testing.expectEqual(hex(pkcs8), results.pkcs8Again);+ testing.expectEqual("RSA,RS256,AQAB,true", [publicJwk.kty, publicJwk.alg, publicJwk.e, publicJwk.ext].join(","));+ testing.expectEqual("verify", publicJwk.key_ops.join(","));+ testing.expectEqual("sign", privateJwk.key_ops.join(","));+ testing.expectEqual(JSON.stringify(privateJwk), results.privateJwkAgain);+ testing.expectEqual("RS1,RS256,RS384,RS512", algs.join(","));+ testing.expectEqual("RSASSA-PKCS1-v1_5", jwkPrivateKey.algorithm.name);+ testing.expectEqual("RSASSA-PKCS1-v1_5", unwrapped.algorithm.name);+ testing.expectEqual(true, results.viaSpki);+ testing.expectEqual(true, results.viaPkcs8);+ testing.expectEqual(true, results.viaJwk);+ testing.expectEqual(true, results.viaUse);+ testing.expectEqual(true, results.viaUnwrap);+ });+</script>++<script id=rsassa-errors type=module>+ const state = await testing.async();+ const subtle = crypto.subtle;+ const errorName = async (fn) => {+ try {+ await fn();+ return null;+ } catch (err) {+ return err.name;+ }+ };+ const algo = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };+ const data = new TextEncoder().encode("hi");+ const gen = (name, usages) => subtle.generateKey(+ { name, hash: "SHA-256", modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) },+ true,+ usages,+ );+ const rsassa = await gen("RSASSA-PKCS1-v1_5", ["sign", "verify"]);+ const oaep = await gen("RSA-OAEP", ["encrypt", "decrypt", "wrapKey", "unwrapKey"]);+ const hmac = await subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, true, ["sign", "verify"]);+ const signature = await subtle.sign(algo, rsassa.privateKey, data);+ // A 512-bit modulus is too short for a SHA-512 DigestInfo.+ const small = await subtle.generateKey(+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-512", modulusLength: 512, publicExponent: new Uint8Array([1, 0, 1]) },+ true,+ ["sign"],+ );+ const publicJwk = await subtle.exportKey("jwk", rsassa.publicKey);+ const { key_ops: _publicOps, ...pubNoOps } = publicJwk;+ const importPublic = (jwk, usages = ["verify"]) => errorName(() => subtle.importKey("jwk", jwk, algo, true, usages));++ const results = {+ // Each half does its own operation only.+ signWithPublic: await errorName(() => subtle.sign(algo, rsassa.publicKey, data)),+ verifyWithPrivate: await errorName(() => subtle.verify(algo, rsassa.privateKey, signature, data)),+ // A signature libcrypto can't produce.+ tooSmall: await errorName(() => subtle.sign("RSASSA-PKCS1-v1_5", small.privateKey, data)),+ // The algorithm must be one that signs, and the key's own.+ unknownName: await errorName(() => subtle.sign("RSA", rsassa.privateKey, data)),+ oaepName: await errorName(() => subtle.sign("RSA-OAEP", oaep.privateKey, data)),+ hmacNameOnRsa: await errorName(() => subtle.sign("HMAC", rsassa.privateKey, data)),+ rsaNameOnHmac: await errorName(() => subtle.sign(algo, hmac, data)),+ rsaVerifyOnHmac: await errorName(() => subtle.verify(algo, hmac, signature, data)),+ rsaNameOnOaep: await errorName(() => subtle.sign(algo, oaep.privateKey, data)),+ // RSASSA-PKCS1-v1_5 keys don't encrypt or wrap, and RSA-OAEP keys don't sign.+ encryptName: await errorName(() => subtle.encrypt(algo, rsassa.publicKey, data)),+ oaepOnRsassa: await errorName(() => subtle.encrypt({ name: "RSA-OAEP" }, rsassa.publicKey, data)),+ wrapName: await errorName(() => subtle.wrapKey("jwk", hmac, rsassa.publicKey, algo)),+ // Import: spki keys verify, pkcs8 keys sign, and a private key needs a usage.+ spkiForSign: await errorName(() => subtle.importKey("spki", rsaTestKey.spki, algo, true, ["sign"])),+ pkcs8ForVerify: await errorName(() => subtle.importKey("pkcs8", rsaTestKey.pkcs8, algo, true, ["verify"])),+ pkcs8NoUsages: await errorName(() => subtle.importKey("pkcs8", rsaTestKey.pkcs8, algo, true, [])),+ spkiNoUsages: await errorName(() => subtle.importKey("spki", rsaTestKey.spki, algo, true, [])),+ noHash: await errorName(() => subtle.importKey("spki", rsaTestKey.spki, "RSASSA-PKCS1-v1_5", true, ["verify"])),+ badHash: await errorName(() => subtle.importKey("spki", rsaTestKey.spki, { ...algo, hash: "SHA-224" }, true, ["verify"])),+ // RSA-PSS isn't implemented yet.+ pss: await errorName(() => subtle.importKey("spki", rsaTestKey.spki, { name: "RSA-PSS", hash: "SHA-256" }, true, ["verify"])),+ // Generation: the private key must get "sign". RSA-PSS isn't implemented yet.+ verifyOnly: await errorName(() => gen("RSASSA-PKCS1-v1_5", ["verify"])),+ pssGenerate: await errorName(() => gen("RSA-PSS", ["sign", "verify"])),+ // JWK: a "sig" key whose `alg` names the requested hash.+ publicForSign: await importPublic(pubNoOps, ["sign"]),+ useEnc: await importPublic({ ...publicJwk, use: "enc" }),+ algOtherHash: await importPublic({ ...publicJwk, alg: "RS384" }),+ algLower: await importPublic({ ...publicJwk, alg: "rs256" }),+ algOaep: await importPublic({ ...publicJwk, alg: "RSA-OAEP-256" }),+ algPss: await importPublic({ ...publicJwk, alg: "PS256" }),+ };++ state.resolve();+ await state.done(() => {+ testing.expectEqual("InvalidAccessError", results.signWithPublic);+ testing.expectEqual("InvalidAccessError", results.verifyWithPrivate);+ testing.expectEqual("OperationError", results.tooSmall);+ testing.expectEqual("NotSupportedError", results.unknownName);+ testing.expectEqual("NotSupportedError", results.oaepName);+ testing.expectEqual("InvalidAccessError", results.hmacNameOnRsa);+ testing.expectEqual("InvalidAccessError", results.rsaNameOnHmac);+ testing.expectEqual("InvalidAccessError", results.rsaVerifyOnHmac);+ testing.expectEqual("InvalidAccessError", results.rsaNameOnOaep);+ testing.expectEqual("NotSupportedError", results.encryptName);+ testing.expectEqual("InvalidAccessError", results.oaepOnRsassa);+ testing.expectEqual("NotSupportedError", results.wrapName);+ testing.expectEqual("SyntaxError", results.spkiForSign);+ testing.expectEqual("SyntaxError", results.pkcs8ForVerify);+ testing.expectEqual("SyntaxError", results.pkcs8NoUsages);+ testing.expectEqual(null, results.spkiNoUsages);+ testing.expectEqual("TypeError", results.noHash);+ testing.expectEqual("NotSupportedError", results.badHash);+ testing.expectEqual("NotSupportedError", results.pss);+ testing.expectEqual("SyntaxError", results.verifyOnly);+ testing.expectEqual("NotSupportedError", results.pssGenerate);+ testing.expectEqual("SyntaxError", results.publicForSign);+ testing.expectEqual("DataError", results.useEnc);+ testing.expectEqual("DataError", results.algOtherHash);+ testing.expectEqual("DataError", results.algLower);+ testing.expectEqual("DataError", results.algOaep);+ testing.expectEqual("DataError", results.algPss);+ });+</script>+<script id=wrap-unwrap type=module>const state = await testing.async();const subtle = crypto.subtle;diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zigindex 73aac52e2..6af3b1e0d 100644--- a/src/browser/webapi/SubtleCrypto.zig+++ b/src/browser/webapi/SubtleCrypto.zig@@ -140,17 +140,17 @@ pub fn importKey(};return EC.import(name, algo.namedCurve(), format, der, is_private, extractable, mask, exec);}- if (RSA.canonicalName(name) != null) {- const hash_name = importHash(algo) orelse return local.typeError("RSA-OAEP import requires a hash");+ if (RSA.scheme(name)) |scheme| {+ const hash_name = importHash(algo) orelse return local.typeError("RSA import requires a hash");const is_jwk = std.mem.eql(u8, format, "jwk");switch (key_data) {.bytes => |b| {if (is_jwk) return local.typeError("jwk format expects an object");- return RSA.import(format, b.values, hash_name, is_private, extractable, mask, exec);+ return RSA.import(scheme, format, b.values, hash_name, is_private, extractable, mask, exec);},.jwk => |jwk| {if (!is_jwk) return local.typeError("this format expects a BufferSource");- return RSA.importJwk(jwk, hash_name, extractable, mask, exec);+ return RSA.importJwk(scheme, jwk, hash_name, extractable, mask, exec);},}}@@ -218,7 +218,7 @@ pub fn importKey(return error.NotSupported;}-/// The hash of an importKey algorithm that carries one (HMAC, RSA-OAEP): those+/// The hash of an importKey algorithm that carries one (HMAC, RSA): those/// params {name, hash} match the `.hmac` variant of the Import union (same/// shape), so the hash is read there. Null for the other variants.fn importHash(algo: algorithm.Import) ?[]const u8 {@@ -247,9 +247,10 @@ fn importKind(format: []const u8, key_data: algorithm.KeyData) bool {return false;}-/// The usages permitted for an EC/OKP key of the given privacy, or null if the-/// algorithm isn't one of the asymmetric algorithms handled here. Real key-/// import for these isn't implemented yet — this only drives usage validation.+/// The usages permitted for an EC/OKP/RSA key of the given privacy, or null if+/// the algorithm isn't one of the asymmetric algorithms handled here. Only EC+/// and RSA import their keys; for the others this only drives usage+/// validation.fn asymmetricAllowedUsages(name: []const u8, is_private: bool) ?[]const []const u8 {if (eqlIgnoreCase(name, "ECDSA") or eqlIgnoreCase(name, "Ed25519") or eqlIgnoreCase(name, "Ed448")) {return if (is_private) &.{"sign"} else &.{"verify"};@@ -257,8 +258,8 @@ fn asymmetricAllowedUsages(name: []const u8, is_private: bool) ?[]const []constif (eqlIgnoreCase(name, "ECDH") or eqlIgnoreCase(name, "X25519") or eqlIgnoreCase(name, "X448")) {return if (is_private) &.{ "deriveKey", "deriveBits" } else &.{};}- if (eqlIgnoreCase(name, "RSA-OAEP")) {- return if (is_private) &.{ "decrypt", "unwrapKey" } else &.{ "encrypt", "wrapKey" };+ if (RSA.scheme(name)) |scheme| {+ return if (is_private) scheme.private_usages else scheme.public_usages;}return null;}@@ -575,7 +576,7 @@ const CryptUse = enum {/// and the wrapKey/unwrapKey usage.fn checkWrappingKey(algo: algorithm.Encrypt, wrapping_key: *const CryptoKey, use: CryptUse) !void {const name = algo.algoName();- if (RSA.canonicalName(name) == null and AES.canonicalName(name) == null) {+ if (!eqlIgnoreCase(name, "RSA-OAEP") and AES.canonicalName(name) == null) {return error.NotSupported;}if (!eqlIgnoreCase(name, wrapping_key._algorithm.name)) {@@ -614,8 +615,9 @@ fn cryptBytes(// RSA-OAEP is handled before the switch: it may arrive as a bare string// ("RSA-OAEP"), which would hit `.name => NotSupported` below. An RSA key// used with another algorithm's name falls through to AES.crypt, which- // rejects the key type.- if (RSA.canonicalName(name) != null) {+ // rejects the key type. The other RSA algorithms don't encrypt, and end+ // up NotSupported below.+ if (eqlIgnoreCase(name, "RSA-OAEP")) {const label: []const u8 = switch (algo) {.params => |p| if (p.label) |l| l.values else "",.name => "",@@ -649,14 +651,19 @@ pub fn sign(data: []const u8, // ArrayBuffer.exec: *const Execution,) !js.Promise {- return switch (key._type) {+ const local = exec.js.local.?;+ switch (key._type) {// Call sign for HMAC..hmac => return HMAC.sign(algo, key, data, exec),+ .rsa => {+ try checkSigningKey(algo, key, CryptoKey.Usages.sign);+ return local.resolvePromise(js.ArrayBuffer{ .values = try RSA.sign(key, data, exec) });+ },else => {log.debug(.not_implemented, "SubtleCrypto.sign", .{ .key_type = key._type });return error.InvalidAccessError;},- };+ }}/// Verify a digital signature.@@ -668,14 +675,38 @@ pub fn verify(data: []const u8, // ArrayBuffer.exec: *const Execution,) !js.Promise {- if (!algo.isHMAC()) {- return error.InvalidAccessError;+ const local = exec.js.local.?;+ switch (key._type) {+ .hmac => {+ if (!algo.isHMAC()) {+ return error.InvalidAccessError;+ }+ return HMAC.verify(key, signature, data, exec);+ },+ .rsa => {+ try checkSigningKey(algo, key, CryptoKey.Usages.verify);+ return local.resolvePromise(try RSA.verify(key, signature, data));+ },+ else => return error.InvalidAccessError,}+}- return switch (key._type) {- .hmac => HMAC.verify(key, signature, data, exec),- else => error.InvalidAccessError,- };+/// The checks sign/verify make before the algorithm's own, in the spec's+/// order: an algorithm that signs (else NotSupported), the key's own algorithm,+/// and the sign or verify usage (else InvalidAccessError).+fn checkSigningKey(algo: algorithm.Sign, key: *const CryptoKey, usage: u8) !void {+ const name = algo.algoName();+ const signing = [_][]const u8{ "HMAC", "RSASSA-PKCS1-v1_5", "RSA-PSS", "ECDSA", "Ed25519", "Ed448" };+ for (signing) |s| {+ if (eqlIgnoreCase(name, s)) break;+ } else return error.NotSupported;++ if (!eqlIgnoreCase(name, key._algorithm.name)) {+ return error.InvalidAccessError;+ }+ if (key._usages & usage == 0) {+ return error.InvalidAccessError;+ }}/// `digest()` accepts an AlgorithmIdentifier: either a bare string (`"SHA-256"`)diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zigindex bdecd51ae..7a4e5ac52 100644--- a/src/browser/webapi/crypto/RSA.zig+++ b/src/browser/webapi/crypto/RSA.zig@@ -16,10 +16,11 @@// You should have received a copy of the GNU Affero General Public License// along with this program. If not, see <https://www.gnu.org/licenses/>.-//! RSA-OAEP: key generation, import and export (spki/pkcs8 DER and JWK), and-//! the encrypt/decrypt operations. The key material lives as a libcrypto-//! EVP_PKEY in `CryptoKey._vary.pkey`. See EC.zig for the asymmetric-key-//! rationale.+//! RSA-OAEP and RSASSA-PKCS1-v1_5: key generation, import and export+//! (spki/pkcs8 DER and JWK), the encrypt/decrypt operations of RSA-OAEP and+//! the sign/verify operations of RSASSA-PKCS1-v1_5. The key material lives as+//! a libcrypto EVP_PKEY in `CryptoKey._vary.pkey`. See EC.zig for the+//! asymmetric-key rationale.const std = @import("std");@@ -84,52 +85,77 @@ fn isValidPublicExponent(bytes: []const u8) bool {return false;}-/// The registered name (case-insensitive), or null if not an RSA-OAEP algorithm.-pub fn canonicalName(name: []const u8) ?[]const u8 {- if (eql(name, "RSA-OAEP")) return "RSA-OAEP";+/// What sets the RSA algorithms implemented here apart: the usages of each+/// half of a key pair and the JWK members that describe their keys.+pub const Scheme = struct {+ name: []const u8,+ private_usages: []const []const u8,+ public_usages: []const []const u8,+ /// The JWK `use` of the keys.+ jwk_use: []const u8,+ /// The JWK `alg` for each of `hashes`: the values of JWA, sections 3.1 and+ /// 4.1, and WebCrypto's "RS1" for RSASSA-PKCS1-v1_5 with SHA-1.+ jwk_algs: [hashes.len][]const u8,+};++const schemes = [_]Scheme{+ .{+ .name = "RSA-OAEP",+ .private_usages = &.{ "decrypt", "unwrapKey" },+ .public_usages = &.{ "encrypt", "wrapKey" },+ .jwk_use = "enc",+ .jwk_algs = .{ "RSA-OAEP", "RSA-OAEP-256", "RSA-OAEP-384", "RSA-OAEP-512" },+ },+ .{+ .name = "RSASSA-PKCS1-v1_5",+ .private_usages = &.{"sign"},+ .public_usages = &.{"verify"},+ .jwk_use = "sig",+ .jwk_algs = .{ "RS1", "RS256", "RS384", "RS512" },+ },+};++/// The scheme of an RSA algorithm name (case-insensitive), or null if it isn't+/// one implemented here.+pub fn scheme(name: []const u8) ?*const Scheme {+ for (&schemes) |*s| {+ if (eql(name, s.name)) return s;+ }return null;}+const hashes = [_][]const u8{ "SHA-1", "SHA-256", "SHA-384", "SHA-512" };+/// The registered hash name (case-insensitive), or null if not a supported/// hash. Stored on the key, so `.algorithm.hash.name` reports it and/// `findDigest` (which is case-sensitive) can look it up.pub fn canonicalHash(name: []const u8) ?[]const u8 {- inline for ([_][]const u8{ "SHA-1", "SHA-256", "SHA-384", "SHA-512" }) |canonical| {+ for (hashes) |canonical| {if (eql(name, canonical)) return canonical;}return null;}-/// The JWK `alg` of each OAEP hash (JWA, section 4.3).-const jwk_algs = [_]struct { hash: []const u8, alg: []const u8 }{- .{ .hash = "SHA-1", .alg = "RSA-OAEP" },- .{ .hash = "SHA-256", .alg = "RSA-OAEP-256" },- .{ .hash = "SHA-384", .alg = "RSA-OAEP-384" },- .{ .hash = "SHA-512", .alg = "RSA-OAEP-512" },-};--/// The JWK `alg` for a canonical hash name.-fn jwkAlgOfHash(hash: []const u8) ?[]const u8 {- for (jwk_algs) |entry| {- if (std.mem.eql(u8, entry.hash, hash)) return entry.alg;+/// The JWK `alg` of `s` for a canonical hash name.+fn jwkAlgOfHash(s: *const Scheme, hash: []const u8) ?[]const u8 {+ for (hashes, s.jwk_algs) |h, alg| {+ if (std.mem.eql(u8, h, hash)) return alg;}return null;}-/// The canonical hash for a JWK `alg`. The spec matches `alg` case-sensitively.-fn hashOfJwkAlg(alg: []const u8) ?[]const u8 {- for (jwk_algs) |entry| {- if (std.mem.eql(u8, entry.alg, alg)) return entry.hash;+/// The canonical hash for a JWK `alg` of `s`. The spec matches `alg`+/// case-sensitively.+fn hashOfJwkAlg(s: *const Scheme, alg: []const u8) ?[]const u8 {+ for (hashes, s.jwk_algs) |hash, a| {+ if (std.mem.eql(u8, a, alg)) return hash;}return null;}const max_modulus_length = 4096;-const private_usages: []const []const u8 = &.{ "decrypt", "unwrapKey" };-const public_usages: []const []const u8 = &.{ "encrypt", "wrapKey" };--/// Generates an RSA-OAEP key pair of `modulusLength` bits with the given public+/// Generates an RSA key pair of `modulusLength` bits with the given public/// exponent. Mirrors EC.generate: each key keeps the EVP_PKEY of its half, and/// the requested usages are split across the pair (validate() rejected illegal/// ones).@@ -142,9 +168,9 @@ pub fn generate(const local = exec.js.local.?;try validate(params, key_usages);- // validate() also accepts RSASSA-PKCS1-v1_5 and RSA-PSS (so their parameter- // errors are reported correctly), but only RSA-OAEP generation is implemented.- if (!eql(params.name, "RSA-OAEP")) return error.NotSupported;+ // validate() also accepts RSA-PSS (so its parameter errors are reported+ // correctly), but it isn't implemented.+ const s = scheme(params.name) orelse return error.NotSupported;// Generation runs on the main thread and can't be interrupted, and its cost// grows steeply with the size: 8192 bits takes seconds, 16384 (BoringSSL's@@ -153,11 +179,11 @@ pub fn generate(if (params.modulusLength > max_modulus_length) return error.OperationError;const hash_name = canonicalHash(switch (params.hash) {- .string => |s| s,+ .string => |str| str,.object => |o| o.name,}).?;- const private_mask = maskOf(private_usages, key_usages);- const public_mask = maskOf(public_usages, key_usages);+ const private_mask = maskOf(s.private_usages, key_usages);+ const public_mask = maskOf(s.public_usages, key_usages);// The private key must end up with at least one usage.if (private_mask == 0) return error.SyntaxError;@@ -194,7 +220,7 @@ pub fn generate(._extractable = extractable,._usages = private_mask,._key = &.{},- ._algorithm = .{ .name = "RSA-OAEP", .hash = hash_name, .modulus_length = modulus_length, .public_exponent = public_exponent },+ ._algorithm = .{ .name = s.name, .hash = hash_name, .modulus_length = modulus_length, .public_exponent = public_exponent },._vary = .{ .pkey = private_pkey },});@@ -205,17 +231,19 @@ pub fn generate(._extractable = true,._usages = public_mask,._key = &.{},- ._algorithm = .{ .name = "RSA-OAEP", .hash = hash_name, .modulus_length = modulus_length, .public_exponent = public_exponent },+ ._algorithm = .{ .name = s.name, .hash = hash_name, .modulus_length = modulus_length, .public_exponent = public_exponent },._vary = .{ .pkey = public_pkey },});return local.resolvePromise(CryptoKey.Pair{ .privateKey = private, .publicKey = public });}-/// Imports an RSA-OAEP key from DER: `spki` (public) or `pkcs8` (private).-/// libcrypto parses the DER, so a malformed structure is DataError. `hash_name`-/// is the OAEP digest, kept for encrypt. JWK goes through `importJwk`.+/// Imports an RSA key of scheme `s` from DER: `spki` (public) or `pkcs8`+/// (private). libcrypto parses the DER, so a malformed structure is DataError.+/// `hash_name` is the digest of the OAEP padding or of the signature, kept on+/// the key. JWK goes through `importJwk`.pub fn import(+ s: *const Scheme,format: []const u8,der: []const u8,hash_name: []const u8,@@ -226,8 +254,8 @@ pub fn import() !js.Promise {const local = exec.js.local.?;- // Reject an unsupported OAEP digest at import time, rather than letting it- // surface only on the first encrypt/decrypt.+ // Reject an unsupported digest at import time, rather than letting it+ // surface only on the first operation.const hash = canonicalHash(hash_name) orelse return error.NotSupported;var ptr: [*c]const u8 = der.ptr;@@ -245,15 +273,17 @@ pub fn import(if (crypto.EVP_PKEY_id(pkey) != crypto.EVP_PKEY_RSA) return error.DataError;- return local.resolvePromise(try newKey(pkey, hash, is_private, extractable, usages_mask, exec));+ return local.resolvePromise(try newKey(s, pkey, hash, is_private, extractable, usages_mask, exec));}-/// Imports an RSA-OAEP key from a JSON Web Key: `n` and `e` for a public key,-/// plus `d`, `p`, `q`, `dp`, `dq` and `qi` for a private one (the presence of-/// `d` decides, as in SubtleCrypto.importKind, which already validated the-/// usages against it). Follows the "import key" steps of RSA-OAEP: a JWK that-/// doesn't fit the requested key, or describes an invalid one, is DataError.+/// Imports an RSA key of scheme `s` from a JSON Web Key: `n` and `e` for a+/// public key, plus `d`, `p`, `q`, `dp`, `dq` and `qi` for a private one (the+/// presence of `d` decides, as in SubtleCrypto.importKind, which already+/// validated the usages against it). Follows the "import key" steps of+/// RSA-OAEP and RSASSA-PKCS1-v1_5: a JWK that doesn't fit the requested key, or+/// describes an invalid one, is DataError.pub fn importJwk(+ s: *const Scheme,jwk: algorithm.KeyData.Jwk,hash_name: []const u8,extractable: bool,@@ -264,10 +294,10 @@ pub fn importJwk(const hash = canonicalHash(hash_name) orelse return error.NotSupported;if (!std.mem.eql(u8, jwk.kty orelse "", "RSA")) return error.DataError;- try common.checkJwk(jwk, "enc", usages_mask, extractable);+ try common.checkJwk(jwk, s.jwk_use, usages_mask, extractable);// `alg` is optional; when present, it must name the requested hash.if (jwk.alg) |alg| {- const alg_hash = hashOfJwkAlg(alg) orelse return error.DataError;+ const alg_hash = hashOfJwkAlg(s, alg) orelse return error.DataError;if (!std.mem.eql(u8, alg_hash, hash)) return error.DataError;}@@ -277,7 +307,7 @@ pub fn importJwk(errdefer crypto.EVP_PKEY_free(pkey);if (crypto.EVP_PKEY_set1_RSA(pkey, rsa) != 1) return error.OutOfMemory;- return local.resolvePromise(try newKey(pkey, hash, jwk.d != null, extractable, usages_mask, exec));+ return local.resolvePromise(try newKey(s, pkey, hash, jwk.d != null, extractable, usages_mask, exec));}/// The RSA key described by a JWK (JWA, section 6.3). A private key needs all@@ -310,9 +340,10 @@ fn jwkBigNum(member: ?[]const u8, exec: *const Execution) !*crypto.BIGNUM {return crypto.BN_bin2bn(bytes.ptr, bytes.len, null) orelse error.OutOfMemory;}-/// Wraps an RSA `pkey` in a CryptoKey. The key takes ownership of `pkey` only on-/// success.+/// Wraps an RSA `pkey` in a CryptoKey of scheme `s`. The key takes ownership+/// of `pkey` only on success.fn newKey(+ s: *const Scheme,pkey: *crypto.EVP_PKEY,hash: []const u8,is_private: bool,@@ -327,7 +358,7 @@ fn newKey(._usages = usages_mask,._key = &.{},._algorithm = .{- .name = "RSA-OAEP",+ .name = s.name,.hash = hash,.modulus_length = @intCast(crypto.EVP_PKEY_bits(pkey)),.public_exponent = try exponentBytes(pkey, exec),@@ -358,7 +389,7 @@ pub fn exportDer(format: []const u8, key: *const CryptoKey, exec: *const Executireturn exec.local_arena.dupe(u8, out[0..@intCast(len)]);}-/// The JWK of an RSA-OAEP key (JWA, section 6.3). Members are listed in+/// The JWK of an RSA key (JWA, section 6.3). Members are listed in/// lexicographic order, the order browsers return a JsonWebKey in.const JwkPublic = struct {alg: []const u8,@@ -384,17 +415,18 @@ const JwkPrivate = struct {qi: []const u8,};-/// The JWK of either half of an RSA-OAEP key.+/// The JWK of either half of an RSA key.pub const Jwk = union(enum) {public: JwkPublic,private: JwkPrivate,};-/// Exports an RSA-OAEP key as a JWK: the public members for either half, plus-/// the private members (with the CRT parameters) for the private key.+/// Exports an RSA key as a JWK: the public members for either half, plus the+/// private members (with the CRT parameters) for the private key.pub fn exportJwk(key: *const CryptoKey, exec: *const Execution) !Jwk {const rsa = crypto.EVP_PKEY_get0_RSA(key.getKeyObject()) orelse return error.OperationError;- const alg = jwkAlgOfHash(key._algorithm.hash orelse "") orelse return error.OperationError;+ const s = scheme(key._algorithm.name) orelse return error.OperationError;+ const alg = jwkAlgOfHash(s, key._algorithm.hash orelse "") orelse return error.OperationError;const n = try jwkMember(crypto.RSA_get0_n(rsa), exec);const e = try jwkMember(crypto.RSA_get0_e(rsa), exec);const key_ops = try key.getUsages(exec);@@ -449,7 +481,7 @@ pub fn crypt(exec: *const Execution,) ![]const u8 {// The key must be an RSA-OAEP key with the matching usage.- if (key._type != .rsa) return error.InvalidAccessError;+ if (key._type != .rsa or !std.mem.eql(u8, key._algorithm.name, "RSA-OAEP")) return error.InvalidAccessError;if (key._usages & usage == 0) return error.InvalidAccessError;const hash_name = key._algorithm.hash orelse return error.OperationError;@@ -489,6 +521,59 @@ pub fn crypt(return out[0..out_len];}+/// RSASSA-PKCS1-v1_5 signature generation (RFC 8017, section 8.2.1) of `data`+/// with the key's hash. SubtleCrypto.sign checked the algorithm and the sign+/// usage; only a private key signs.+pub fn sign(key: *const CryptoKey, data: []const u8, exec: *const Execution) ![]const u8 {+ if (key._kind != .private) return error.InvalidAccessError;++ const ctx = try digestContext(key, false);+ defer crypto.EVP_MD_CTX_free(ctx);++ // First call (null output) reports the size; the second writes the buffer.+ var sig_len: usize = 0;+ if (crypto.EVP_DigestSign(ctx, null, &sig_len, data.ptr, data.len) != 1) return error.OperationError;+ const out = try exec.local_arena.alloc(u8, sig_len);+ if (crypto.EVP_DigestSign(ctx, out.ptr, &sig_len, data.ptr, data.len) != 1) return error.OperationError;+ return out[0..sig_len];+}++/// RSASSA-PKCS1-v1_5 signature verification (RFC 8017, section 8.2.2) of+/// `signature` over `data` with the key's hash. SubtleCrypto.verify checked+/// the algorithm and the verify usage; only a public key verifies. A signature+/// that doesn't match, whatever its length, is false rather than an error.+pub fn verify(key: *const CryptoKey, signature: []const u8, data: []const u8) !bool {+ if (key._kind != .public) return error.InvalidAccessError;++ const ctx = try digestContext(key, true);+ defer crypto.EVP_MD_CTX_free(ctx);++ if (crypto.EVP_DigestVerify(ctx, signature.ptr, signature.len, data.ptr, data.len) == 1) return true;+ // A bad signature is an expected outcome, not a failure: don't leave it on+ // the thread's error queue for the next libcrypto caller.+ crypto.ERR_clear_error();+ return false;+}++/// A digest context set up to sign or verify with `key`: its hash, and+/// PKCS #1 v1.5 padding. Free it with EVP_MD_CTX_free.+fn digestContext(key: *const CryptoKey, verifying: bool) !*crypto.EVP_MD_CTX {+ const hash_name = key._algorithm.hash orelse return error.OperationError;+ const md = crypto.findDigest(hash_name) catch return error.OperationError;++ const ctx = crypto.EVP_MD_CTX_new() orelse return error.OutOfMemory;+ errdefer crypto.EVP_MD_CTX_free(ctx);+ // The key context belongs to `ctx`.+ var pctx: ?*crypto.EVP_PKEY_CTX = null;+ const init_ok = if (verifying)+ crypto.EVP_DigestVerifyInit(ctx, &pctx, md, null, key.getKeyObject())+ else+ crypto.EVP_DigestSignInit(ctx, &pctx, md, null, key.getKeyObject());+ if (init_ok != 1) return error.OperationError;+ if (crypto.EVP_PKEY_CTX_set_rsa_padding(pctx, crypto.RSA_PKCS1_PADDING) != 1) return error.OperationError;+ return ctx;+}+/// The usage bitmask of those `usages` that belong to `set`.fn maskOf(set: []const []const u8, usages: []const []const u8) u8 {var mask: u8 = 0;diff --git a/src/browser/webapi/crypto/algorithm.zig b/src/browser/webapi/crypto/algorithm.zigindex 16d841a7f..b6dfe7025 100644--- a/src/browser/webapi/crypto/algorithm.zig+++ b/src/browser/webapi/crypto/algorithm.zig@@ -226,11 +226,15 @@ pub const Sign = union(enum) {string: []const u8,object: struct { name: []const u8 },- pub fn isHMAC(self: Sign) bool {- const name = switch (self) {+ pub fn algoName(self: Sign) []const u8 {+ return switch (self) {.string => |string| string,.object => |object| object.name,};+ }++ pub fn isHMAC(self: Sign) bool {+ const name = self.algoName();if (name.len < 4) return false;const hmac: u32 = @bitCast([4]u8{ 'H', 'M', 'A', 'C' });diff --git a/src/sys/libcrypto.zig b/src/sys/libcrypto.zigindex 79c4560b9..9ee15c1a8 100644--- a/src/sys/libcrypto.zig+++ b/src/sys/libcrypto.zig@@ -29,7 +29,7 @@ const EC_KEY = struct_ec_key_st;const struct_evp_pkey_st = opaque {};pub const EVP_PKEY = struct_evp_pkey_st;const struct_evp_pkey_ctx_st = opaque {};-const EVP_PKEY_CTX = struct_evp_pkey_ctx_st;+pub const EVP_PKEY_CTX = struct_evp_pkey_ctx_st;pub extern fn RAND_bytes(buf: [*]u8, len: usize) c_int;@@ -44,6 +44,8 @@ pub const EVP_MAX_MD_BLOCK_SIZE = 128;pub extern fn EVP_MD_size(md: ?*const EVP_MD) usize;pub extern fn EVP_MD_block_size(md: ?*const EVP_MD) usize;+pub extern fn ERR_clear_error() void;+pub extern fn CRYPTO_memcmp(a: ?*const anyopaque, b: ?*const anyopaque, len: usize) c_int;pub extern fn HMAC(@@ -152,8 +154,9 @@ pub extern fn EC_KEY_set_public_key(key: *EC_KEY, point: *const EC_POINT) c_int;pub extern fn d2i_PUBKEY(out: ?*?*EVP_PKEY, inp: *[*c]const u8, len: c_long) ?*EVP_PKEY;pub extern fn d2i_AutoPrivateKey(out: ?*?*EVP_PKEY, inp: *[*c]const u8, len: c_long) ?*EVP_PKEY;-// RSA-OAEP: key generation, import, and the encrypt/decrypt operations.+// RSA: key generation, import, and the encrypt/decrypt and sign/verify operations.pub const EVP_PKEY_RSA = 6; // NID_rsaEncryption+pub const RSA_PKCS1_PADDING = 1;pub const RSA_PKCS1_OAEP_PADDING = 4;const struct_rsa_st = opaque {};@@ -233,11 +236,14 @@ pub extern fn EVP_PKEY_free(pkey: ?*EVP_PKEY) void;pub extern fn EVP_DigestSignInit(ctx: ?*EVP_MD_CTX, pctx: ?*?*EVP_PKEY_CTX, typ: ?*const EVP_MD, e: ?*ENGINE, pkey: ?*EVP_PKEY) c_int;pub extern fn EVP_DigestSign(ctx: ?*EVP_MD_CTX, sig: [*c]u8, sig_len: *usize, data: [*c]const u8, data_len: usize) c_int;+pub extern fn EVP_DigestVerifyInit(ctx: ?*EVP_MD_CTX, pctx: ?*?*EVP_PKEY_CTX, typ: ?*const EVP_MD, e: ?*ENGINE, pkey: ?*EVP_PKEY) c_int;+/// Returns 1 for a valid signature, 0 otherwise (on the error queue).+pub extern fn EVP_DigestVerify(ctx: ?*EVP_MD_CTX, sig: [*c]const u8, sig_len: usize, data: [*c]const u8, data_len: usize) c_int;pub extern fn EVP_Digest(data: ?*const anyopaque, len: usize, md_out: [*c]u8, md_out_size: [*c]c_uint, @"type": ?*const EVP_MD, impl: ?*ENGINE) c_int;pub extern fn EVP_MD_CTX_new() ?*EVP_MD_CTX;pub extern fn EVP_MD_CTX_free(ctx: ?*EVP_MD_CTX) void;const struct_evp_md_ctx_st = opaque {};-const EVP_MD_CTX = struct_evp_md_ctx_st;+pub const EVP_MD_CTX = struct_evp_md_ctx_st;const struct_x509_st = opaque {};pub const X509 = struct_x509_st;