Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: crypto.subtle.wrapKey / unwrapKey, and AES-KW key wrap

orezraey40a291bef4f8
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index 6670873fe..2dfb05a0d 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -404,6 +404,152 @@
});
</script>
+<script id=wrap-unwrap type=module>
+ const state = await testing.async();
+ const subtle = crypto.subtle;
+ const hex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");
+ const gcm = { name: "AES-GCM", iv: new Uint8Array(12) };
+ const cbc = { name: "AES-CBC", iv: new Uint8Array(16) };
+ const rsaAlgo = { name: "RSA-OAEP", hash: "SHA-256" };
+ const msg = new TextEncoder().encode("wrapped");
+
+ const target = await subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]);
+ const rsa = await subtle.generateKey(
+ { ...rsaAlgo, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) },
+ true,
+ ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
+ );
+ const kw = await subtle.generateKey({ name: "AES-KW", length: 128 }, true, ["wrapKey", "unwrapKey"]);
+ const gcmWrapper = await subtle.generateKey({ name: "AES-GCM", length: 128 }, true, ["wrapKey", "unwrapKey", "decrypt"]);
+ const cbcWrapper = await subtle.generateKey({ name: "AES-CBC", length: 128 }, true, ["wrapKey", "unwrapKey"]);
+ const raw = hex(await subtle.exportKey("raw", target));
+
+ // AES-KW (RFC 3394) wraps the raw key, 8 bytes longer.
+ const kwWrapped = await subtle.wrapKey("raw", target, kw, "AES-KW");
+ const kwBack = await subtle.unwrapKey("raw", kwWrapped, kw, { name: "AES-KW" }, "AES-GCM", true, ["encrypt"]);
+
+ // AES-GCM wraps a JWK as the UTF-8 of JSON.stringify(exportKey("jwk", key)).
+ const jwkWrapped = await subtle.wrapKey("jwk", rsa.privateKey, gcmWrapper, gcm);
+ const jwkText = new TextDecoder().decode(await subtle.decrypt(gcm, gcmWrapper, jwkWrapped));
+ const jwkBack = await subtle.unwrapKey("jwk", jwkWrapped, gcmWrapper, gcm, rsaAlgo, true, ["decrypt"]);
+ const ct = await subtle.encrypt({ name: "RSA-OAEP" }, rsa.publicKey, msg);
+
+ // RSA-OAEP wraps by encrypting; AES-CBC here wraps a pkcs8 key.
+ const rsaWrapped = await subtle.wrapKey("raw", target, rsa.publicKey, { name: "RSA-OAEP" });
+ const rsaBack = await subtle.unwrapKey("raw", rsaWrapped, rsa.privateKey, "RSA-OAEP", { name: "AES-GCM" }, false, ["decrypt"]);
+ const p8Wrapped = await subtle.wrapKey("pkcs8", rsa.privateKey, cbcWrapper, cbc);
+ const p8Back = await subtle.unwrapKey("pkcs8", p8Wrapped, cbcWrapper, cbc, rsaAlgo, true, ["decrypt"]);
+
+ const results = {
+ kwRaw: hex(await subtle.exportKey("raw", kwBack)),
+ jwkJson: JSON.stringify(await subtle.exportKey("jwk", rsa.privateKey)),
+ jwkDecrypt: new TextDecoder().decode(await subtle.decrypt({ name: "RSA-OAEP" }, jwkBack, ct)),
+ rsaBackDecrypt: hex(await subtle.decrypt(gcm, rsaBack, await subtle.encrypt(gcm, target, msg))),
+ p8: hex(await subtle.exportKey("pkcs8", p8Back)),
+ p8Original: hex(await subtle.exportKey("pkcs8", rsa.privateKey)),
+ };
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(40, kwWrapped.byteLength);
+ testing.expectEqual(raw, results.kwRaw);
+ testing.expectEqual(results.jwkJson, jwkText);
+ testing.expectEqual("private", jwkBack.type);
+ testing.expectEqual("wrapped", results.jwkDecrypt);
+ // The unwrapped key takes the extractable flag and usages asked for.
+ testing.expectEqual(false, rsaBack.extractable);
+ testing.expectEqual("decrypt", rsaBack.usages.join(","));
+ testing.expectEqual(hex(msg), results.rsaBackDecrypt);
+ testing.expectEqual(results.p8Original, results.p8);
+ });
+</script>
+
+<script id=wrap-unwrap-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 gcm = { name: "AES-GCM", iv: new Uint8Array(12) };
+ const cbc = { name: "AES-CBC", iv: new Uint8Array(16) };
+ const aes = (name, usages, extractable = true) => subtle.generateKey({ name, length: 128 }, extractable, usages);
+
+ const target = await aes("AES-GCM", ["encrypt"]);
+ const locked = await aes("AES-GCM", ["encrypt"], false);
+ const wrapper = await aes("AES-GCM", ["wrapKey", "unwrapKey"]);
+ const encryptOnly = await aes("AES-GCM", ["encrypt", "decrypt"]);
+ const encryptAndUnwrap = await aes("AES-GCM", ["encrypt", "unwrapKey"]);
+ const kw = await aes("AES-KW", ["wrapKey", "unwrapKey"]);
+ const otherKw = await aes("AES-KW", ["wrapKey", "unwrapKey"]);
+ const hmac = await subtle.generateKey({ name: "HMAC", hash: "SHA-256" }, true, ["sign"]);
+ // 160 bits: 20 raw bytes, not a multiple of the 8 AES-KW needs.
+ const hmac160 = await subtle.generateKey({ name: "HMAC", hash: "SHA-256", length: 160 }, true, ["sign"]);
+ const rsa = await subtle.generateKey(
+ { name: "RSA-OAEP", hash: "SHA-256", modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) },
+ true,
+ ["decrypt"],
+ );
+ const ecdh = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
+ const x25519 = await subtle.generateKey({ name: "X25519" }, true, ["deriveBits"]);
+ const kwWrapped = await subtle.wrapKey("raw", target, kw, "AES-KW");
+ const notJson = await subtle.wrapKey("raw", target, wrapper, gcm);
+ const noKty = await subtle.encrypt(gcm, encryptAndUnwrap, new TextEncoder().encode(JSON.stringify({ k: "AAAAAAAAAAAAAAAAAAAAAA" })));
+
+ const results = {
+ // The wrapping key: an algorithm that wraps or encrypts, its own algorithm, and the wrapKey/unwrapKey usage.
+ hmacAlgorithm: await errorName(() => subtle.wrapKey("raw", target, hmac, { name: "HMAC" })),
+ nameMismatch: await errorName(() => subtle.wrapKey("raw", target, wrapper, cbc)),
+ noWrapUsage: await errorName(() => subtle.wrapKey("raw", target, encryptOnly, gcm)),
+ noUnwrapUsage: await errorName(() => subtle.unwrapKey("raw", notJson, encryptOnly, gcm, "AES-GCM", true, ["encrypt"])),
+ // The wrapped key: exportable, in a format it has.
+ notExtractable: await errorName(() => subtle.wrapKey("raw", locked, wrapper, gcm)),
+ rsaRaw: await errorName(() => subtle.wrapKey("raw", rsa.privateKey, wrapper, gcm)),
+ // Only a public key has a raw form; EC's (the public point) isn't implemented.
+ x25519PrivateRaw: await errorName(() => subtle.wrapKey("raw", x25519.privateKey, wrapper, gcm)),
+ ecPrivateRaw: await errorName(() => subtle.wrapKey("raw", ecdh.privateKey, wrapper, gcm)),
+ ecPublicRaw: await errorName(() => subtle.wrapKey("raw", ecdh.publicKey, wrapper, gcm)),
+ x25519PublicRaw: await errorName(() => subtle.wrapKey("raw", x25519.publicKey, wrapper, gcm)),
+ badFormat: await errorName(() => subtle.wrapKey("pem", target, wrapper, gcm)),
+ // AES-KW only wraps: no encrypt, and its integrity check fails with another key.
+ encryptWithKw: await errorName(() => subtle.encrypt({ name: "AES-KW" }, kw, new Uint8Array(16))),
+ wrongKwKey: await errorName(() => subtle.unwrapKey("raw", kwWrapped, otherKw, "AES-KW", "AES-GCM", true, ["encrypt"])),
+ kwTooShort: await errorName(() => subtle.unwrapKey("raw", new Uint8Array(8), kw, "AES-KW", "AES-GCM", true, ["encrypt"])),
+ // The spec's AES-KW "wrap key" step says OperationError (Chrome reports DataError).
+ kwNotMultipleOf8: await errorName(() => subtle.wrapKey("raw", hmac160, kw, "AES-KW")),
+ // The unwrapped bytes go through importKey: a JWK must be JSON with a kty, and a secret key needs usages.
+ notJson: await errorName(() => subtle.unwrapKey("jwk", notJson, wrapper, gcm, "AES-GCM", true, ["encrypt"])),
+ jwkWithoutKty: await errorName(() => subtle.unwrapKey("jwk", noKty, encryptAndUnwrap, gcm, "AES-GCM", true, ["encrypt"])),
+ emptyUsages: await errorName(() => subtle.unwrapKey("raw", kwWrapped, kw, "AES-KW", "AES-GCM", true, [])),
+ };
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual("NotSupportedError", results.hmacAlgorithm);
+ testing.expectEqual("InvalidAccessError", results.nameMismatch);
+ testing.expectEqual("InvalidAccessError", results.noWrapUsage);
+ testing.expectEqual("InvalidAccessError", results.noUnwrapUsage);
+ testing.expectEqual("InvalidAccessError", results.notExtractable);
+ testing.expectEqual("NotSupportedError", results.rsaRaw);
+ testing.expectEqual("InvalidAccessError", results.x25519PrivateRaw);
+ testing.expectEqual("InvalidAccessError", results.ecPrivateRaw);
+ testing.expectEqual("NotSupportedError", results.ecPublicRaw);
+ testing.expectEqual(null, results.x25519PublicRaw);
+ testing.expectEqual("TypeError", results.badFormat);
+ testing.expectEqual("NotSupportedError", results.encryptWithKw);
+ testing.expectEqual("OperationError", results.wrongKwKey);
+ testing.expectEqual("OperationError", results.kwTooShort);
+ testing.expectEqual("OperationError", results.kwNotMultipleOf8);
+ testing.expectEqual("DataError", results.notJson);
+ testing.expectEqual("DataError", results.jwkWithoutKty);
+ testing.expectEqual("SyntaxError", results.emptyUsages);
+ });
+</script>
+
<script id=aes-ctr-counter-wrap type=module>
const state = await testing.async();
// AES-CTR must increment only the rightmost `length` bits of the counter
diff --git a/src/browser/webapi/CryptoKey.zig b/src/browser/webapi/CryptoKey.zig
index b4a8cb286..343f62b02 100644
--- a/src/browser/webapi/CryptoKey.zig
+++ b/src/browser/webapi/CryptoKey.zig
@@ -137,14 +137,6 @@ pub fn acquireRef(self: *CryptoKey) void {
self._rc.acquire();
}
-pub fn canEncrypt(self: *const CryptoKey) bool {
- return self._usages & Usages.encrypt != 0;
-}
-
-pub fn canDecrypt(self: *const CryptoKey) bool {
- return self._usages & Usages.decrypt != 0;
-}
-
pub fn canSign(self: *const CryptoKey) bool {
return self._usages & Usages.sign != 0;
}
diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zig
index 8713f8cfd..243bd641a 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -270,6 +270,22 @@ pub fn exportKey(
key: *CryptoKey,
exec: *const Execution,
) !js.Promise {
+ const local = exec.js.local.?;
+ return switch (try exportAs(format, key, exec)) {
+ .bytes => |bytes| local.resolvePromise(js.ArrayBuffer{ .values = bytes }),
+ .jwk => |jwk| local.resolvePromise(jwk),
+ };
+}
+
+/// A key exported in some format: the key's bytes (raw, spki, pkcs8), or its
+/// JWK object.
+const Exported = union(enum) {
+ bytes: []const u8,
+ jwk: js.Value,
+};
+
+/// The "export key" steps shared by exportKey and wrapKey.
+fn exportAs(format: []const u8, key: *CryptoKey, exec: *const Execution) !Exported {
const local = exec.js.local.?;
if (!key.canExportKey()) {
return error.InvalidAccessError;
@@ -280,17 +296,27 @@ pub fn exportKey(
if (key._type == .rsa) {
return error.NotSupported;
}
- return local.resolvePromise(js.ArrayBuffer{ .values = key._key });
+ // Only the public half of an asymmetric key has a raw form.
+ if (key._kind == .private) {
+ return error.InvalidAccessError;
+ }
+ // EC keys live in `_vary.pkey` too, with no bytes in `_key`: their raw
+ // form (the public point) isn't implemented, and an empty buffer
+ // would pass for one.
+ if (key._type == .ec) {
+ return error.NotSupported;
+ }
+ return .{ .bytes = key._key };
}
if (std.mem.eql(u8, format, "jwk")) {
- return exportJwk(key, exec);
+ return .{ .jwk = try exportJwk(key, exec) };
}
const is_der = std.mem.eql(u8, format, "pkcs8") or std.mem.eql(u8, format, "spki");
if (is_der) {
if (key._type == .rsa) {
- return RSA.exportDer(format, key, exec);
+ return .{ .bytes = try RSA.exportDer(format, key, exec) };
}
log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = format });
return error.NotSupported;
@@ -308,7 +334,7 @@ const JwkSecret = struct {
key_ops: []const []const u8,
};
-fn exportJwk(key: *CryptoKey, exec: *const Execution) !js.Promise {
+fn exportJwk(key: *CryptoKey, exec: *const Execution) !js.Value {
const local = exec.js.local.?;
// The `alg` registry value depends on the algorithm and key length.
@@ -328,12 +354,12 @@ fn exportJwk(key: *CryptoKey, exec: *const Execution) !js.Promise {
},
};
- return local.resolvePromise(JwkSecret{
+ return local.zigValueToJs(JwkSecret{
.k = try common.base64Encode(exec.local_arena, key._key),
.alg = alg,
.ext = key._extractable,
.key_ops = try key.getUsages(exec),
- });
+ }, .{});
}
/// Derive an array of bits from a base key. `length` is in bits and may be null
@@ -431,7 +457,9 @@ pub fn encrypt(
data: js.TypedArray(u8),
exec: *const Execution,
) !js.Promise {
- return cryptOp(algo, key, data.values, true, exec);
+ const local = exec.js.local.?;
+ const out = try cryptBytes(algo, key, data.values, .encrypt, exec);
+ return local.resolvePromise(js.ArrayBuffer{ .values = out });
}
/// Decrypts data with the given key and algorithm.
@@ -442,28 +470,141 @@ pub fn decrypt(
data: js.TypedArray(u8),
exec: *const Execution,
) !js.Promise {
- return cryptOp(algo, key, data.values, false, exec);
+ const local = exec.js.local.?;
+ const out = try cryptBytes(algo, key, data.values, .decrypt, exec);
+ return local.resolvePromise(js.ArrayBuffer{ .values = out });
}
-fn cryptOp(
- algo: algorithm.Encrypt,
+/// Wraps a key: exports it in `format` (a JWK as its JSON text) and encrypts
+/// the result with `wrapping_key`, or wraps it with AES-KW.
+pub fn wrapKey(
+ _: *const SubtleCrypto,
+ format: []const u8,
key: *CryptoKey,
- data: []const u8,
- encrypting: bool,
+ wrapping_key: *CryptoKey,
+ algo: algorithm.Encrypt,
+ exec: *const Execution,
+) !js.Promise {
+ const local = exec.js.local.?;
+ try checkWrappingKey(algo, wrapping_key, .wrap);
+
+ const bytes = switch (try exportAs(format, key, exec)) {
+ .bytes => |bytes| bytes,
+ // JSON.stringify of the JWK object, UTF-8 encoded.
+ .jwk => |jwk| try jwk.toJson(exec.local_arena),
+ };
+ const out = try cryptBytes(algo, wrapping_key, bytes, .wrap, exec);
+ return local.resolvePromise(js.ArrayBuffer{ .values = out });
+}
+
+/// Unwraps a key: decrypts `wrapped_key` with `unwrapping_key` (or unwraps it
+/// with AES-KW) and imports the result in `format`, a JWK being its JSON text.
+pub fn unwrapKey(
+ self: *const SubtleCrypto,
+ format: []const u8,
+ wrapped_key: js.TypedArray(u8),
+ unwrapping_key: *CryptoKey,
+ algo: algorithm.Encrypt,
+ unwrapped_key_algo: algorithm.Import,
+ extractable: bool,
+ key_usages: []const []const u8,
exec: *const Execution,
) !js.Promise {
+ try checkWrappingKey(algo, unwrapping_key, .unwrap);
+
+ const bytes = try cryptBytes(algo, unwrapping_key, wrapped_key.values, .unwrap, exec);
+ const key_data: algorithm.KeyData = if (std.mem.eql(u8, format, "jwk"))
+ .{ .jwk = try parseJwk(bytes, exec) }
+ else
+ .{ .bytes = .{ .values = bytes } };
+ // importKey rejects a secret or private key with no usages (SyntaxError),
+ // the last check unwrapKey asks for.
+ return self.importKey(format, key_data, unwrapped_key_algo, extractable, key_usages, exec);
+}
+
+/// What `cryptBytes` is for, which decides the direction and the usage the key
+/// needs.
+const CryptUse = enum {
+ encrypt,
+ decrypt,
+ wrap,
+ unwrap,
+
+ fn encrypting(self: CryptUse) bool {
+ return self == .encrypt or self == .wrap;
+ }
+
+ fn usage(self: CryptUse) u8 {
+ return switch (self) {
+ .encrypt => CryptoKey.Usages.encrypt,
+ .decrypt => CryptoKey.Usages.decrypt,
+ .wrap => CryptoKey.Usages.wrapKey,
+ .unwrap => CryptoKey.Usages.unwrapKey,
+ };
+ }
+};
+
+/// The checks wrapKey/unwrapKey make on the wrapping key before touching the
+/// other key, in the spec's order: an algorithm that can wrap (AES-KW) or
+/// encrypt (RSA-OAEP, AES-CBC/CTR/GCM), the same algorithm as the wrapping key,
+/// 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) {
+ return error.NotSupported;
+ }
+ if (!eqlIgnoreCase(name, wrapping_key._algorithm.name)) {
+ return error.InvalidAccessError;
+ }
+ if (wrapping_key._usages & use.usage() == 0) {
+ return error.InvalidAccessError;
+ }
+}
+
+/// "Parse a JWK" for unwrapKey: the bytes as JSON text, converted to a JWK the
+/// way an importKey `keyData` object is. Anything that doesn't parse is
+/// DataError; the import then rejects what isn't a usable JWK.
+fn parseJwk(bytes: []const u8, exec: *const Execution) !algorithm.KeyData.Jwk {
const local = exec.js.local.?;
+ // JSON.parse throws on bad input: keep that exception from the page.
+ var try_catch: js.TryCatch = undefined;
+ try_catch.init(local);
+ defer try_catch.deinit();
+
+ const value = local.parseJSON(bytes) catch return error.DataError;
+ return local.jsValueToZig(algorithm.KeyData.Jwk, value) catch return error.DataError;
+}
+
+/// Encrypts or decrypts `data` with `key`, for encrypt/decrypt and for
+/// wrapKey/unwrapKey, which encrypt the exported key (or use AES-KW's own key
+/// wrap). Returns the resulting bytes.
+fn cryptBytes(
+ algo: algorithm.Encrypt,
+ key: *CryptoKey,
+ data: []const u8,
+ use: CryptUse,
+ exec: *const Execution,
+) ![]const u8 {
+ const name = algo.algoName();
// 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(algo.algoName()) != null) {
+ if (RSA.canonicalName(name) != null) {
const label: []const u8 = switch (algo) {
.params => |p| if (p.label) |l| l.values else "",
.name => "",
};
- const out = try RSA.crypt(key, data, label, encrypting, exec);
- return local.resolvePromise(js.ArrayBuffer{ .values = out });
+ return RSA.crypt(key, data, label, use.encrypting(), use.usage(), exec);
+ }
+
+ // AES-KW has no encrypt/decrypt, only its key wrap; its params are just
+ // the name, so a bare string is fine.
+ if (eqlIgnoreCase(name, "AES-KW")) {
+ if (use == .encrypt or use == .decrypt) {
+ return error.NotSupported;
+ }
+ return AES.keyWrap(key, data, use.encrypting(), use.usage(), exec);
}
const params = switch (algo) {
@@ -471,9 +612,7 @@ fn cryptOp(
// A bare string identifier carries no iv/counter, so it can't drive AES.
.name => return error.NotSupported,
};
-
- const out = try AES.crypt(params, key, data, encrypting, exec);
- return local.resolvePromise(js.ArrayBuffer{ .values = out });
+ return AES.crypt(params, key, data, use.encrypting(), use.usage(), exec);
}
/// Generate a digital signature.
@@ -567,6 +706,8 @@ pub const JsApi = struct {
pub const exportKey = bridge.function(SubtleCrypto.exportKey, .{});
pub const encrypt = bridge.function(SubtleCrypto.encrypt, .{});
pub const decrypt = bridge.function(SubtleCrypto.decrypt, .{});
+ pub const wrapKey = bridge.function(SubtleCrypto.wrapKey, .{});
+ pub const unwrapKey = bridge.function(SubtleCrypto.unwrapKey, .{});
pub const sign = bridge.function(SubtleCrypto.sign, .{});
pub const verify = bridge.function(SubtleCrypto.verify, .{});
pub const deriveBits = bridge.function(SubtleCrypto.deriveBits, .{});
diff --git a/src/browser/webapi/crypto/AES.zig b/src/browser/webapi/crypto/AES.zig
index 1c17fa021..daa1a8cd4 100644
--- a/src/browser/webapi/crypto/AES.zig
+++ b/src/browser/webapi/crypto/AES.zig
@@ -16,9 +16,8 @@
// 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/>.
-//! AES for AES-CBC/CTR/GCM/KW: key generation, import, and encrypt/decrypt
-//! (CBC/CTR/GCM). Keys are raw byte strings; wrapKey/unwrapKey is not yet
-//! implemented.
+//! AES for AES-CBC/CTR/GCM/KW: key generation, import, encrypt/decrypt
+//! (CBC/CTR/GCM) and AES-KW's key wrap/unwrap. Keys are raw byte strings.
const std = @import("std");
const lp = @import("lightpanda");
@@ -176,12 +175,14 @@ fn cipherFor(mode: Mode, key_len: usize) ?*const crypto.EVP_CIPHER {
}
/// AES encrypt (`encrypting = true`) or decrypt. Returns the resulting bytes
-/// (ciphertext for GCM includes the appended tag).
+/// (ciphertext for GCM includes the appended tag). `usage` is the usage bit
+/// the key needs: encrypt/decrypt, or wrapKey/unwrapKey when wrapping a key.
pub fn crypt(
params: anytype, // algorithm.Encrypt.params
key: *const CryptoKey,
data: []const u8,
encrypting: bool,
+ usage: u8,
exec: *const Execution,
) CipherError![]const u8 {
const mode = modeFor(params.name) orelse return error.NotSupported;
@@ -191,7 +192,7 @@ pub fn crypt(
if (key._type != .aes or !eqlIgnoreCase(key._algorithm.name, params.name)) {
return error.InvalidAccessError;
}
- if ((encrypting and !key.canEncrypt()) or (!encrypting and !key.canDecrypt())) {
+ if (key._usages & usage == 0) {
return error.InvalidAccessError;
}
@@ -209,6 +210,43 @@ pub fn crypt(
};
}
+/// AES-KW (RFC 3394) key wrap (`wrapping = true`) or unwrap, with the default
+/// IV. `usage` is the wrapKey/unwrapKey bit the key needs. Data that isn't a
+/// multiple of 8 bytes (or too short), and an integrity failure on unwrap, are
+/// OperationError.
+pub fn keyWrap(
+ key: *const CryptoKey,
+ data: []const u8,
+ wrapping: bool,
+ usage: u8,
+ exec: *const Execution,
+) CipherError![]const u8 {
+ if (key._type != .aes or !eqlIgnoreCase(key._algorithm.name, "AES-KW")) {
+ return error.InvalidAccessError;
+ }
+ if (key._usages & usage == 0) {
+ return error.InvalidAccessError;
+ }
+ if (data.len < 8) return error.OperationError;
+
+ // 16-byte aligned like the key schedules BoringSSL allocates itself.
+ var aes_key: crypto.AES_KEY align(16) = undefined;
+ const bits: c_uint = @intCast(key._key.len * 8);
+ const set = if (wrapping)
+ crypto.AES_set_encrypt_key(key._key.ptr, bits, &aes_key)
+ else
+ crypto.AES_set_decrypt_key(key._key.ptr, bits, &aes_key);
+ if (set != 0) return error.OperationError;
+
+ const out = try exec.local_arena.alloc(u8, if (wrapping) data.len + 8 else data.len - 8);
+ const len = if (wrapping)
+ crypto.AES_wrap_key(&aes_key, null, out.ptr, data.ptr, data.len)
+ else
+ crypto.AES_unwrap_key(&aes_key, null, out.ptr, data.ptr, data.len);
+ if (len < 0) return error.OperationError;
+ return out[0..@intCast(len)];
+}
+
fn ivOf(opt: anytype) ?[]const u8 {
const v = opt orelse return null;
return v.values;
diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zig
index 69b87be40..9bd3bf499 100644
--- a/src/browser/webapi/crypto/RSA.zig
+++ b/src/browser/webapi/crypto/RSA.zig
@@ -357,8 +357,7 @@ fn newKey(
/// Exports an RSA key as DER: `spki` for a public key, `pkcs8` for a private
/// one. Asking for the other half's format is InvalidAccessError.
-pub fn exportDer(format: []const u8, key: *const CryptoKey, exec: *const Execution) !js.Promise {
- const local = exec.js.local.?;
+pub fn exportDer(format: []const u8, key: *const CryptoKey, exec: *const Execution) ![]const u8 {
const pkey = key.getKeyObject();
var out: [*c]u8 = null;
@@ -375,8 +374,7 @@ pub fn exportDer(format: []const u8, key: *const CryptoKey, exec: *const Executi
defer crypto.OPENSSL_free(out);
if (len <= 0) return error.OperationError;
- const der = try exec.local_arena.dupe(u8, out[0..@intCast(len)]);
- return local.resolvePromise(js.ArrayBuffer{ .values = der });
+ return exec.local_arena.dupe(u8, out[0..@intCast(len)]);
}
/// The JWK of an RSA-OAEP key (JWA, section 6.3). Members are listed in
@@ -405,9 +403,9 @@ const JwkPrivate = struct {
qi: []const u8,
};
-/// 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.
-pub fn exportJwk(key: *const CryptoKey, exec: *const Execution) !js.Promise {
+/// Exports an RSA-OAEP key as a JWK object: 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) !js.Value {
const local = exec.js.local.?;
const rsa = crypto.EVP_PKEY_get0_RSA(key.getKeyObject()) orelse return error.OperationError;
const alg = jwkAlgOfHash(key._algorithm.hash orelse "") orelse return error.OperationError;
@@ -416,9 +414,9 @@ pub fn exportJwk(key: *const CryptoKey, exec: *const Execution) !js.Promise {
const key_ops = try key.getUsages(exec);
if (key._kind == .public) {
- return local.resolvePromise(JwkPublic{ .alg = alg, .e = e, .ext = key._extractable, .key_ops = key_ops, .n = n });
+ return local.zigValueToJs(JwkPublic{ .alg = alg, .e = e, .ext = key._extractable, .key_ops = key_ops, .n = n }, .{});
}
- return local.resolvePromise(JwkPrivate{
+ return local.zigValueToJs(JwkPrivate{
.alg = alg,
.d = try jwkMember(crypto.RSA_get0_d(rsa), exec),
.dp = try jwkMember(crypto.RSA_get0_dmp1(rsa), exec),
@@ -430,7 +428,7 @@ pub fn exportJwk(key: *const CryptoKey, exec: *const Execution) !js.Promise {
.p = try jwkMember(crypto.RSA_get0_p(rsa), exec),
.q = try jwkMember(crypto.RSA_get0_q(rsa), exec),
.qi = try jwkMember(crypto.RSA_get0_iqmp(rsa), exec),
- });
+ }, .{});
}
/// A key component as a JWK Base64urlUInt member.
@@ -453,19 +451,20 @@ fn bnBytes(bn: ?*const crypto.BIGNUM, exec: *const Execution) ![]const u8 {
/// RSA-OAEP encrypt/decrypt. `encrypting` selects the init/op pair; the
/// padding, OAEP digest (the hash stored on the key), MGF1 digest, label and
-/// the two-call output sizing are identical for both directions.
+/// the two-call output sizing are identical for both directions. `usage` is the
+/// usage bit the key needs: encrypt/decrypt, or wrapKey/unwrapKey when wrapping
+/// a key.
pub fn crypt(
key: *const CryptoKey,
data: []const u8,
label: []const u8,
encrypting: bool,
+ usage: u8,
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 ((encrypting and !key.canEncrypt()) or (!encrypting and !key.canDecrypt())) {
- return error.InvalidAccessError;
- }
+ if (key._usages & usage == 0) return error.InvalidAccessError;
const hash_name = key._algorithm.hash orelse return error.OperationError;
const md = crypto.findDigest(hash_name) catch return error.OperationError;
diff --git a/src/sys/libcrypto.zig b/src/sys/libcrypto.zig
index d4d6fc9c6..79c4560b9 100644
--- a/src/sys/libcrypto.zig
+++ b/src/sys/libcrypto.zig
@@ -112,6 +112,20 @@ pub extern fn EVP_DecryptInit_ex(ctx: *EVP_CIPHER_CTX, cipher: ?*const EVP_CIPHE
pub extern fn EVP_DecryptUpdate(ctx: *EVP_CIPHER_CTX, out: [*c]u8, out_len: *c_int, in: [*c]const u8, in_len: c_int) c_int;
pub extern fn EVP_DecryptFinal_ex(ctx: *EVP_CIPHER_CTX, out: [*c]u8, out_len: *c_int) c_int;
+// AES key wrap (RFC 3394), for AES-KW. `AES_KEY` must match BoringSSL's
+// `struct aes_key_st` (AES_MAXNR = 14).
+pub const AES_KEY = extern struct {
+ rd_key: [4 * (14 + 1)]u32,
+ rounds: c_uint,
+};
+/// Returns 0 on success, negative for an invalid key size.
+pub extern fn AES_set_encrypt_key(key: [*]const u8, bits: c_uint, aeskey: *AES_KEY) c_int;
+pub extern fn AES_set_decrypt_key(key: [*]const u8, bits: c_uint, aeskey: *AES_KEY) c_int;
+/// Returns the output length (`in_len` + 8 / - 8), or -1. A null `iv` is the
+/// default IV.
+pub extern fn AES_wrap_key(key: *const AES_KEY, iv: ?[*]const u8, out: [*]u8, in: [*]const u8, in_len: usize) c_int;
+pub extern fn AES_unwrap_key(key: *const AES_KEY, iv: ?[*]const u8, out: [*]u8, in: [*]const u8, in_len: usize) c_int;
+
// EVP_CIPHER_CTX_ctrl commands for AES-GCM.
pub const EVP_CTRL_GCM_SET_IVLEN = 0x9;
pub const EVP_CTRL_GCM_GET_TAG = 0x10;