Skip to content

Truly independent web browser

LibCrypto: Implement Web Crypto's backend in libcrypto_rust on OpenSSL

Shannon Booth7524123031ec
diff --git a/Libraries/LibCrypto/Rust/src/der.rs b/Libraries/LibCrypto/Rust/src/der.rs
new file mode 100644
index 00000000000..57830d1a819
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/der.rs
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The few DER structures that Web Crypto exports or checks. Each one is written into a single buffer of its final size,
+//! so that no partial copy of a private key is left behind, which OpenSSL's encoders do leave.
+//! Object identifiers are given as the contents of their DER encoding.
+
+pub(crate) const INTEGER: u8 = 0x02;
+pub(crate) const BIT_STRING: u8 = 0x03;
+pub(crate) const OCTET_STRING: u8 = 0x04;
+pub(crate) const OBJECT_IDENTIFIER: u8 = 0x06;
+pub(crate) const SEQUENCE: u8 = 0x30;
+pub(crate) const NULL: [u8; 2] = [0x05, 0x00];
+
+/// The tag and definite length that start an element of `length` content bytes.
+pub(crate) fn header(tag: u8, length: usize) -> Vec<u8> {
+ let mut header = vec![tag];
+ if length < 0x80 {
+ header.push(length as u8);
+ } else {
+ let bytes = length.to_be_bytes();
+ let leading_zeros = bytes.iter().take_while(|&&byte| byte == 0).count();
+ header.push(0x80 | (bytes.len() - leading_zeros) as u8);
+ header.extend_from_slice(&bytes[leading_zeros..]);
+ }
+ header
+}
+
+/// An element of the given tag and contents, the contents given in parts.
+pub(crate) fn element(tag: u8, contents: &[&[u8]]) -> Vec<u8> {
+ let length = contents.iter().map(|part| part.len()).sum();
+ let header = header(tag, length);
+ let mut output = Vec::with_capacity(header.len() + length);
+ output.extend_from_slice(&header);
+ for part in contents {
+ output.extend_from_slice(part);
+ }
+ output
+}
+
+/// The object identifier of the given DER contents.
+pub(crate) fn object_identifier(contents: &[u8]) -> Vec<u8> {
+ element(OBJECT_IDENTIFIER, &[contents])
+}
+
+fn algorithm_identifier(algorithm: &[u8], parameters: Option<&[u8]>) -> Vec<u8> {
+ element(
+ SEQUENCE,
+ &[&object_identifier(algorithm), parameters.unwrap_or_default()],
+ )
+}
+
+/// https://www.rfc-editor.org/rfc/rfc8017#appendix-A.1.2
+pub(crate) fn rsa_private_key(integers: &[&[u8]]) -> Vec<u8> {
+ // RSAPrivateKey ::= SEQUENCE {
+ // version Version,
+ // modulus INTEGER, -- n
+ // publicExponent INTEGER, -- e
+ // privateExponent INTEGER, -- d
+ // prime1 INTEGER, -- p
+ // prime2 INTEGER, -- q
+ // exponent1 INTEGER, -- d mod (p-1)
+ // exponent2 INTEGER, -- d mod (q-1)
+ // coefficient INTEGER, -- (inverse of q) mod p
+ // otherPrimeInfos OtherPrimeInfos OPTIONAL
+ // }
+ // NB: The integers are unsigned and have no leading zeros, so a zero byte keeps one whose top bit is set positive.
+ let version = [INTEGER, 1, 0];
+ let prefixes: Vec<Vec<u8>> = integers
+ .iter()
+ .map(|integer| {
+ let needs_zero = integer.first().is_none_or(|&byte| byte & 0x80 != 0);
+ let mut prefix = header(INTEGER, integer.len() + usize::from(needs_zero));
+ if needs_zero {
+ prefix.push(0);
+ }
+ prefix
+ })
+ .collect();
+ let mut contents: Vec<&[u8]> = vec![&version];
+ for (prefix, integer) in prefixes.iter().zip(integers) {
+ contents.push(prefix);
+ contents.push(integer);
+ }
+ element(SEQUENCE, &contents)
+}
+
+/// https://www.rfc-editor.org/rfc/rfc5280#section-4.1
+pub(crate) fn subject_public_key_info(algorithm: &[u8], parameters: Option<&[u8]>, public_key: &[u8]) -> Vec<u8> {
+ let bit_string = element(BIT_STRING, &[&[0], public_key]);
+ element(SEQUENCE, &[&algorithm_identifier(algorithm, parameters), &bit_string])
+}
+
+/// https://www.rfc-editor.org/rfc/rfc5208#section-5
+pub(crate) fn private_key_info(algorithm: &[u8], parameters: Option<&[u8]>, private_key: &[u8]) -> Vec<u8> {
+ let version = [INTEGER, 1, 0];
+ let private_key_header = header(OCTET_STRING, private_key.len());
+ element(
+ SEQUENCE,
+ &[
+ &version,
+ &algorithm_identifier(algorithm, parameters),
+ &private_key_header,
+ private_key,
+ ],
+ )
+}
diff --git a/Libraries/LibCrypto/Rust/src/ec.rs b/Libraries/LibCrypto/Rust/src/ec.rs
new file mode 100644
index 00000000000..dd2f37c6759
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/ec.rs
@@ -0,0 +1,446 @@
+/*
+ * Copyright (c) 2024-2025, Altomani Gianluca <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! EC keys of the NIST prime curves. A key given by its coordinates or scalar is on the curve whose coordinates have
+//! that size: 32 bytes for P-256, 48 for P-384 and 66 for P-521.
+
+use core::ffi::{CStr, c_int};
+
+use crate::der;
+use crate::key::{HandleTag, Key, KeyDecodeError, KeyHandle, KeyPair, SecretBytes, StoredKey};
+use crate::openssl::{self, ParamBuilder, Pkey, end_parameter, octet_string_parameter, utf8_parameter};
+use crate::{CryptoError, EcCurve, KeyAlgorithm, sys};
+
+#[derive(Clone)]
+pub(crate) struct EcPublicKey {
+ key: Pkey,
+ curve: EcCurve,
+}
+
+/// A private key keeps the optional parts of the ECPrivateKey it was given in, which it is exported with: its curve's
+/// parameters, and its public key.
+pub(crate) struct EcPrivateKey {
+ key: Pkey,
+ curve: EcCurve,
+ has_parameters: bool,
+ public_key: Option<EcPublicKey>,
+}
+
+impl EcCurve {
+ fn from_scalar_size(scalar_size: usize) -> Result<Self, CryptoError> {
+ match scalar_size {
+ 32 => Ok(Self::P256),
+ 48 => Ok(Self::P384),
+ 66 => Ok(Self::P521),
+ _ => Err(CryptoError::Invalid("Unsupported EC curve")),
+ }
+ }
+
+ fn scalar_size(self) -> usize {
+ match self {
+ Self::P256 => 32,
+ Self::P384 => 48,
+ Self::P521 => 66,
+ }
+ }
+
+ /// The name of the curve's group, as OpenSSL takes it.
+ fn name(self) -> &'static CStr {
+ match self {
+ Self::P256 => c"P-256",
+ Self::P384 => c"P-384",
+ Self::P521 => c"P-521",
+ }
+ }
+
+ fn nid(self) -> c_int {
+ match self {
+ Self::P256 => sys::NID_X9_62_PRIME256V1,
+ Self::P384 => sys::NID_SECP384R1,
+ Self::P521 => sys::NID_SECP521R1,
+ }
+ }
+
+ /// The contents of the DER encoding of the curve's object identifier.
+ fn oid(self) -> &'static [u8] {
+ match self {
+ // secp256r1, 1.2.840.10045.3.1.7
+ Self::P256 => &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07],
+ // secp384r1, 1.3.132.0.34
+ Self::P384 => &[0x2b, 0x81, 0x04, 0x00, 0x22],
+ // secp521r1, 1.3.132.0.35
+ Self::P521 => &[0x2b, 0x81, 0x04, 0x00, 0x23],
+ }
+ }
+
+ pub(crate) fn from_oid(oid: &[u8]) -> Option<Self> {
+ [Self::P256, Self::P384, Self::P521]
+ .into_iter()
+ .find(|curve| curve.oid() == oid)
+ }
+
+ /// The arcs of the curve's object identifier, as a stored key gives them.
+ fn arcs(self) -> &'static [u32] {
+ match self {
+ Self::P256 => &[1, 2, 840, 10045, 3, 1, 7],
+ Self::P384 => &[1, 3, 132, 0, 34],
+ Self::P521 => &[1, 3, 132, 0, 35],
+ }
+ }
+}
+
+/// The coordinates of the public point of `key`, a key on `curve`.
+fn coordinates(key: &Pkey, curve: EcCurve) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
+ let coordinate = |name| -> Result<Vec<u8>, CryptoError> {
+ let number = key.number(name).ok_or(CryptoError::Backend)?;
+ Ok(number.to_padded(curve.scalar_size())?.into_vec())
+ };
+ Ok((coordinate(c"qx")?, coordinate(c"qy")?))
+}
+
+impl EcPublicKey {
+ /// A public key from its SEC 1 encoding, uncompressed or compressed.
+ pub(crate) fn from_octets(data: &[u8]) -> Result<Self, CryptoError> {
+ let scalar_size = match data.first() {
+ None => return Err(CryptoError::Invalid("Empty EC point")),
+ Some(0x04) if data.len() % 2 == 1 => (data.len() - 1) / 2,
+ Some(0x02 | 0x03) => data.len() - 1,
+ Some(_) => return Err(CryptoError::Invalid("Unsupported EC point format")),
+ };
+ let curve = EcCurve::from_scalar_size(scalar_size)?;
+ let invalid = |_| CryptoError::Invalid("Invalid EC public key");
+ let mut params = [
+ utf8_parameter(c"group", curve.name()),
+ octet_string_parameter(c"pub", data),
+ end_parameter(),
+ ];
+ let key = Pkey::from_data(c"EC", sys::EVP_PKEY_PUBLIC_KEY, params.as_mut_ptr()).map_err(invalid)?;
+ if !openssl::check_key(&key, false, false).map_err(invalid)?.public {
+ return Err(invalid(CryptoError::Backend));
+ }
+ Ok(Self { key, curve })
+ }
+
+ fn from_coordinates(x: &[u8], y: &[u8]) -> Result<Self, CryptoError> {
+ if x.len() != y.len() {
+ return Err(CryptoError::Invalid("EC coordinates have different sizes"));
+ }
+ let mut octets = Vec::with_capacity(1 + x.len() + y.len());
+ octets.push(0x04);
+ octets.extend_from_slice(x);
+ octets.extend_from_slice(y);
+ Self::from_octets(&octets)
+ }
+
+ fn coordinates(&self) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
+ coordinates(&self.key, self.curve)
+ }
+
+ fn to_uncompressed(&self) -> Result<Vec<u8>, CryptoError> {
+ let (x, y) = self.coordinates()?;
+ let mut octets = Vec::with_capacity(1 + x.len() + y.len());
+ octets.push(0x04);
+ octets.extend_from_slice(&x);
+ octets.extend_from_slice(&y);
+ Ok(octets)
+ }
+}
+
+impl EcPrivateKey {
+ fn generate(curve: EcCurve) -> Result<Self, CryptoError> {
+ let params = [utf8_parameter(c"group", curve.name()), end_parameter()];
+ let key = Pkey::generate(c"EC", Some(params.as_ptr()))?;
+ let mut private_key = Self {
+ key,
+ curve,
+ has_parameters: false,
+ public_key: None,
+ };
+ private_key.public_key = Some(private_key.derive_public_key()?);
+ Ok(private_key)
+ }
+
+ /// The key of the private value `d`, whose public key, when given, must be the one `d` gives.
+ fn from_scalar(d: &[u8], has_parameters: bool, public_key: Option<EcPublicKey>) -> Result<Self, CryptoError> {
+ let curve = EcCurve::from_scalar_size(d.len())?;
+ let point =
+ openssl::ec_public_point(curve.nid(), d)?.ok_or(CryptoError::Invalid("EC private key is out of range"))?;
+ if let Some(public_key) = &public_key
+ && public_key.to_uncompressed()? != point
+ {
+ return Err(CryptoError::Invalid("EC public key does not match the private key"));
+ }
+
+ let mut builder = ParamBuilder::new()?;
+ builder.push_utf8(c"group", curve.name())?;
+ builder.push_number(c"priv", d, true)?;
+ builder.push_octets(c"pub", &point)?;
+ let params = builder.build()?;
+ let key = Pkey::from_data(c"EC", sys::EVP_PKEY_KEYPAIR, params.as_ptr())?;
+ Ok(Self {
+ key,
+ curve,
+ has_parameters,
+ public_key,
+ })
+ }
+
+ fn d_bytes(&self) -> Result<SecretBytes, CryptoError> {
+ let d = self.key.number(c"priv").ok_or(CryptoError::Backend)?;
+ d.to_padded(self.curve.scalar_size())
+ }
+
+ fn derive_public_key(&self) -> Result<EcPublicKey, CryptoError> {
+ let (x, y) = coordinates(&self.key, self.curve)?;
+ EcPublicKey::from_coordinates(&x, &y)
+ }
+
+ /// The ECPrivateKey of this key, with the parts it was given in.
+ fn export_as_der(&self) -> Result<Vec<u8>, CryptoError> {
+ let public_point = match &self.public_key {
+ Some(public_key) => Some(public_key.to_uncompressed()?),
+ None => None,
+ };
+ Ok(encode_private_key(
+ &self.d_bytes()?,
+ self.has_parameters.then_some(self.curve),
+ public_point.as_deref(),
+ ))
+ }
+}
+
+// https://www.rfc-editor.org/rfc/rfc5915#section-3
+fn encode_private_key(d: &[u8], parameters: Option<EcCurve>, public_point: Option<&[u8]>) -> Vec<u8> {
+ let version = [der::INTEGER, 1, 1];
+ let d_header = der::header(der::OCTET_STRING, d.len());
+ let parameters = parameters.map(|curve| der::element(0xa0, &[&der::object_identifier(curve.oid())]));
+ let public_key = public_point.map(|point| der::element(0xa1, &[&der::element(der::BIT_STRING, &[&[0], point])]));
+ der::element(
+ der::SEQUENCE,
+ &[
+ &version,
+ &d_header,
+ d,
+ parameters.as_deref().unwrap_or_default(),
+ public_key.as_deref().unwrap_or_default(),
+ ],
+ )
+}
+
+/// The private key `key` of a PKCS#8 PrivateKeyInfo with the named curve `curve`, whose privateKey is `encoded`.
+pub(crate) fn parse_private_key_info(curve: EcCurve, key: Pkey, encoded: &[u8]) -> Result<KeyHandle, CryptoError> {
+ let scalar_size = curve.scalar_size();
+ let d = key
+ .number(c"priv")
+ .ok_or(CryptoError::Backend)?
+ .to_padded(scalar_size)?;
+ let public_key = EcPrivateKey::from_scalar(&d, false, None)?.derive_public_key()?;
+ let uncompressed = public_key.to_uncompressed()?;
+ let mut compressed = uncompressed[..=scalar_size].to_vec();
+ compressed[0] = 0x02 | (uncompressed.last().copied().unwrap_or_default() & 1);
+
+ // NB: OpenSSL accepts BER, and a privateKey of any width. The parameters and the public key are optional, and the
+ // public key may be compressed, so the encoding must be the DER encoding of the key in one of those forms.
+ for with_parameters in [false, true] {
+ for public_point in [None, Some(uncompressed.as_slice()), Some(compressed.as_slice())] {
+ let parameters = with_parameters.then_some(curve);
+ let mut candidate = encode_private_key(&d, parameters, public_point);
+ let matches = candidate == encoded;
+ crate::key::clear(&mut candidate);
+ if !matches {
+ continue;
+ }
+ let private_key = EcPrivateKey::from_scalar(&d, with_parameters, public_point.map(|_| public_key.clone()))?;
+ return Ok(KeyHandle(Key::EcPrivate(private_key)));
+ }
+ }
+ Err(CryptoError::Invalid("Invalid ECPrivateKey"))
+}
+
+/// The public key of a SubjectPublicKeyInfo, whose subjectPublicKey is the SEC 1 encoding of the point.
+pub(crate) fn parse_subject_public_key(encoded: &[u8]) -> Result<KeyHandle, CryptoError> {
+ Ok(KeyHandle(Key::EcPublic(EcPublicKey::from_octets(encoded)?)))
+}
+
+fn public_key(key: &KeyHandle) -> &EcPublicKey {
+ match &key.0 {
+ Key::EcPublic(public_key) => public_key,
+ _ => panic!("The key is not an EC public key"),
+ }
+}
+
+fn private_key(key: &KeyHandle) -> &EcPrivateKey {
+ match &key.0 {
+ Key::EcPrivate(private_key) => private_key,
+ _ => panic!("The key is not an EC private key"),
+ }
+}
+
+pub fn ec_generate_key_pair(curve: EcCurve) -> Result<KeyPair, CryptoError> {
+ let private_key = EcPrivateKey::generate(curve).map_err(|_| CryptoError::Backend)?;
+ let public_key = private_key.public_key.clone().ok_or(CryptoError::Backend)?;
+ Ok(KeyPair {
+ public_key: KeyHandle(Key::EcPublic(public_key)),
+ private_key: KeyHandle(Key::EcPrivate(private_key)),
+ })
+}
+
+pub fn ec_sign(curve: EcCurve, key: &KeyHandle, digest: &[u8]) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
+ let private_key = private_key(key);
+ if private_key.curve != curve {
+ return Err(CryptoError::Invalid("The key is on a different curve"));
+ }
+ openssl::ecdsa_sign(&private_key.key, digest, curve.scalar_size())
+}
+
+pub fn ec_verify(curve: EcCurve, key: &KeyHandle, digest: &[u8], r: &[u8], s: &[u8]) -> Result<bool, CryptoError> {
+ let public_key = public_key(key);
+ if public_key.curve != curve || r.len() != curve.scalar_size() || s.len() != curve.scalar_size() {
+ return Ok(false);
+ }
+ openssl::ecdsa_verify(&public_key.key, digest, r, s)
+}
+
+pub fn ec_public_key_scalar_size(key: &KeyHandle) -> usize {
+ public_key(key).curve.scalar_size()
+}
+
+pub fn ec_key_from_coordinates(x: &[u8], y: &[u8], d: Option<&[u8]>) -> Option<KeyHandle> {
+ let public_key = EcPublicKey::from_coordinates(x, y).ok()?;
+ let Some(d) = d else {
+ return Some(KeyHandle(Key::EcPublic(public_key)));
+ };
+ let private_key = EcPrivateKey::from_scalar(d, false, Some(public_key)).ok()?;
+ Some(KeyHandle(Key::EcPrivate(private_key)))
+}
+
+pub fn ec_parse_raw_public_key(bytes: &[u8]) -> Option<KeyHandle> {
+ Some(KeyHandle(Key::EcPublic(EcPublicKey::from_octets(bytes).ok()?)))
+}
+
+// NB: Every EC key is a valid key for its own curve, since building it checks that.
+pub fn ec_key_is_valid(curve: EcCurve, key: &KeyHandle) -> bool {
+ let key_curve = match &key.0 {
+ Key::EcPublic(public_key) => public_key.curve,
+ Key::EcPrivate(private_key) => private_key.curve,
+ _ => panic!("The key is not an EC key"),
+ };
+ key_curve == curve
+}
+
+pub fn ec_export_der(curve: EcCurve, key: &KeyHandle, is_public: bool) -> Result<Vec<u8>, CryptoError> {
+ let parameters = der::object_identifier(curve.oid());
+ if is_public {
+ let point = public_key(key).to_uncompressed()?;
+ return Ok(der::subject_public_key_info(
+ KeyAlgorithm::Ec.oid(),
+ Some(&parameters),
+ &point,
+ ));
+ }
+ let mut private_key = private_key(key).export_as_der()?;
+ let private_key_info = der::private_key_info(KeyAlgorithm::Ec.oid(), Some(&parameters), &private_key);
+ crate::key::clear(&mut private_key);
+ Ok(private_key_info)
+}
+
+pub fn ec_export_uncompressed(key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
+ public_key(key).to_uncompressed()
+}
+
+pub fn ec_export_public_coordinates(key: &KeyHandle) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
+ match &key.0 {
+ Key::EcPublic(public_key) => public_key.coordinates(),
+ Key::EcPrivate(private_key) => match &private_key.public_key {
+ Some(public_key) => public_key.coordinates(),
+ None => private_key.derive_public_key()?.coordinates(),
+ },
+ _ => panic!("The key is not an EC key"),
+ }
+}
+
+pub fn ec_export_private_scalar(key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
+ Ok(private_key(key).d_bytes()?.into_vec())
+}
+
+pub fn ec_compute_coordinate(curve: EcCurve, key: &KeyHandle, public_key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
+ let private_key = private_key(key);
+ if private_key.curve != curve {
+ return Err(CryptoError::Invalid("The key is on a different curve"));
+ }
+ let peer = self::public_key(public_key);
+ if private_key.curve != peer.curve {
+ return Err(CryptoError::Invalid("EC keys are on different curves"));
+ }
+ openssl::derive(&private_key.key, &peer.key, true)
+}
+
+pub(crate) fn public_key_for_private_key(key: &KeyHandle) -> Option<KeyHandle> {
+ let Key::EcPrivate(private_key) = &key.0 else {
+ return None;
+ };
+ if let Some(public_key) = &private_key.public_key {
+ return Some(KeyHandle(Key::EcPublic(public_key.clone())));
+ }
+ Some(KeyHandle(Key::EcPublic(private_key.derive_public_key().ok()?)))
+}
+
+impl EcPublicKey {
+ /// The stored form of the key: its coordinates.
+ pub(crate) fn stored(&self) -> StoredKey {
+ let (x, y) = self.coordinates().expect("OpenSSL gives an EC key's coordinates");
+ StoredKey::new(HandleTag::EcPublic, vec![SecretBytes::new(x), SecretBytes::new(y)])
+ }
+}
+
+impl EcPrivateKey {
+ /// The stored form of the key: its private value, then its public key's coordinates if it has its public key, with
+ /// the curve it was given with.
+ pub(crate) fn stored(&self) -> StoredKey {
+ let mut buffers = vec![self.d_bytes().expect("OpenSSL gives an EC key's private value")];
+ if let Some(public_key) = &self.public_key {
+ let (x, y) = public_key.coordinates().expect("OpenSSL gives an EC key's coordinates");
+ buffers.extend([SecretBytes::new(x), SecretBytes::new(y)]);
+ }
+ StoredKey {
+ tag: HandleTag::EcPrivate,
+ buffers,
+ ec_parameters: self.has_parameters.then(|| self.curve.arcs().to_vec()),
+ has_ec_public_key: self.public_key.is_some(),
+ }
+ }
+}
+
+/// The key that a stored handle of an EC tag holds.
+pub(crate) fn decode_stored(
+ tag: HandleTag,
+ buffers: &[&[u8]],
+ parameters: Option<&[u32]>,
+ has_public_key: bool,
+) -> Result<KeyHandle, KeyDecodeError> {
+ let invalid = |_| KeyDecodeError::InvalidComponents;
+ match tag {
+ HandleTag::EcPublic => Ok(KeyHandle(Key::EcPublic(
+ EcPublicKey::from_coordinates(buffers[0], buffers[1]).map_err(invalid)?,
+ ))),
+ HandleTag::EcPrivate => {
+ let public_key = if has_public_key {
+ Some(EcPublicKey::from_coordinates(buffers[1], buffers[2]).map_err(invalid)?)
+ } else {
+ None
+ };
+ let private_key =
+ EcPrivateKey::from_scalar(buffers[0], parameters.is_some(), public_key).map_err(invalid)?;
+ // NB: A key stores the parameters it was given with, which name its own curve.
+ if parameters.is_some_and(|parameters| parameters != private_key.curve.arcs()) {
+ return Err(KeyDecodeError::InvalidComponents);
+ }
+ Ok(KeyHandle(Key::EcPrivate(private_key)))
+ }
+ _ => Err(KeyDecodeError::InvalidComponents),
+ }
+}
diff --git a/Libraries/LibCrypto/Rust/src/ffi.rs b/Libraries/LibCrypto/Rust/src/ffi.rs
deleted file mode 100644
index 4da711280d5..00000000000
--- a/Libraries/LibCrypto/Rust/src/ffi.rs
+++ /dev/null
@@ -1,449 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- * Copyright (c) 2024, stelar7 <[email protected]>
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2024, Andreas Kling <[email protected]>
- * Copyright (c) 2024-2025, Altomani Gianluca <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use core::ffi::c_void;
-
-use ak::{Span, SpanMut};
-
-use super::{
- Argon2Inputs, Argon2Type, Asn1Structure, CShakeKind, EcCurve, KmacKind, MlDsaSize, MlKemSize, OkpCurve,
- RsaJwkInteger, ShaHashKind,
-};
-
-pub(super) type ReceiveBytes = unsafe extern "C" fn(*mut c_void, Span<'_, u8>);
-
-#[repr(C)]
-pub(super) struct OptionalBytes<'a> {
- has_value: bool,
- bytes: Span<'a, u8>,
-}
-
-impl<'a> From<Option<&'a [u8]>> for OptionalBytes<'a> {
- fn from(bytes: Option<&'a [u8]>) -> Self {
- Self {
- has_value: bytes.is_some(),
- bytes: Span::new(bytes.unwrap_or_default()),
- }
- }
-}
-
-unsafe extern "C" {
- pub(super) fn crypto_decode_asn1_structure(
- data: Span<'_, u8>,
- structure: Asn1Structure,
- out: *mut c_void,
- all_consumed: &mut bool,
- ) -> usize;
- pub(super) fn crypto_public_key_for_private_key(key: *const c_void, name: usize) -> *mut c_void;
- pub(super) fn crypto_sha_digest(
- kind: ShaHashKind,
- data: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_cshake_validate_parameters(output_length: u32) -> usize;
- pub(super) fn crypto_cshake_digest(
- kind: CShakeKind,
- data: Span<'_, u8>,
- output_length: u32,
- customization: OptionalBytes<'_>,
- function_name: OptionalBytes<'_>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> usize;
- pub(super) fn crypto_hmac_sign(
- kind: ShaHashKind,
- key: Span<'_, u8>,
- message: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_kmac_default_key_length(kind: KmacKind) -> u32;
- pub(super) fn crypto_kmac_validate_parameters(output_length: u32, customization: OptionalBytes<'_>) -> bool;
- pub(super) fn crypto_kmac_sign(
- kind: KmacKind,
- key: Span<'_, u8>,
- message: Span<'_, u8>,
- output_length: u32,
- customization: OptionalBytes<'_>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_hash_digest_size(kind: ShaHashKind) -> usize;
- pub(super) fn crypto_hkdf_derive_key(
- kind: ShaHashKind,
- salt: Span<'_, u8>,
- key: Span<'_, u8>,
- info: Span<'_, u8>,
- length: u32,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_pbkdf2_derive_key(
- kind: ShaHashKind,
- password: Span<'_, u8>,
- salt: Span<'_, u8>,
- iterations: u32,
- length: u32,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_argon2_validate_parameters(nonce: Span<'_, u8>) -> usize;
- pub(super) fn crypto_argon2_derive_key(
- kind: Argon2Type,
- inputs: &RawArgon2Inputs<'_>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> usize;
- pub(super) fn crypto_aes_cbc_cipher(
- encrypt: bool,
- key: Span<'_, u8>,
- input: Span<'_, u8>,
- iv: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_aes_ctr_cipher(
- encrypt: bool,
- key: Span<'_, u8>,
- input: Span<'_, u8>,
- counter: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_aes_kw_cipher(
- wrap: bool,
- key: Span<'_, u8>,
- input: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_aes_gcm_encrypt(
- key: Span<'_, u8>,
- plaintext: Span<'_, u8>,
- iv: Span<'_, u8>,
- additional_data: Span<'_, u8>,
- tag_length: usize,
- ciphertext: *mut c_void,
- tag: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_aes_gcm_decrypt(
- key: Span<'_, u8>,
- ciphertext: Span<'_, u8>,
- iv: Span<'_, u8>,
- additional_data: Span<'_, u8>,
- tag: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_aes_ocb_cipher(
- encrypt: bool,
- key: Span<'_, u8>,
- input: Span<'_, u8>,
- iv: Span<'_, u8>,
- additional_data: Span<'_, u8>,
- tag_length: usize,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> usize;
- pub(super) fn crypto_chacha20_poly1305_cipher(
- encrypt: bool,
- key: Span<'_, u8>,
- iv: Span<'_, u8>,
- input: Span<'_, u8>,
- additional_data: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> usize;
- pub(super) fn crypto_asn1_allocate_key_info(structure: Asn1Structure) -> *mut c_void;
- pub(super) fn crypto_asn1_delete_key_info(structure: Asn1Structure, key_info: *mut c_void) -> ();
- pub(super) fn crypto_rsa_key_info_has_encryption_oid(structure: Asn1Structure, key_info: *const c_void) -> bool;
- pub(super) fn crypto_rsa_key_info_read_key(structure: Asn1Structure, key_info: *const c_void) -> *mut c_void;
- pub(super) fn crypto_rsa_key_is_valid(key: *const c_void, valid: &mut bool) -> bool;
- pub(super) fn crypto_rsa_validate_modulus_length(modulus_length: u32) -> bool;
- pub(super) fn crypto_rsa_generate_key_pair(
- modulus_length: u32,
- exponent: Span<'_, u8>,
- public_key: &mut *mut c_void,
- private_key: &mut *mut c_void,
- ) -> bool;
- pub(super) fn crypto_rsa_read_key_metadata(
- key: *const c_void,
- modulus_length: &mut u32,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_rsa_key_from_jwk_components(
- is_private: bool,
- components: Span<'_, Span<'_, u8>>,
- ) -> *mut c_void;
- pub(super) fn crypto_rsa_export_der(
- key: *const c_void,
- is_public: bool,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_rsa_export_jwk_integer(
- key: *const c_void,
- component: RsaJwkInteger,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_rsa_oaep_cipher(
- encrypt: bool,
- hash_kind: ShaHashKind,
- key: *const c_void,
- label: Span<'_, u8>,
- input: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_rsa_pss_sign(
- hash_kind: ShaHashKind,
- key: *const c_void,
- salt_length: u32,
- message: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_rsa_pss_verify(
- hash_kind: ShaHashKind,
- key: *const c_void,
- salt_length: u32,
- message: Span<'_, u8>,
- signature: Span<'_, u8>,
- verified: &mut bool,
- ) -> bool;
- pub(super) fn crypto_rsa_pkcs1_sign(
- hash_kind: ShaHashKind,
- key: *const c_void,
- message: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_rsa_pkcs1_verify(
- hash_kind: ShaHashKind,
- key: *const c_void,
- message: Span<'_, u8>,
- signature: Span<'_, u8>,
- verified: &mut bool,
- ) -> bool;
- pub(super) fn crypto_ec_generate_key_pair(
- curve: EcCurve,
- public_key: &mut *mut c_void,
- private_key: &mut *mut c_void,
- ) -> bool;
- pub(super) fn crypto_ec_sign(
- curve: EcCurve,
- key: *const c_void,
- digest: Span<'_, u8>,
- r: *mut c_void,
- s: *mut c_void,
- receive: ReceiveBytes,
- ) -> usize;
- pub(super) fn crypto_ec_verify(
- curve: EcCurve,
- key: *const c_void,
- digest: Span<'_, u8>,
- r: Span<'_, u8>,
- s: Span<'_, u8>,
- verified: &mut bool,
- ) -> usize;
- pub(super) fn crypto_ec_public_key_scalar_size(key: *const c_void) -> usize;
- pub(super) fn crypto_ec_compute_coordinate(
- curve: EcCurve,
- key: *const c_void,
- public_key: *const c_void,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> usize;
- pub(super) fn crypto_ec_key_info_has_public_key_oid(structure: Asn1Structure, key_info: *const c_void) -> bool;
- pub(super) fn crypto_ec_key_info_parameters(
- structure: Asn1Structure,
- key_info: *const c_void,
- parameters: &mut Span<'_, u32>,
- ) -> bool;
- pub(super) fn crypto_ec_private_key_info_parameters_match(key_info: *const c_void) -> bool;
- pub(super) fn crypto_ec_key_info_read_key(structure: Asn1Structure, key_info: *const c_void) -> *mut c_void;
- pub(super) fn crypto_ec_key_from_coordinates(x: Span<'_, u8>, y: Span<'_, u8>, d: OptionalBytes<'_>)
- -> *mut c_void;
- pub(super) fn crypto_ec_parse_raw_public_key(bytes: Span<'_, u8>) -> *mut c_void;
- pub(super) fn crypto_ec_key_is_valid(curve: EcCurve, key: *const c_void, valid: &mut bool) -> bool;
- pub(super) fn crypto_ec_export_der(
- curve: EcCurve,
- key: *const c_void,
- is_public: bool,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_ec_export_uncompressed(key: *const c_void, state: *mut c_void, receive: ReceiveBytes) -> bool;
- pub(super) fn crypto_ec_export_public_coordinates(
- key: *const c_void,
- x: *mut c_void,
- y: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_ec_export_private_scalar(
- key: *const c_void,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_okp_generate_private_key(curve: OkpCurve, state: *mut c_void, receive: ReceiveBytes) -> bool;
- pub(super) fn crypto_okp_generate_public_key(
- curve: OkpCurve,
- private_key: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_okp_compute_coordinate(
- curve: OkpCurve,
- private_key: Span<'_, u8>,
- public_key: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_okp_sign(
- curve: OkpCurve,
- private_key: Span<'_, u8>,
- message: Span<'_, u8>,
- context: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_okp_verify(
- curve: OkpCurve,
- public_key: Span<'_, u8>,
- signature: Span<'_, u8>,
- message: Span<'_, u8>,
- context: Span<'_, u8>,
- verified: &mut bool,
- ) -> usize;
- pub(super) fn crypto_okp_key_info_has_oid(
- curve: OkpCurve,
- structure: Asn1Structure,
- key_info: *const c_void,
- ) -> bool;
- pub(super) fn crypto_asn1_key_info_raw_key(
- structure: Asn1Structure,
- key_info: *const c_void,
- bytes: &mut Span<'_, u8>,
- ) -> ();
- pub(super) fn crypto_asn1_octet_string_bytes(string: *const c_void, bytes: &mut Span<'_, u8>) -> ();
- pub(super) fn crypto_okp_export_der(
- curve: OkpCurve,
- is_public: bool,
- key: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_mldsa_sign(
- size: MlDsaSize,
- key: *const c_void,
- message: Span<'_, u8>,
- context: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_mldsa_verify(
- size: MlDsaSize,
- key: *const c_void,
- message: Span<'_, u8>,
- signature: Span<'_, u8>,
- context: Span<'_, u8>,
- verified: &mut bool,
- ) -> bool;
- pub(super) fn crypto_mldsa_generate_key_pair(
- size: MlDsaSize,
- seed: Span<'_, u8>,
- public_key: &mut *mut c_void,
- private_key: &mut *mut c_void,
- ) -> usize;
- pub(super) fn crypto_asn1_key_info_identifier(
- structure: Asn1Structure,
- key_info: *const c_void,
- oid: &mut Span<'_, u32>,
- ) -> ();
- pub(super) fn crypto_mldsa_key_info_read_private_key(key_info: *const c_void) -> *mut c_void;
- pub(super) fn crypto_mldsa_read_public_key(size: MlDsaSize, bytes: Span<'_, u8>) -> *mut c_void;
- pub(super) fn crypto_mldsa_public_bytes(key: *const c_void, bytes: &mut Span<'_, u8>) -> ();
- pub(super) fn crypto_mldsa_seed_bytes(key: *const c_void, state: *mut c_void, receive: ReceiveBytes) -> bool;
- pub(super) fn crypto_mldsa_export_der(
- key: *const c_void,
- is_public: bool,
- oid: Span<'_, u32>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_mlkem_generate_key_pair(
- size: MlKemSize,
- seed: Span<'_, u8>,
- public_key: &mut *mut c_void,
- private_key: &mut *mut c_void,
- ) -> usize;
- pub(super) fn crypto_mlkem_key_info_read_private_key(key_info: *const c_void) -> *mut c_void;
- pub(super) fn crypto_mlkem_read_public_key(bytes: Span<'_, u8>) -> *mut c_void;
- pub(super) fn crypto_mlkem_public_bytes(key: *const c_void, state: *mut c_void, receive: ReceiveBytes) -> ();
- pub(super) fn crypto_mlkem_seed_bytes(key: *const c_void, state: *mut c_void, receive: ReceiveBytes) -> bool;
- pub(super) fn crypto_ml_private_key_has_seed(key: *const c_void) -> bool;
- pub(super) fn crypto_mlkem_export_der(
- key: *const c_void,
- is_public: bool,
- oid: Span<'_, u32>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> bool;
- pub(super) fn crypto_mlkem_encapsulate(
- size: MlKemSize,
- key: *const c_void,
- shared_key: *mut c_void,
- ciphertext: *mut c_void,
- receive: ReceiveBytes,
- ) -> usize;
- pub(super) fn crypto_mlkem_decapsulate(
- size: MlKemSize,
- key: *const c_void,
- ciphertext: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> usize;
- pub(super) fn crypto_fill_with_random(bytes: SpanMut<'_, u8>);
- pub(super) fn crypto_generate_random_uuid(state: *mut c_void, receive: ReceiveBytes);
-}
-
-#[repr(C)]
-pub(super) struct RawArgon2Inputs<'a> {
- password: Span<'a, u8>,
- nonce: Span<'a, u8>,
- parallelism: u32,
- memory: u32,
- passes: u32,
- version: u32,
- secret_value: OptionalBytes<'a>,
- associated_data: OptionalBytes<'a>,
- tag_length: u32,
-}
-
-impl<'a> From<&Argon2Inputs<'a>> for RawArgon2Inputs<'a> {
- fn from(inputs: &Argon2Inputs<'a>) -> Self {
- Self {
- password: Span::new(inputs.password),
- nonce: Span::new(inputs.nonce),
- memory: inputs.memory,
- passes: inputs.passes,
- parallelism: inputs.parallelism,
- version: inputs.version,
- secret_value: inputs.secret_value.into(),
- associated_data: inputs.associated_data.into(),
- tag_length: inputs.tag_length,
- }
- }
-}
diff --git a/Libraries/LibCrypto/Rust/src/key.rs b/Libraries/LibCrypto/Rust/src/key.rs
index 4e39ee44ea3..ea16ee0bc2e 100644
--- a/Libraries/LibCrypto/Rust/src/key.rs
+++ b/Libraries/LibCrypto/Rust/src/key.rs
@@ -6,193 +6,246 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use core::ffi::c_void;
-use core::ptr::NonNull;
-
-use ak::Span;
-
-#[repr(transparent)]
-pub struct KeyHandle(NonNull<c_void>);
+use crate::ec::{self, EcPrivateKey, EcPublicKey};
+use crate::ml::{self, MlDsaPublicKey, MlKemPublicKey, MlPrivateKey};
+use crate::rsa::{self, RsaPrivateKey, RsaPublicKey};
+
+pub struct KeyHandle(pub(crate) Key);
+
+pub(crate) enum Key {
+ Secret(SecretBytes),
+ OkpPublic(Vec<u8>),
+ OkpPrivate(SecretBytes),
+ MlDsaPublic(MlDsaPublicKey),
+ MlKemPublic(MlKemPublicKey),
+ MlPrivate(MlPrivateKey),
+ EcPublic(EcPublicKey),
+ EcPrivate(EcPrivateKey),
+ RsaPublic(RsaPublicKey),
+ RsaPrivate(RsaPrivateKey),
+}
-pub struct KeyPair {
- pub public_key: KeyHandle,
- pub private_key: KeyHandle,
+/// The tag of a stored key, which says what its buffers hold. The values are part of the stable storage serialization
+/// format (Web::Crypto::HandleTag).
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum HandleTag {
+ Secret = 0,
+ RsaPublic = 1,
+ RsaPrivate = 2,
+ EcPublic = 3,
+ EcPrivate = 4,
+ MlDsaPublic = 5,
+ MlDsaPrivate = 6,
+ MlKemPublic = 7,
+ MlKemPrivate = 8,
+ OkpPublic = 9,
+ OkpPrivate = 10,
}
-impl KeyPair {
- pub(super) unsafe fn from_raw(public_key: *mut c_void, private_key: *mut c_void) -> Self {
- // SAFETY: The caller transfers ownership of both native keys.
- let (public_key, private_key) = unsafe { (KeyHandle::from_raw(public_key), KeyHandle::from_raw(private_key)) };
- Self {
- public_key: public_key.expect("LibCrypto returns a public key"),
- private_key: private_key.expect("LibCrypto returns a private key"),
+impl HandleTag {
+ const ALL: [Self; 11] = [
+ Self::Secret,
+ Self::RsaPublic,
+ Self::RsaPrivate,
+ Self::EcPublic,
+ Self::EcPrivate,
+ Self::MlDsaPublic,
+ Self::MlDsaPrivate,
+ Self::MlKemPublic,
+ Self::MlKemPrivate,
+ Self::OkpPublic,
+ Self::OkpPrivate,
+ ];
+
+ /// The number of buffers that a key of this tag stores. An EC private key stores one, followed by its public key's
+ /// two when it has its public key.
+ pub fn buffer_count(self) -> usize {
+ match self {
+ Self::Secret
+ | Self::EcPrivate
+ | Self::MlDsaPublic
+ | Self::MlKemPublic
+ | Self::OkpPublic
+ | Self::OkpPrivate => 1,
+ Self::RsaPublic | Self::EcPublic => 2,
+ Self::MlDsaPrivate | Self::MlKemPrivate => 3,
+ Self::RsaPrivate => 8,
}
}
}
-#[derive(Debug)]
-pub enum KeyDecodeError {
- InvalidComponents,
- OutOfMemory,
+impl TryFrom<u8> for HandleTag {
+ type Error = KeyDecodeError;
+
+ fn try_from(value: u8) -> Result<Self, KeyDecodeError> {
+ Self::ALL
+ .get(usize::from(value))
+ .copied()
+ .ok_or(KeyDecodeError::InvalidComponents)
+ }
}
-pub struct KeyComponents<'a> {
- pub tag: u8,
- buffers: [&'a [u8]; 8],
- buffer_count: usize,
- pub ec_parameters: Option<&'a [u32]>,
+/// The stored form of a key: its tag, its buffers and, for an EC private key, the curve it was given with and whether
+/// it has its public key.
+pub struct StoredKey {
+ pub tag: HandleTag,
+ pub(crate) buffers: Vec<SecretBytes>,
+ pub ec_parameters: Option<Vec<u32>>,
pub has_ec_public_key: bool,
}
-impl<'a> KeyComponents<'a> {
- pub fn buffers(&self) -> &[&'a [u8]] {
- &self.buffers[..self.buffer_count]
+impl StoredKey {
+ pub(crate) fn new(tag: HandleTag, buffers: Vec<SecretBytes>) -> Self {
+ Self {
+ tag,
+ buffers,
+ ec_parameters: None,
+ has_ec_public_key: false,
+ }
+ }
+
+ pub fn buffers(&self) -> Vec<&[u8]> {
+ self.buffers.iter().map(|buffer| &**buffer).collect()
}
}
-/// The result of decoding a key handle, Crypto's KeyDecodeResult.
-#[repr(u8)]
-#[allow(dead_code, reason = "LibCrypto constructs the variants")]
-enum RawKeyDecodeResult {
- Decoded,
- InvalidComponents,
- OutOfMemory,
+/// Bytes that are cleared when they are dropped.
+pub(crate) struct SecretBytes(Vec<u8>);
+
+impl SecretBytes {
+ pub(crate) fn new(bytes: Vec<u8>) -> Self {
+ Self(bytes)
+ }
+
+ /// Shortens the bytes to `length`, clearing the ones cut off.
+ pub(crate) fn truncate(&mut self, length: usize) {
+ if length < self.0.len() {
+ clear(&mut self.0[length..]);
+ self.0.truncate(length);
+ }
+ }
+
+ /// Appends `bytes`, which must fit in the capacity reserved so that no partial copy is left behind by a reallocation.
+ pub(crate) fn extend_from_slice(&mut self, bytes: &[u8]) {
+ assert!(self.0.len() + bytes.len() <= self.0.capacity());
+ self.0.extend_from_slice(bytes);
+ }
+
+ pub(crate) fn into_vec(mut self) -> Vec<u8> {
+ core::mem::take(&mut self.0)
+ }
}
-#[repr(C)]
-struct RawKeyComponents<'a> {
- tag: u8,
- buffers: [Span<'a, u8>; 8],
- buffer_count: usize,
- has_ec_parameters: bool,
- ec_parameters: Span<'a, u32>,
- has_ec_public_key: bool,
+impl core::ops::Deref for SecretBytes {
+ type Target = [u8];
+
+ fn deref(&self) -> &[u8] {
+ &self.0
+ }
}
-unsafe extern "C" {
- fn crypto_key_destroy_handle(key: *mut c_void);
- fn crypto_key_create_byte_handle(bytes: Span<'_, u8>) -> *mut c_void;
- fn crypto_key_create_okp_handle(is_private: bool, bytes: Span<'_, u8>) -> *mut c_void;
- fn crypto_key_byte_handle_bytes(key: *const c_void, bytes: &mut Span<'_, u8>);
- fn crypto_key_okp_handle_bytes(key: *const c_void, bytes: &mut Span<'_, u8>);
- fn crypto_key_encode_handle(
- key: *const c_void,
- state: *mut c_void,
- steps: unsafe extern "C" fn(*mut c_void, *const RawKeyComponents<'_>),
- );
- fn crypto_key_decode_handle(fields: &RawKeyComponents<'_>, key: &mut *mut c_void) -> RawKeyDecodeResult;
+impl core::ops::DerefMut for SecretBytes {
+ fn deref_mut(&mut self) -> &mut [u8] {
+ &mut self.0
+ }
}
-impl KeyHandle {
- /// # Safety
- ///
- /// A non-null pointer must transfer ownership of a LibCrypto key handle.
- pub unsafe fn from_raw(key: *mut c_void) -> Option<Self> {
- NonNull::new(key).map(Self)
+impl Drop for SecretBytes {
+ fn drop(&mut self) {
+ clear(&mut self.0);
}
+}
- pub fn as_raw(&self) -> *mut c_void {
- self.0.as_ptr()
+/// Overwrites `bytes` with zeros in a way the compiler does not remove.
+pub(crate) fn clear(bytes: &mut [u8]) {
+ for byte in bytes.iter_mut() {
+ // SAFETY: The pointer comes from a live mutable reference.
+ unsafe { core::ptr::write_volatile(byte, 0) };
}
+ core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
+}
+
+pub struct KeyPair {
+ pub public_key: KeyHandle,
+ pub private_key: KeyHandle,
+}
+
+#[derive(Debug)]
+pub enum KeyDecodeError {
+ InvalidComponents,
+}
+impl KeyHandle {
pub fn from_secret_bytes(bytes: &[u8]) -> Self {
- // SAFETY: The input is borrowed for the copy.
- let key = unsafe { crypto_key_create_byte_handle(Span::new(bytes)) };
- // SAFETY: The native call transfers ownership of the key.
- unsafe { Self::from_raw(key) }.expect("LibCrypto returns a secret key")
+ Self(Key::Secret(SecretBytes::new(bytes.to_vec())))
}
pub fn from_okp_bytes(is_private: bool, bytes: &[u8]) -> Self {
- // SAFETY: The input is borrowed for the copy.
- let key = unsafe { crypto_key_create_okp_handle(is_private, Span::new(bytes)) };
- // SAFETY: The native call transfers ownership of the key.
- unsafe { Self::from_raw(key) }.expect("LibCrypto returns an OKP key")
+ Self(if is_private {
+ Key::OkpPrivate(SecretBytes::new(bytes.to_vec()))
+ } else {
+ Key::OkpPublic(bytes.to_vec())
+ })
}
pub fn secret_bytes(&self) -> &[u8] {
- let mut bytes = Span::default();
- // SAFETY: The key owns the returned bytes.
- unsafe { crypto_key_byte_handle_bytes(self.as_raw(), &mut bytes) };
- bytes.as_slice()
+ match &self.0 {
+ Key::Secret(bytes) => bytes,
+ _ => panic!("The key is not a secret key"),
+ }
}
pub fn okp_bytes(&self) -> &[u8] {
- let mut bytes = Span::default();
- // SAFETY: The key owns the returned bytes.
- unsafe { crypto_key_okp_handle_bytes(self.as_raw(), &mut bytes) };
- bytes.as_slice()
- }
-
- pub fn with_components<R>(&self, callback: impl FnOnce(KeyComponents<'_>) -> R) -> R {
- fn run<F: FnOnce(KeyComponents<'_>) -> R, R>(key: &KeyHandle, callback: F) -> R {
- unsafe extern "C" fn receive<F: FnOnce(KeyComponents<'_>) -> R, R>(
- state: *mut c_void,
- fields: *const RawKeyComponents<'_>,
- ) {
- // SAFETY: LibCrypto invokes the callback synchronously with the live slots.
- let (state, fields) = unsafe { (&mut *state.cast::<(Option<F>, Option<R>)>(), &*fields) };
- let callback = state.0.take().expect("LibCrypto supplies the components once");
- state.1 = Some(callback(KeyComponents {
- tag: fields.tag,
- buffers: fields.buffers.map(Span::as_slice),
- buffer_count: fields.buffer_count,
- ec_parameters: fields.has_ec_parameters.then(|| fields.ec_parameters.as_slice()),
- has_ec_public_key: fields.has_ec_public_key,
- }));
- }
- let mut state: (Option<F>, Option<R>) = (Some(callback), None);
- // SAFETY: The key and callback state are live for the synchronous native call.
- unsafe { crypto_key_encode_handle(key.as_raw(), core::ptr::from_mut(&mut state).cast(), receive::<F, R>) };
- state.1.expect("LibCrypto supplies the key components")
+ match &self.0 {
+ Key::OkpPublic(bytes) => bytes,
+ Key::OkpPrivate(bytes) => bytes,
+ _ => panic!("The key is not an OKP key"),
+ }
+ }
+
+ pub(crate) fn is_okp_private(&self) -> bool {
+ matches!(self.0, Key::OkpPrivate(_))
+ }
+
+ pub fn to_stored(&self) -> StoredKey {
+ match &self.0 {
+ Key::Secret(bytes) => StoredKey::new(HandleTag::Secret, vec![SecretBytes::new(bytes.to_vec())]),
+ Key::OkpPublic(bytes) => StoredKey::new(HandleTag::OkpPublic, vec![SecretBytes::new(bytes.clone())]),
+ Key::OkpPrivate(bytes) => StoredKey::new(HandleTag::OkpPrivate, vec![SecretBytes::new(bytes.to_vec())]),
+ Key::EcPublic(key) => key.stored(),
+ Key::EcPrivate(key) => key.stored(),
+ Key::RsaPublic(key) => key.stored(),
+ Key::RsaPrivate(key) => key.stored(),
+ Key::MlDsaPublic(key) => key.stored(),
+ Key::MlKemPublic(key) => key.stored(),
+ Key::MlPrivate(key) => key.stored(),
}
- run(self, callback)
}
- pub fn from_components(
- tag: u8,
+ /// The key that a stored form holds, as `to_stored()` gives it.
+ pub fn from_stored(
+ tag: HandleTag,
buffers: &[&[u8]],
ec_parameters: Option<&[u32]>,
has_ec_public_key: bool,
) -> Result<Self, KeyDecodeError> {
- let expected = match tag {
- 0 | 5 | 7 | 9 | 10 => 1,
- 1 | 3 => 2,
- 2 => 8,
- 4 if has_ec_public_key => 3,
- 4 => 1,
- 6 | 8 => 3,
- _ => return Err(KeyDecodeError::InvalidComponents),
- };
- if buffers.len() != expected || (tag != 4 && (ec_parameters.is_some() || has_ec_public_key)) {
+ let is_ec_private_key = tag == HandleTag::EcPrivate;
+ let expected = tag.buffer_count() + if has_ec_public_key { 2 } else { 0 };
+ if buffers.len() != expected || (!is_ec_private_key && (ec_parameters.is_some() || has_ec_public_key)) {
return Err(KeyDecodeError::InvalidComponents);
}
- let mut spans = [Span::default(); 8];
- for (span, bytes) in spans.iter_mut().zip(buffers) {
- *span = Span::new(bytes);
- }
- let fields = RawKeyComponents {
- tag,
- buffers: spans,
- buffer_count: buffers.len(),
- has_ec_parameters: ec_parameters.is_some(),
- ec_parameters: Span::new(ec_parameters.unwrap_or_default()),
- has_ec_public_key,
- };
- let mut key = core::ptr::null_mut();
- // SAFETY: The validated fields and output slot are live for the call.
- match unsafe { crypto_key_decode_handle(&fields, &mut key) } {
- RawKeyDecodeResult::Decoded => {}
- RawKeyDecodeResult::InvalidComponents => return Err(KeyDecodeError::InvalidComponents),
- RawKeyDecodeResult::OutOfMemory => return Err(KeyDecodeError::OutOfMemory),
+ match tag {
+ HandleTag::Secret => Ok(Self::from_secret_bytes(buffers[0])),
+ HandleTag::OkpPublic => Ok(Self::from_okp_bytes(false, buffers[0])),
+ HandleTag::OkpPrivate => Ok(Self::from_okp_bytes(true, buffers[0])),
+ HandleTag::RsaPublic | HandleTag::RsaPrivate => rsa::decode_stored(tag, buffers),
+ HandleTag::EcPublic | HandleTag::EcPrivate => {
+ ec::decode_stored(tag, buffers, ec_parameters, has_ec_public_key)
+ }
+ HandleTag::MlDsaPublic | HandleTag::MlDsaPrivate | HandleTag::MlKemPublic | HandleTag::MlKemPrivate => {
+ ml::decode_stored(tag, buffers)
+ }
}
- // SAFETY: Success transfers ownership of the native key.
- Ok(unsafe { Self::from_raw(key) }.expect("LibCrypto returns the decoded key"))
- }
-}
-
-impl Drop for KeyHandle {
- fn drop(&mut self) {
- // SAFETY: This value owns the native handle.
- unsafe { crypto_key_destroy_handle(self.as_raw()) };
}
}
diff --git a/Libraries/LibCrypto/Rust/src/key_info.rs b/Libraries/LibCrypto/Rust/src/key_info.rs
index 3947349661e..296e1708767 100644
--- a/Libraries/LibCrypto/Rust/src/key_info.rs
+++ b/Libraries/LibCrypto/Rust/src/key_info.rs
@@ -6,125 +6,215 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use core::ffi::c_void;
-use core::ptr::NonNull;
-
-use ak::{Span, Utf16String};
+use super::{CryptoError, EcCurve, KeyHandle, MlDsaSize, MlKemSize, OkpCurve, der, ec, ml, rsa};
+use crate::key::SecretBytes;
+use crate::openssl::{self, KeyKind, Pkey};
+
+/// The algorithm of a SubjectPublicKeyInfo or PrivateKeyInfo.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum KeyAlgorithm {
+ Rsa,
+ Ec,
+ Okp(OkpCurve),
+ MlDsa(MlDsaSize),
+ MlKem(MlKemSize),
+}
-use super::{Asn1Structure, KeyHandle, OkpCurve, ffi, result_from_error};
+impl KeyAlgorithm {
+ const ALL: [Self; 12] = [
+ Self::Rsa,
+ Self::Ec,
+ Self::Okp(OkpCurve::X25519),
+ Self::Okp(OkpCurve::X448),
+ Self::Okp(OkpCurve::Ed25519),
+ Self::Okp(OkpCurve::Ed448),
+ Self::MlDsa(MlDsaSize::MlDsa44),
+ Self::MlDsa(MlDsaSize::MlDsa65),
+ Self::MlDsa(MlDsaSize::MlDsa87),
+ Self::MlKem(MlKemSize::MlKem512),
+ Self::MlKem(MlKemSize::MlKem768),
+ Self::MlKem(MlKemSize::MlKem1024),
+ ];
+
+ /// The contents of the DER encoding of the algorithm's object identifier.
+ pub(crate) fn oid(self) -> &'static [u8] {
+ match self {
+ // rsaEncryption, 1.2.840.113549.1.1.1
+ Self::Rsa => &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01],
+ // id-ecPublicKey, 1.2.840.10045.2.1
+ Self::Ec => &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01],
+ // id-X25519, id-X448, id-Ed25519 and id-Ed448, 1.3.101.110 to 1.3.101.113
+ Self::Okp(OkpCurve::X25519) => &[0x2b, 0x65, 0x6e],
+ Self::Okp(OkpCurve::X448) => &[0x2b, 0x65, 0x6f],
+ Self::Okp(OkpCurve::Ed25519) => &[0x2b, 0x65, 0x70],
+ Self::Okp(OkpCurve::Ed448) => &[0x2b, 0x65, 0x71],
+ // id-ml-dsa-44, id-ml-dsa-65 and id-ml-dsa-87, 2.16.840.1.101.3.4.3.17 to 2.16.840.1.101.3.4.3.19
+ Self::MlDsa(MlDsaSize::MlDsa44) => &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x11],
+ Self::MlDsa(MlDsaSize::MlDsa65) => &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x12],
+ Self::MlDsa(MlDsaSize::MlDsa87) => &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x13],
+ // id-alg-ml-kem-512, id-alg-ml-kem-768 and id-alg-ml-kem-1024, 2.16.840.1.101.3.4.4.1 to 2.16.840.1.101.3.4.4.3
+ Self::MlKem(MlKemSize::MlKem512) => &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x01],
+ Self::MlKem(MlKemSize::MlKem768) => &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x02],
+ Self::MlKem(MlKemSize::MlKem1024) => &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x03],
+ }
+ }
-pub enum Asn1Value<'a> {
- KeyInfo(KeyInfo),
- OctetString(&'a [u8]),
+ fn from_oid(oid: &[u8]) -> Option<Self> {
+ Self::ALL.into_iter().find(|algorithm| algorithm.oid() == oid)
+ }
}
+/// A SubjectPublicKeyInfo or PrivateKeyInfo.
pub struct KeyInfo {
- structure: Asn1Structure,
- ptr: NonNull<c_void>,
+ is_private: bool,
+ algorithm: Option<KeyAlgorithm>,
+ has_parameters: bool,
+ named_curve: Option<EcCurve>,
+ raw_key: SecretBytes,
+ // The RSA, EC, ML-DSA or ML-KEM key of the structure, parsed while the structure is.
+ parsed_key: Option<KeyHandle>,
+ is_ml_expanded_key_form: bool,
}
-pub fn decode_asn1_structure(data: &[u8], structure: Asn1Structure) -> Result<(Asn1Value<'_>, bool), Utf16String> {
- // SAFETY: LibCrypto allocates storage of the selected structure.
- let raw = unsafe { ffi::crypto_asn1_allocate_key_info(structure) };
- let native = KeyInfo {
- structure,
- ptr: NonNull::new(raw).expect("LibCrypto returns the ASN.1 structure"),
- };
- let mut all_consumed = false;
- // SAFETY: The input and native storage of the selected structure live for the call.
- let status = unsafe {
- ffi::crypto_decode_asn1_structure(Span::new(data), structure, native.ptr.as_ptr(), &mut all_consumed)
- };
- result_from_error(status)?;
- let value = if matches!(structure, Asn1Structure::OctetString) {
- let mut bytes = Span::default();
- // SAFETY: This native value is an octet string that borrows its bytes from data.
- unsafe { ffi::crypto_asn1_octet_string_bytes(native.ptr.as_ptr(), &mut bytes) };
- Asn1Value::OctetString(bytes.as_slice())
- } else {
- Asn1Value::KeyInfo(native)
- };
- Ok((value, all_consumed))
+fn kind_of(oid: &[u8]) -> KeyKind {
+ match KeyAlgorithm::from_oid(oid) {
+ Some(KeyAlgorithm::Rsa) => KeyKind::Rsa,
+ Some(KeyAlgorithm::Ec) => KeyKind::Ec,
+ Some(KeyAlgorithm::MlDsa(_)) => KeyKind::MlDsa,
+ Some(KeyAlgorithm::MlKem(_)) => KeyKind::MlKem,
+ Some(KeyAlgorithm::Okp(_)) | None => KeyKind::Other,
+ }
}
impl KeyInfo {
- pub fn has_rsa_encryption_oid(&self) -> bool {
- // SAFETY: The native value matches its structure tag.
- unsafe { ffi::crypto_rsa_key_info_has_encryption_oid(self.structure, self.ptr.as_ptr()) }
+ fn new(is_private: bool, algorithm: openssl::AlgorithmIdentifier, raw_key: SecretBytes) -> Self {
+ Self {
+ is_private,
+ algorithm: KeyAlgorithm::from_oid(&algorithm.oid),
+ has_parameters: algorithm.has_parameters(),
+ named_curve: algorithm.curve.as_deref().and_then(EcCurve::from_oid),
+ raw_key,
+ parsed_key: None,
+ is_ml_expanded_key_form: false,
+ }
}
+}
- pub fn rsa_key(&self) -> KeyHandle {
- // SAFETY: The native value matches its structure tag.
- let raw = unsafe { ffi::crypto_rsa_key_info_read_key(self.structure, self.ptr.as_ptr()) };
- // SAFETY: The native call transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns an RSA key")
+/// The contents of the DER OCTET STRING at the start of `data`, and whether it takes all of `data`.
+pub fn parse_octet_string(data: &[u8]) -> Result<(&[u8], bool), CryptoError> {
+ let invalid = || CryptoError::Invalid("Invalid OCTET STRING");
+ let (&tag, rest) = data.split_first().ok_or_else(invalid)?;
+ let (&first_length_byte, mut rest) = rest.split_first().ok_or_else(invalid)?;
+ if tag != der::OCTET_STRING {
+ return Err(invalid());
}
-
- pub fn has_ec_public_key_oid(&self) -> bool {
- // SAFETY: The native value matches its structure tag.
- unsafe { ffi::crypto_ec_key_info_has_public_key_oid(self.structure, self.ptr.as_ptr()) }
+ let length = if first_length_byte & 0x80 == 0 {
+ usize::from(first_length_byte)
+ } else {
+ let count = usize::from(first_length_byte & 0x7f);
+ if count == 0 || count > size_of::<usize>() || rest.len() < count {
+ return Err(invalid());
+ }
+ let (length_bytes, after) = rest.split_at(count);
+ rest = after;
+ length_bytes
+ .iter()
+ .fold(0, |length, &byte| (length << 8) | usize::from(byte))
+ };
+ let header_length = data.len() - rest.len();
+ if rest.len() < length {
+ return Err(invalid());
}
-
- pub fn ec_parameters(&self) -> Option<&[u32]> {
- let mut parameters = Span::default();
- // SAFETY: The native value matches its structure tag and owns the parameters.
- let has_parameters =
- unsafe { ffi::crypto_ec_key_info_parameters(self.structure, self.ptr.as_ptr(), &mut parameters) };
- has_parameters.then(|| parameters.as_slice())
+ // NB: DER gives each length a single encoding, which is the one this writes.
+ if data[..header_length] != der::header(der::OCTET_STRING, length) {
+ return Err(CryptoError::Invalid("OCTET STRING is not in DER"));
}
+ Ok((&rest[..length], header_length + length == data.len()))
+}
- pub fn ec_private_parameters_match(&self) -> bool {
- assert!(matches!(self.structure, Asn1Structure::PrivateKeyInfo));
- // SAFETY: This is a native private key info value.
- unsafe { ffi::crypto_ec_private_key_info_parameters_match(self.ptr.as_ptr()) }
- }
+/// The DER SubjectPublicKeyInfo at the start of `data`, and whether it takes all of `data`.
+pub fn parse_subject_public_key_info(data: &[u8]) -> Result<(KeyInfo, bool), CryptoError> {
+ let parsed = openssl::parse_subject_public_key_info(data, kind_of).map_err(CryptoError::Invalid)?;
+ let key_info = KeyInfo::new(false, parsed.algorithm, SecretBytes::new(parsed.raw_key));
+ let key_info = with_parsed_key(key_info, parsed.key, None)?;
+ Ok((key_info, parsed.consumed == data.len()))
+}
+
+/// The DER PrivateKeyInfo at the start of `data`, and whether it takes all of `data`.
+pub fn parse_private_key_info(data: &[u8]) -> Result<(KeyInfo, bool), CryptoError> {
+ let parsed = openssl::parse_private_key_info(data, kind_of).map_err(CryptoError::Invalid)?;
+ let key_info = KeyInfo::new(true, parsed.algorithm, parsed.raw_key);
+ let key_info = with_parsed_key(key_info, None, parsed.key)?;
+ Ok((key_info, parsed.consumed == data.len()))
+}
- pub fn ec_key(&self) -> KeyHandle {
- // SAFETY: The native value matches its structure tag.
- let raw = unsafe { ffi::crypto_ec_key_info_read_key(self.structure, self.ptr.as_ptr()) };
- // SAFETY: The native call transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns an EC key")
+/// The structure with the key of its algorithm, for the algorithms whose keys are parsed with the structure.
+// NB: OpenSSL decodes the RSA and EC keys of either structure, so those keys are taken from it.
+fn with_parsed_key(
+ mut key_info: KeyInfo,
+ public_key: Option<Pkey>,
+ private_key: Option<Pkey>,
+) -> Result<KeyInfo, CryptoError> {
+ match key_info.algorithm {
+ Some(KeyAlgorithm::Rsa) => {
+ key_info.parsed_key = Some(match (public_key, private_key) {
+ (_, Some(private_key)) => rsa::from_private_key(private_key),
+ (Some(public_key), _) => rsa::from_public_key(public_key),
+ _ => unreachable!("OpenSSL decodes RSA keys"),
+ });
+ }
+ Some(KeyAlgorithm::Ec) => {
+ let curve = key_info
+ .named_curve
+ .ok_or(CryptoError::Invalid("Unsupported EC parameters"))?;
+ let key = if let Some(private_key) = private_key {
+ ec::parse_private_key_info(curve, private_key, key_info.raw_key())?
+ } else {
+ ec::parse_subject_public_key(key_info.raw_key())?
+ };
+ key_info.parsed_key = Some(key);
+ }
+ Some(algorithm @ (KeyAlgorithm::MlDsa(_) | KeyAlgorithm::MlKem(_))) if key_info.is_private => {
+ match ml::parse_private_key(algorithm, key_info.raw_key())? {
+ Some(private_key) => key_info.parsed_key = Some(private_key),
+ None => key_info.is_ml_expanded_key_form = true,
+ }
+ }
+ _ => {}
}
+ Ok(key_info)
+}
- pub fn has_okp_oid(&self, curve: OkpCurve) -> bool {
- // SAFETY: The native value matches its structure tag.
- unsafe { ffi::crypto_okp_key_info_has_oid(curve, self.structure, self.ptr.as_ptr()) }
+impl KeyInfo {
+ /// The key of the structure's algorithm, which is parsed with an RSA or EC structure, or an ML-DSA or ML-KEM
+ /// PrivateKeyInfo.
+ pub fn take_key(&mut self) -> KeyHandle {
+ self.parsed_key
+ .take()
+ .expect("The structure holds a key of its algorithm")
}
- pub fn raw_key(&self) -> &[u8] {
- let mut bytes = Span::default();
- // SAFETY: The native value matches its structure tag and owns the bytes.
- unsafe { ffi::crypto_asn1_key_info_raw_key(self.structure, self.ptr.as_ptr(), &mut bytes) };
- bytes.as_slice()
+ /// Whether the privateKey of an ML-DSA or ML-KEM PrivateKeyInfo is in the expandedKey form, which has no key.
+ pub fn is_ml_expanded_key_form(&self) -> bool {
+ self.is_ml_expanded_key_form
}
- pub fn oid(&self) -> &[u32] {
- let mut oid = Span::default();
- // SAFETY: The native value matches its structure tag and owns the identifier.
- unsafe { ffi::crypto_asn1_key_info_identifier(self.structure, self.ptr.as_ptr(), &mut oid) };
- oid.as_slice()
+ /// The algorithm the structure names, if it is one of those that Web Crypto supports.
+ pub fn algorithm(&self) -> Option<KeyAlgorithm> {
+ self.algorithm
}
- pub fn mldsa_private_key(&self) -> KeyHandle {
- assert!(matches!(self.structure, Asn1Structure::PrivateKeyInfo));
- // SAFETY: This is a native private key info value.
- let raw = unsafe { ffi::crypto_mldsa_key_info_read_private_key(self.ptr.as_ptr()) };
- // SAFETY: The native call transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns an ML-DSA key")
+ /// Whether the structure's AlgorithmIdentifier has parameters.
+ pub fn has_parameters(&self) -> bool {
+ self.has_parameters
}
- pub fn mlkem_private_key(&self) -> KeyHandle {
- assert!(matches!(self.structure, Asn1Structure::PrivateKeyInfo));
- // SAFETY: This is a native private key info value.
- let raw = unsafe { ffi::crypto_mlkem_key_info_read_private_key(self.ptr.as_ptr()) };
- // SAFETY: The native call transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns an ML-KEM key")
+ /// The curve the structure's parameters name, if they name P-256, P-384 or P-521.
+ pub fn named_curve(&self) -> Option<EcCurve> {
+ self.named_curve
}
-}
-impl Drop for KeyInfo {
- fn drop(&mut self) {
- // SAFETY: This value owns the native structure.
- unsafe { ffi::crypto_asn1_delete_key_info(self.structure, self.ptr.as_ptr()) };
+ pub fn raw_key(&self) -> &[u8] {
+ &self.raw_key
}
}
diff --git a/Libraries/LibCrypto/Rust/src/lib.rs b/Libraries/LibCrypto/Rust/src/lib.rs
index edb2cd8d78a..6e57672f628 100644
--- a/Libraries/LibCrypto/Rust/src/lib.rs
+++ b/Libraries/LibCrypto/Rust/src/lib.rs
@@ -9,26 +9,60 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use core::ffi::c_void;
+use core::ffi::{CStr, c_int, c_uint};
-use ak::{Span, SpanMut, Utf16String};
+use ak::Utf16String;
use subtle::ConstantTimeEq;
-mod ffi;
+use key::SecretBytes;
+use openssl::{Cipher, CipherContext, Pkey, end_parameter, octet_string_parameter, uint_parameter, utf8_parameter};
+
+mod der;
+mod ec;
mod key;
mod key_info;
-
-pub use key::{KeyComponents, KeyDecodeError, KeyHandle, KeyPair};
-pub use key_info::{Asn1Value, KeyInfo, decode_asn1_structure};
-
-use ffi::ReceiveBytes;
-
+mod ml;
+mod openssl;
+mod rsa;
+mod sys;
+
+pub use ec::{
+ ec_compute_coordinate, ec_export_der, ec_export_private_scalar, ec_export_public_coordinates,
+ ec_export_uncompressed, ec_generate_key_pair, ec_key_from_coordinates, ec_key_is_valid, ec_parse_raw_public_key,
+ ec_public_key_scalar_size, ec_sign, ec_verify,
+};
+pub use key::{HandleTag, KeyDecodeError, KeyHandle, KeyPair, StoredKey};
+pub use key_info::{KeyAlgorithm, KeyInfo, parse_octet_string, parse_private_key_info, parse_subject_public_key_info};
+pub use ml::{
+ ml_export_der, ml_seed_bytes, mldsa_generate_key_pair, mldsa_public_bytes, mldsa_read_public_key, mldsa_sign,
+ mldsa_verify, mlkem_decapsulate, mlkem_encapsulate, mlkem_generate_key_pair, mlkem_public_bytes,
+ mlkem_read_public_key,
+};
+pub use rsa::{
+ RsaSignaturePadding, rsa_export_der, rsa_export_jwk_integer, rsa_export_public_exponent, rsa_generate_key_pair,
+ rsa_key_from_components, rsa_key_is_valid, rsa_oaep_cipher, rsa_read_key_metadata, rsa_sign,
+ rsa_validate_modulus_length, rsa_validate_public_exponent, rsa_verify,
+};
+
+/// The error of an operation: an input that it rejects, for the reason given, or a failure of OpenSSL.
#[derive(Debug)]
-pub struct BackendError;
+pub enum CryptoError {
+ Invalid(&'static str),
+ Backend,
+}
-#[repr(i32)]
+impl CryptoError {
+ pub fn message(&self) -> &'static str {
+ match self {
+ Self::Invalid(reason) => reason,
+ Self::Backend => "The cryptographic operation failed",
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
pub enum ShaHashKind {
- Sha1 = 2,
+ Sha1,
Sha256,
Sha384,
Sha512,
@@ -37,36 +71,31 @@ pub enum ShaHashKind {
Sha3_512,
}
-#[repr(i32)]
pub enum CShakeKind {
CShake128,
CShake256,
}
-#[repr(i32)]
#[derive(Clone, Copy)]
pub enum KmacKind {
Kmac128,
Kmac256,
}
-#[repr(i32)]
pub enum Argon2Type {
Argon2d,
Argon2i,
Argon2id,
}
-#[derive(Clone, Copy)]
-#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
pub enum EcCurve {
P256,
P384,
P521,
}
-#[derive(Clone, Copy)]
-#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
pub enum OkpCurve {
Ed25519,
Ed448,
@@ -74,7 +103,6 @@ pub enum OkpCurve {
X448,
}
-#[repr(u8)]
pub enum RsaJwkInteger {
Modulus,
PublicExponent,
@@ -86,85 +114,139 @@ pub enum RsaJwkInteger {
Coefficient,
}
-#[derive(Clone, Copy)]
-#[repr(i32)]
+#[derive(Clone, Copy, PartialEq, Eq)]
pub enum MlDsaSize {
MlDsa44,
MlDsa65,
MlDsa87,
}
-#[derive(Clone, Copy)]
-#[repr(i32)]
+#[derive(Clone, Copy, PartialEq, Eq)]
pub enum MlKemSize {
MlKem512,
MlKem768,
MlKem1024,
}
-#[derive(Clone, Copy)]
-#[repr(u8)]
-pub enum Asn1Structure {
- SubjectPublicKeyInfo,
- PrivateKeyInfo,
- OctetString,
-}
-
pub struct Argon2Inputs<'a> {
pub password: &'a [u8],
pub nonce: &'a [u8],
pub memory: u32,
pub passes: u32,
pub parallelism: u32,
- pub version: u32,
pub secret_value: Option<&'a [u8]>,
pub associated_data: Option<&'a [u8]>,
pub tag_length: u32,
}
-unsafe extern "C" fn receive_bytes(state: *mut c_void, bytes: Span<'_, u8>) {
- // SAFETY: The native call supplies the output slot and lends the bytes during the callback.
- unsafe { *state.cast::<Vec<u8>>() = bytes.as_slice().to_vec() };
+pub fn fill_with_random(bytes: &mut [u8]) {
+ // NB: As with AK's fill_with_random(), a failure to produce random bytes is not something to recover from.
+ openssl::fill_with_random(bytes).expect("OpenSSL produces random bytes");
+}
+
+impl ShaHashKind {
+ /// The name of the digest, as OpenSSL takes it.
+ pub(crate) fn name(&self) -> &'static CStr {
+ match self {
+ Self::Sha1 => c"SHA1",
+ Self::Sha256 => c"SHA2-256",
+ Self::Sha384 => c"SHA2-384",
+ Self::Sha512 => c"SHA2-512",
+ Self::Sha3_256 => c"SHA3-256",
+ Self::Sha3_384 => c"SHA3-384",
+ Self::Sha3_512 => c"SHA3-512",
+ }
+ }
}
-fn receive_native_bytes<T>(call: impl FnOnce(*mut c_void, ReceiveBytes) -> T) -> (T, Vec<u8>) {
- let mut bytes = Vec::new();
- let status = call(core::ptr::from_mut(&mut bytes).cast(), receive_bytes);
- (status, bytes)
+pub fn sha_digest(kind: ShaHashKind, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ openssl::digest(kind.name(), data)
}
-fn result_from_error(raw: usize) -> Result<(), Utf16String> {
- if raw == 0 {
- Ok(())
- } else {
- // SAFETY: A nonzero error returned by LibCrypto transfers an owned string.
- Err(unsafe { Utf16String::from_raw_owned(raw) })
+pub fn hash_digest_size(kind: ShaHashKind) -> usize {
+ match kind {
+ ShaHashKind::Sha1 => 20,
+ ShaHashKind::Sha256 | ShaHashKind::Sha3_256 => 32,
+ ShaHashKind::Sha384 | ShaHashKind::Sha3_384 => 48,
+ ShaHashKind::Sha512 | ShaHashKind::Sha3_512 => 64,
}
}
-pub fn fill_with_random(bytes: &mut [u8]) {
- // SAFETY: The native function writes into the span during the call.
- unsafe { ffi::crypto_fill_with_random(SpanMut::new(bytes)) };
+pub fn hmac_sign(kind: ShaHashKind, key: &[u8], message: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let params = [utf8_parameter(c"digest", kind.name()), end_parameter()];
+ openssl::mac(c"HMAC", key, message, hash_digest_size(kind), &params)
}
-pub fn generate_random_uuid() -> Utf16String {
- // SAFETY: The native function invokes the receiver synchronously.
- let ((), bytes) =
- receive_native_bytes(|state, receive| unsafe { ffi::crypto_generate_random_uuid(state, receive) });
- Utf16String::from_ascii(&bytes)
+pub fn hkdf_derive_key(
+ kind: ShaHashKind,
+ salt: &[u8],
+ key: &[u8],
+ info: &[u8],
+ length: u32,
+) -> Result<Vec<u8>, CryptoError> {
+ let params = [
+ utf8_parameter(c"digest", kind.name()),
+ octet_string_parameter(c"key", key),
+ octet_string_parameter(c"salt", salt),
+ octet_string_parameter(c"info", info),
+ end_parameter(),
+ ];
+ let mut derived = vec![0; length as usize];
+ openssl::kdf(c"HKDF", &params, &mut derived)?;
+ Ok(derived)
}
-pub fn sha_digest(kind: ShaHashKind, data: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) =
- receive_native_bytes(|state, receive| unsafe { ffi::crypto_sha_digest(kind, Span::new(data), state, receive) });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
+pub fn pbkdf2_derive_key(
+ kind: ShaHashKind,
+ password: &[u8],
+ salt: &[u8],
+ iterations: u32,
+ length: u32,
+) -> Result<Vec<u8>, CryptoError> {
+ // NB: OpenSSL's PBKDF2 takes the iteration count and the lengths as int.
+ let fits_in_int = |value: usize| c_int::try_from(value).is_ok();
+ if ![iterations as usize, password.len(), salt.len(), length as usize]
+ .into_iter()
+ .all(fits_in_int)
+ {
+ return Err(CryptoError::Backend);
+ }
+ let mut iterations: c_uint = iterations;
+ // NB: Web Crypto does not impose SP 800-132's lower bounds on the salt, iterations and key length, which OpenSSL
+ // checks unless asked for PKCS #5 behaviour.
+ let mut pkcs5 = 1;
+ let params = [
+ utf8_parameter(c"digest", kind.name()),
+ octet_string_parameter(c"pass", password),
+ octet_string_parameter(c"salt", salt),
+ uint_parameter(c"iter", &mut iterations),
+ openssl::int_parameter(c"pkcs5", &mut pkcs5),
+ end_parameter(),
+ ];
+ let mut derived = vec![0; length as usize];
+ openssl::kdf(c"PBKDF2", &params, &mut derived)?;
+ Ok(derived)
+}
+
+pub fn cshake_validate_parameters(output_length: u32) -> Result<(), CryptoError> {
+ if !output_length.is_multiple_of(8) {
+ return Err(CryptoError::Invalid("SHAKE output length must be a multiple of 8 bits"));
+ }
+ Ok(())
}
-pub fn cshake_validate_parameters(output_length: u32) -> Result<(), Utf16String> {
- // SAFETY: The call takes no pointers.
- result_from_error(unsafe { ffi::crypto_cshake_validate_parameters(output_length) })
+// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf
+fn left_encode(output: &mut Vec<u8>, value: u64) {
+ let bytes = value.to_be_bytes();
+ let leading_zeros = bytes.iter().take_while(|&&byte| byte == 0).count().min(bytes.len() - 1);
+ output.push((bytes.len() - leading_zeros) as u8);
+ output.extend_from_slice(&bytes[leading_zeros..]);
+}
+
+// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf
+fn encode_string(output: &mut Vec<u8>, string: &[u8]) {
+ left_encode(output, string.len() as u64 * 8);
+ output.extend_from_slice(string);
}
pub fn cshake_digest(
@@ -173,143 +255,188 @@ pub fn cshake_digest(
output_length: u32,
customization: Option<&[u8]>,
function_name: Option<&[u8]>,
-) -> Result<Vec<u8>, Utf16String> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_cshake_digest(
- kind,
- Span::new(data),
- output_length,
- customization.into(),
- function_name.into(),
- state,
- receive,
- )
- });
- result_from_error(status)?;
- Ok(bytes)
-}
-
-pub fn hmac_sign(kind: ShaHashKind, key: &[u8], message: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (succeeded, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_hmac_sign(kind, Span::new(key), Span::new(message), state, receive)
- });
- if !succeeded {
- return Err(BackendError);
+) -> Result<Vec<u8>, CryptoError> {
+ cshake_validate_parameters(output_length)?;
+ let mut output = vec![0; (output_length / 8) as usize];
+ cshake(
+ kind,
+ data,
+ function_name.unwrap_or_default(),
+ customization.unwrap_or_default(),
+ &mut output,
+ )?;
+ Ok(output)
+}
+
+fn cshake(
+ kind: CShakeKind,
+ data: &[u8],
+ name: &[u8],
+ customization: &[u8],
+ output: &mut [u8],
+) -> Result<(), CryptoError> {
+ // If N = "" and S = "", return SHAKE128(X, L) (or SHAKE256(X, L) for cSHAKE256).
+ if name.is_empty() && customization.is_empty() {
+ let shake = match kind {
+ CShakeKind::CShake128 => c"SHAKE128",
+ CShakeKind::CShake256 => c"SHAKE256",
+ };
+ return openssl::extendable_output(shake, &[data], output);
}
- Ok(bytes)
+
+ // Else return KECCAK[256](bytepad(encode_string(N) || encode_string(S), 168) || X || 00, L) for cSHAKE128, or
+ // KECCAK[512](bytepad(encode_string(N) || encode_string(S), 136) || X || 00, L) for cSHAKE256.
+ // NB: OpenSSL's KECCAK-KMAC digests are KECCAK[c](M || 00, L), the function that KMAC builds on.
+ let (rate, keccak_name) = match kind {
+ CShakeKind::CShake128 => (168, c"KECCAK-KMAC-128"),
+ CShakeKind::CShake256 => (136, c"KECCAK-KMAC-256"),
+ };
+ let mut prefix = Vec::new();
+ left_encode(&mut prefix, rate as u64);
+ encode_string(&mut prefix, name);
+ encode_string(&mut prefix, customization);
+ prefix.resize(prefix.len().div_ceil(rate) * rate, 0);
+ openssl::extendable_output(keccak_name, &[&prefix, data], output)
}
pub fn timing_safe_compare(left: &[u8], right: &[u8]) -> bool {
left.ct_eq(right).into()
}
-pub fn kmac_default_key_length(kind: KmacKind) -> u32 {
- // SAFETY: The input is borrowed for the call.
- unsafe { ffi::crypto_kmac_default_key_length(kind) }
-}
-
pub fn kmac_validate_parameters(output_length: u32, customization: Option<&[u8]>) -> bool {
- // SAFETY: The input is borrowed for the call.
- unsafe { ffi::crypto_kmac_validate_parameters(output_length, customization.into()) }
+ // OpenSSL's KMAC implementation rejects longer outputs and customization strings.
+ const MAXIMUM_OUTPUT_LENGTH: u32 = 0xFF_FFFF / 8;
+ const MAXIMUM_CUSTOMIZATION_LENGTH: usize = 512;
+
+ output_length != 0
+ && output_length.is_multiple_of(8)
+ && output_length / 8 <= MAXIMUM_OUTPUT_LENGTH
+ && customization.is_none_or(|customization| customization.len() <= MAXIMUM_CUSTOMIZATION_LENGTH)
}
+// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-sign
pub fn kmac_sign(
kind: KmacKind,
key: &[u8],
message: &[u8],
output_length: u32,
customization: Option<&[u8]>,
-) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_kmac_sign(
- kind,
- Span::new(key),
- Span::new(message),
- output_length,
- customization.into(),
- state,
- receive,
- )
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
+) -> Result<Vec<u8>, CryptoError> {
+ if !kmac_validate_parameters(output_length, customization) {
+ return Err(CryptoError::Backend);
+ }
+ let name = match kind {
+ KmacKind::Kmac128 => c"KMAC-128",
+ KmacKind::Kmac256 => c"KMAC-256",
+ };
+ let output_size = (output_length / 8) as usize;
+ let mut size = c_uint::try_from(output_size).map_err(|_| CryptoError::Backend)?;
+ let mut params = vec![uint_parameter(c"size", &mut size)];
+ if let Some(customization) = customization {
+ params.push(octet_string_parameter(c"custom", customization));
+ }
+ params.push(end_parameter());
+ openssl::mac(name, key, message, output_size, &params)
}
-pub fn hash_digest_size(kind: ShaHashKind) -> usize {
- // SAFETY: The input is borrowed for the call.
- unsafe { ffi::crypto_hash_digest_size(kind) }
+pub fn argon2_validate_parameters(nonce: &[u8]) -> Result<(), CryptoError> {
+ // OpenSSL's Argon2 implementation rejects shorter salts.
+ const MINIMUM_NONCE_LENGTH: usize = 8;
+
+ if nonce.len() < MINIMUM_NONCE_LENGTH {
+ return Err(CryptoError::Invalid("Argon2 nonce must be at least 8 bytes"));
+ }
+ Ok(())
}
-pub fn hkdf_derive_key(
- kind: ShaHashKind,
- salt: &[u8],
+/// Argon2 with inputs that `argon2_validate_parameters()` accepts.
+pub fn argon2_derive_key(kind: Argon2Type, inputs: &Argon2Inputs<'_>) -> Result<Vec<u8>, CryptoError> {
+ let name = match kind {
+ Argon2Type::Argon2d => c"ARGON2D",
+ Argon2Type::Argon2i => c"ARGON2I",
+ Argon2Type::Argon2id => c"ARGON2ID",
+ };
+ // NB: OpenSSL takes version 0x13, the only version Web Crypto allows, and one thread when none are given.
+ let mut output = vec![0; inputs.tag_length as usize];
+ let (mut passes, mut lanes, mut memory) = (inputs.passes, inputs.parallelism, inputs.memory);
+ let mut size = c_uint::try_from(output.len()).map_err(|_| CryptoError::Backend)?;
+ let mut params = vec![
+ octet_string_parameter(c"pass", inputs.password),
+ octet_string_parameter(c"salt", inputs.nonce),
+ uint_parameter(c"iter", &mut passes),
+ uint_parameter(c"lanes", &mut lanes),
+ uint_parameter(c"memcost", &mut memory),
+ uint_parameter(c"size", &mut size),
+ ];
+ if let Some(secret) = inputs.secret_value {
+ params.push(octet_string_parameter(c"secret", secret));
+ }
+ if let Some(associated_data) = inputs.associated_data {
+ params.push(octet_string_parameter(c"ad", associated_data));
+ }
+ params.push(end_parameter());
+ openssl::kdf(name, &params, &mut output)?;
+ Ok(output)
+}
+
+enum AesMode {
+ Cbc,
+ Ctr,
+ Gcm,
+ Ocb,
+ Kw,
+}
+
+fn aes_cipher(mode: AesMode, key: &[u8]) -> Result<Cipher, CryptoError> {
+ let ciphers = match mode {
+ AesMode::Cbc => [sys::EVP_aes_128_cbc, sys::EVP_aes_192_cbc, sys::EVP_aes_256_cbc],
+ AesMode::Ctr => [sys::EVP_aes_128_ctr, sys::EVP_aes_192_ctr, sys::EVP_aes_256_ctr],
+ AesMode::Gcm => [sys::EVP_aes_128_gcm, sys::EVP_aes_192_gcm, sys::EVP_aes_256_gcm],
+ AesMode::Ocb => [sys::EVP_aes_128_ocb, sys::EVP_aes_192_ocb, sys::EVP_aes_256_ocb],
+ AesMode::Kw => [sys::EVP_aes_128_wrap, sys::EVP_aes_192_wrap, sys::EVP_aes_256_wrap],
+ };
+ let getter = match key.len() {
+ 16 => ciphers[0],
+ 24 => ciphers[1],
+ 32 => ciphers[2],
+ _ => return Err(CryptoError::Backend),
+ };
+ Ok(Cipher::from_static(getter))
+}
+
+/// Encrypts or decrypts `input` whole with a context set up with the cipher, key and IV.
+fn cipher(
+ encrypt: bool,
+ cipher: Cipher,
key: &[u8],
- info: &[u8],
- length: u32,
-) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_hkdf_derive_key(
- kind,
- Span::new(salt),
- Span::new(key),
- Span::new(info),
- length,
- state,
- receive,
- )
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
+ iv: Option<&[u8]>,
+ input: &[u8],
+ allow_key_wrapping: bool,
+) -> Result<Vec<u8>, CryptoError> {
+ let mut context = CipherContext::create()?;
+ if allow_key_wrapping {
+ context.allow_key_wrapping();
+ }
+ context.init(encrypt, Some(cipher), Some(key), iv)?;
+ let mut output = Vec::with_capacity(input.len());
+ // NB: Key wrapping takes its input whole.
+ if allow_key_wrapping {
+ context.update_whole(input, &mut output)?;
+ } else {
+ context.update(input, &mut output)?;
+ }
+ context.finalize(&mut output)?;
+ Ok(output)
}
-pub fn pbkdf2_derive_key(
- kind: ShaHashKind,
- password: &[u8],
- salt: &[u8],
- iterations: u32,
- length: u32,
-) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_pbkdf2_derive_key(
- kind,
- Span::new(password),
- Span::new(salt),
- iterations,
- length,
- state,
- receive,
- )
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn argon2_validate_parameters(nonce: &[u8]) -> Result<(), Utf16String> {
- // SAFETY: The input is borrowed for the call.
- result_from_error(unsafe { ffi::crypto_argon2_validate_parameters(Span::new(nonce)) })
-}
-
-pub fn argon2_derive_key(kind: Argon2Type, inputs: &Argon2Inputs<'_>) -> Result<Vec<u8>, Utf16String> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_argon2_derive_key(kind, &inputs.into(), state, receive)
- });
- result_from_error(status)?;
- Ok(bytes)
-}
-
-pub fn aes_cbc_cipher(encrypt: bool, key: &[u8], input: &[u8], iv: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_aes_cbc_cipher(encrypt, Span::new(key), Span::new(input), Span::new(iv), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
+pub fn aes_cbc_cipher(encrypt: bool, key: &[u8], input: &[u8], iv: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ const IV_LENGTH: usize = 16;
+
+ let aes = aes_cipher(AesMode::Cbc, key)?;
+ if iv.len() != IV_LENGTH {
+ return Err(CryptoError::Backend);
+ }
+ cipher(encrypt, aes, key, Some(iv), input, false)
}
/// Increments only the low `counter_length` bits of the counter block, modulo 2^counter_length, as the standard
@@ -320,10 +447,10 @@ pub fn aes_ctr_cipher(
input: &[u8],
counter: &[u8],
counter_length: u8,
-) -> Result<Vec<u8>, BackendError> {
- let counter_block: [u8; 16] = counter.try_into().map_err(|_| BackendError)?;
+) -> Result<Vec<u8>, CryptoError> {
+ let counter_block: [u8; 16] = counter.try_into().map_err(|_| CryptoError::Backend)?;
if counter_length == 0 || counter_length > 128 {
- return Err(BackendError);
+ return Err(CryptoError::Backend);
}
// The native cipher increments the whole block, so split the input where the low bits wrap around.
@@ -355,78 +482,72 @@ fn aes_ctr_cipher_whole_block_counter(
key: &[u8],
input: &[u8],
counter: &[u8],
-) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_aes_ctr_cipher(
- encrypt,
- Span::new(key),
- Span::new(input),
- Span::new(counter),
- state,
- receive,
- )
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn aes_kw_cipher(wrap: bool, key: &[u8], input: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_aes_kw_cipher(wrap, Span::new(key), Span::new(input), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn aes_gcm_encrypt(
+) -> Result<Vec<u8>, CryptoError> {
+ let aes = aes_cipher(AesMode::Ctr, key)?;
+ cipher(encrypt, aes, key, Some(counter), input, false)
+}
+
+pub fn aes_kw_cipher(wrap: bool, key: &[u8], input: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let aes = aes_cipher(AesMode::Kw, key)?;
+ cipher(wrap, aes, key, None, input, true)
+}
+
+/// Encrypts `input`, giving the ciphertext followed by a tag of `tag_length` bytes, or decrypts such a ciphertext.
+fn aead(
+ cipher: Cipher,
+ encrypt: bool,
key: &[u8],
- plaintext: &[u8],
iv: &[u8],
additional_data: &[u8],
tag_length: usize,
-) -> Result<(Vec<u8>, Vec<u8>), BackendError> {
- let mut first = Vec::new();
- let mut second = Vec::new();
- // SAFETY: Inputs and both output slots are borrowed for the call.
- let status = unsafe {
- ffi::crypto_aes_gcm_encrypt(
- Span::new(key),
- Span::new(plaintext),
- Span::new(iv),
- Span::new(additional_data),
- tag_length,
- core::ptr::from_mut(&mut first).cast(),
- core::ptr::from_mut(&mut second).cast(),
- receive_bytes,
- )
+ input: &[u8],
+) -> Result<Vec<u8>, CryptoError> {
+ let (input, tag) = if encrypt {
+ (input, None)
+ } else {
+ let split_index = input
+ .len()
+ .checked_sub(tag_length)
+ .ok_or(CryptoError::Invalid("Ciphertext too short"))?;
+ let (ciphertext, tag) = input.split_at(split_index);
+ (ciphertext, Some(tag))
};
- status.then_some(()).ok_or(BackendError)?;
- Ok((first, second))
+
+ let mut context = CipherContext::create()?;
+ context.init(encrypt, Some(cipher), None, None)?;
+ context.set_iv_length(iv.len())?;
+ // NB: In OCB mode the tag length can only be set before the IV is; otherwise a default length is used.
+ let ocb_ciphers = [sys::EVP_aes_128_ocb, sys::EVP_aes_192_ocb, sys::EVP_aes_256_ocb].map(Cipher::from_static);
+ if ocb_ciphers.contains(&cipher) {
+ context.set_tag_length(tag_length)?;
+ }
+ context.init(encrypt, None, Some(key), Some(iv))?;
+ if let Some(tag) = tag {
+ context.set_tag(tag)?;
+ }
+ context.add_additional_data(additional_data)?;
+
+ let mut output = Vec::with_capacity(input.len() + tag_length);
+ context.update(input, &mut output)?;
+ context.finalize(&mut output)?;
+ if encrypt {
+ output.extend_from_slice(&context.tag(tag_length)?);
+ }
+ Ok(output)
}
-pub fn aes_gcm_decrypt(
+/// AES-GCM encryption, giving the ciphertext followed by a tag of `tag_length` bytes, or decryption of such a
+/// ciphertext.
+pub fn aes_gcm_cipher(
+ encrypt: bool,
key: &[u8],
- ciphertext: &[u8],
+ input: &[u8],
iv: &[u8],
additional_data: &[u8],
- tag: &[u8],
-) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_aes_gcm_decrypt(
- Span::new(key),
- Span::new(ciphertext),
- Span::new(iv),
- Span::new(additional_data),
- Span::new(tag),
- state,
- receive,
- )
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
+ tag_length: usize,
+) -> Result<Vec<u8>, CryptoError> {
+ let cipher = aes_cipher(AesMode::Gcm, key)?;
+ aead(cipher, encrypt, key, iv, additional_data, tag_length, input)
}
pub fn aes_ocb_cipher(
@@ -436,22 +557,13 @@ pub fn aes_ocb_cipher(
iv: &[u8],
additional_data: &[u8],
tag_length: usize,
-) -> Result<Vec<u8>, Utf16String> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_aes_ocb_cipher(
- encrypt,
- Span::new(key),
- Span::new(input),
- Span::new(iv),
- Span::new(additional_data),
- tag_length,
- state,
- receive,
- )
- });
- result_from_error(status)?;
- Ok(bytes)
+) -> Result<Vec<u8>, CryptoError> {
+ let tag_length_bytes = tag_length / 8;
+ if !(1..=16).contains(&tag_length_bytes) {
+ return Err(CryptoError::Invalid("Invalid AES-OCB tag length"));
+ }
+ let cipher = aes_cipher(AesMode::Ocb, key).map_err(|_| CryptoError::Invalid("Invalid AES-OCB key length"))?;
+ aead(cipher, encrypt, key, iv, additional_data, tag_length_bytes, input)
}
pub fn chacha20_poly1305_cipher(
@@ -460,320 +572,113 @@ pub fn chacha20_poly1305_cipher(
iv: &[u8],
input: &[u8],
additional_data: &[u8],
-) -> Result<Vec<u8>, Utf16String> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_chacha20_poly1305_cipher(
- encrypt,
- Span::new(key),
- Span::new(iv),
- Span::new(input),
- Span::new(additional_data),
- state,
- receive,
- )
- });
- result_from_error(status)?;
- Ok(bytes)
-}
-
-pub fn rsa_key_is_valid(key: &KeyHandle) -> Result<bool, BackendError> {
- let mut value = false;
- // SAFETY: Inputs and output are borrowed for the call.
- let status = unsafe { ffi::crypto_rsa_key_is_valid(key.as_raw(), &mut value) };
- status.then_some(()).ok_or(BackendError)?;
- Ok(value)
-}
-
-/// Whether the big-endian `exponent` is at least 3, is odd, and is less than 2^modulus_length - 1.
-pub fn rsa_validate_public_exponent(exponent: &[u8], modulus_length: u32) -> bool {
- let exponent = strip_leading_zeros(exponent);
- let (Some(&first), Some(&last)) = (exponent.first(), exponent.last()) else {
- return false;
- };
- if (exponent.len() == 1 && first < 3) || last & 1 == 0 {
- return false;
- }
-
- // NB: exponent + 1 has one bit more than exponent exactly when every bit of exponent is set.
- let bit_length = (exponent.len() as u64 - 1) * 8 + u64::from(8 - first.leading_zeros());
- let all_bits_set = (first & first.wrapping_add(1)) == 0 && exponent[1..].iter().all(|&byte| byte == 0xff);
- let incremented_bit_length = bit_length + u64::from(all_bits_set);
- incremented_bit_length <= u64::from(modulus_length)
-}
-
-fn strip_leading_zeros(bytes: &[u8]) -> &[u8] {
- let leading_zeros = bytes.iter().take_while(|&&byte| byte == 0).count();
- &bytes[leading_zeros..]
-}
-
-pub fn rsa_validate_modulus_length(modulus_length: u32) -> bool {
- // SAFETY: The input is borrowed for the call.
- unsafe { ffi::crypto_rsa_validate_modulus_length(modulus_length) }
-}
+) -> Result<Vec<u8>, CryptoError> {
+ const KEY_SIZE: usize = 32;
+ const NONCE_SIZE: usize = 12;
+ const TAG_SIZE: usize = 16;
-pub fn rsa_generate_key_pair(modulus_length: u32, exponent: &[u8]) -> Result<KeyPair, BackendError> {
- let mut public_key = core::ptr::null_mut();
- let mut private_key = core::ptr::null_mut();
- // SAFETY: Inputs and output slots are borrowed for the call.
- let status = unsafe {
- ffi::crypto_rsa_generate_key_pair(modulus_length, Span::new(exponent), &mut public_key, &mut private_key)
- };
- status.then_some(()).ok_or(BackendError)?;
- // SAFETY: Success transfers ownership of both keys.
- Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
-}
-
-/// The big-endian `exponent` with no leading zero bytes.
-pub fn rsa_export_public_exponent(exponent: &[u8]) -> Vec<u8> {
- strip_leading_zeros(exponent).to_vec()
+ if key.len() != KEY_SIZE {
+ return Err(CryptoError::Invalid("ChaCha20-Poly1305 key must be 32 bytes"));
+ }
+ if iv.len() != NONCE_SIZE {
+ return Err(CryptoError::Invalid("ChaCha20-Poly1305 nonce must be 12 bytes"));
+ }
+ aead(
+ Cipher::from_static(sys::EVP_chacha20_poly1305),
+ encrypt,
+ key,
+ iv,
+ additional_data,
+ TAG_SIZE,
+ input,
+ )
+}
+
+impl OkpCurve {
+ /// The name of the curve's key type, as OpenSSL takes it.
+ fn name(self) -> &'static CStr {
+ match self {
+ Self::Ed25519 => c"ED25519",
+ Self::Ed448 => c"ED448",
+ Self::X25519 => c"X25519",
+ Self::X448 => c"X448",
+ }
+ }
}
-pub fn rsa_export_der(key: &KeyHandle, is_public: bool) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_rsa_export_der(key.as_raw(), is_public, state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
+pub fn okp_generate_private_key(curve: OkpCurve) -> Result<Vec<u8>, CryptoError> {
+ Ok(Pkey::generate(curve.name(), None)?.raw_private_key()?.into_vec())
}
-pub fn rsa_export_jwk_integer(key: &KeyHandle, component: RsaJwkInteger) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_rsa_export_jwk_integer(key.as_raw(), component, state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
+pub fn okp_generate_public_key(curve: OkpCurve, private_key: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ Pkey::from_raw_private_key(curve.name(), private_key)?.raw_public_key()
}
-pub fn rsa_oaep_cipher(
- encrypt: bool,
- hash_kind: ShaHashKind,
- key: &KeyHandle,
- label: &[u8],
- input: &[u8],
-) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_rsa_oaep_cipher(
- encrypt,
- hash_kind,
- key.as_raw(),
- Span::new(label),
- Span::new(input),
- state,
- receive,
- )
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn rsa_pss_sign(
- hash_kind: ShaHashKind,
- key: &KeyHandle,
- salt_length: u32,
- message: &[u8],
-) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_rsa_pss_sign(hash_kind, key.as_raw(), salt_length, Span::new(message), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn rsa_pss_verify(
- hash_kind: ShaHashKind,
- key: &KeyHandle,
- salt_length: u32,
- message: &[u8],
- signature: &[u8],
-) -> Result<bool, BackendError> {
- let mut value = false;
- // SAFETY: Inputs and output are borrowed for the call.
- let status = unsafe {
- ffi::crypto_rsa_pss_verify(
- hash_kind,
- key.as_raw(),
- salt_length,
- Span::new(message),
- Span::new(signature),
- &mut value,
- )
- };
- status.then_some(()).ok_or(BackendError)?;
- Ok(value)
+pub fn okp_compute_coordinate(curve: OkpCurve, private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ if !matches!(curve, OkpCurve::X25519 | OkpCurve::X448) {
+ return Err(CryptoError::Backend);
+ }
+ let key = Pkey::from_raw_private_key(curve.name(), private_key)?;
+ let peer = Pkey::from_raw_public_key(curve.name(), public_key)?;
+ openssl::derive(&key, &peer, false)
}
-pub fn rsa_pkcs1_sign(hash_kind: ShaHashKind, key: &KeyHandle, message: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_rsa_pkcs1_sign(hash_kind, key.as_raw(), Span::new(message), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
+pub fn okp_sign(curve: OkpCurve, private_key: &[u8], message: &[u8], context: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let key = Pkey::from_raw_private_key(curve.name(), private_key)?;
+ match curve {
+ OkpCurve::Ed25519 => openssl::digest_sign(&key, None, &[end_parameter()], message),
+ OkpCurve::Ed448 => openssl::digest_sign(&key, None, &openssl::context_string_parameters(context), message),
+ OkpCurve::X25519 | OkpCurve::X448 => Err(CryptoError::Backend),
+ }
}
-pub fn rsa_pkcs1_verify(
- hash_kind: ShaHashKind,
- key: &KeyHandle,
- message: &[u8],
- signature: &[u8],
-) -> Result<bool, BackendError> {
- let mut value = false;
- // SAFETY: Inputs and output are borrowed for the call.
- let status = unsafe {
- ffi::crypto_rsa_pkcs1_verify(
- hash_kind,
- key.as_raw(),
- Span::new(message),
- Span::new(signature),
- &mut value,
- )
- };
- status.then_some(()).ok_or(BackendError)?;
- Ok(value)
-}
-
-pub fn ec_generate_key_pair(curve: EcCurve) -> Result<KeyPair, BackendError> {
- let mut public_key = core::ptr::null_mut();
- let mut private_key = core::ptr::null_mut();
- // SAFETY: Inputs and output slots are borrowed for the call.
- let status = unsafe { ffi::crypto_ec_generate_key_pair(curve, &mut public_key, &mut private_key) };
- status.then_some(()).ok_or(BackendError)?;
- // SAFETY: Success transfers ownership of both keys.
- Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
-}
-
-pub fn ec_verify(curve: EcCurve, key: &KeyHandle, digest: &[u8], r: &[u8], s: &[u8]) -> Result<bool, Utf16String> {
- let mut value = false;
- // SAFETY: Inputs and output are borrowed for the call.
- let status = unsafe {
- ffi::crypto_ec_verify(
- curve,
- key.as_raw(),
- Span::new(digest),
- Span::new(r),
- Span::new(s),
- &mut value,
- )
- };
- result_from_error(status)?;
- Ok(value)
-}
-
-pub fn ec_public_key_scalar_size(key: &KeyHandle) -> usize {
- // SAFETY: The input is borrowed for the call.
- unsafe { ffi::crypto_ec_public_key_scalar_size(key.as_raw()) }
-}
-
-pub fn ec_key_from_coordinates(x: &[u8], y: &[u8], d: Option<&[u8]>) -> Option<KeyHandle> {
- // SAFETY: The input is borrowed for the call.
- let raw = unsafe { ffi::crypto_ec_key_from_coordinates(Span::new(x), Span::new(y), d.into()) };
- // SAFETY: The native operation transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }
-}
-
-pub fn ec_parse_raw_public_key(bytes: &[u8]) -> Option<KeyHandle> {
- // SAFETY: The input is borrowed for the call.
- let raw = unsafe { ffi::crypto_ec_parse_raw_public_key(Span::new(bytes)) };
- // SAFETY: The native operation transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }
-}
-
-pub fn ec_key_is_valid(curve: EcCurve, key: &KeyHandle) -> Result<bool, BackendError> {
- let mut value = false;
- // SAFETY: Inputs and output are borrowed for the call.
- let status = unsafe { ffi::crypto_ec_key_is_valid(curve, key.as_raw(), &mut value) };
- status.then_some(()).ok_or(BackendError)?;
- Ok(value)
-}
-
-pub fn ec_export_der(curve: EcCurve, key: &KeyHandle, is_public: bool) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_ec_export_der(curve, key.as_raw(), is_public, state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn ec_export_uncompressed(key: &KeyHandle) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_ec_export_uncompressed(key.as_raw(), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn ec_export_public_coordinates(key: &KeyHandle) -> Result<(Vec<u8>, Vec<u8>), BackendError> {
- let mut first = Vec::new();
- let mut second = Vec::new();
- // SAFETY: Inputs and both output slots are borrowed for the call.
- let status = unsafe {
- ffi::crypto_ec_export_public_coordinates(
- key.as_raw(),
- core::ptr::from_mut(&mut first).cast(),
- core::ptr::from_mut(&mut second).cast(),
- receive_bytes,
- )
+// NB: The y-coordinates of the points of order 1, 2, 4 and 8, which Web Crypto's verify operation returns false for
+// when the public key or the signature's R is one. The sign bit of x is ignored.
+const SMALL_ORDER_ED25519_Y_COORDINATES: [[u8; 32]; 7] = [
+ // y = 0, order 4
+ [
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ],
+ // y = 1, the identity
+ [
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ],
+ // Order 8
+ [
+ 0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0, 0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0, 0xd5, 0xdf,
+ 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39, 0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05,
+ ],
+ // Order 8
+ [
+ 0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f, 0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f, 0x2a, 0x20,
+ 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6, 0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a,
+ ],
+ // y = p - 1, order 2
+ [
+ 0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
+ ],
+ // y = p, a non-canonical 0
+ [
+ 0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
+ ],
+ // y = p + 1, a non-canonical 1
+ [
+ 0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
+ ],
+];
+
+fn is_small_order_ed25519_point(point: &[u8]) -> bool {
+ let Some((&last, rest)) = point.split_last() else {
+ return false;
};
- status.then_some(()).ok_or(BackendError)?;
- Ok((first, second))
-}
-
-pub fn ec_export_private_scalar(key: &KeyHandle) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_ec_export_private_scalar(key.as_raw(), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn okp_generate_private_key(curve: OkpCurve) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) =
- receive_native_bytes(|state, receive| unsafe { ffi::crypto_okp_generate_private_key(curve, state, receive) });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn okp_generate_public_key(curve: OkpCurve, private_key: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_okp_generate_public_key(curve, Span::new(private_key), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn okp_compute_coordinate(curve: OkpCurve, private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_okp_compute_coordinate(curve, Span::new(private_key), Span::new(public_key), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn okp_sign(curve: OkpCurve, private_key: &[u8], message: &[u8], context: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_okp_sign(
- curve,
- Span::new(private_key),
- Span::new(message),
- Span::new(context),
- state,
- receive,
- )
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
+ SMALL_ORDER_ED25519_Y_COORDINATES
+ .iter()
+ .any(|y| rest == &y[..31] && last & 0x7f == y[31])
}
pub fn okp_verify(
@@ -782,240 +687,55 @@ pub fn okp_verify(
signature: &[u8],
message: &[u8],
context: &[u8],
-) -> Result<bool, Utf16String> {
- let mut value = false;
- // SAFETY: Inputs and output are borrowed for the call.
- let status = unsafe {
- ffi::crypto_okp_verify(
- curve,
- Span::new(public_key),
- Span::new(signature),
- Span::new(message),
- Span::new(context),
- &mut value,
- )
- };
- result_from_error(status)?;
- Ok(value)
-}
-
-pub fn okp_export_der(curve: OkpCurve, is_public: bool, key: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_okp_export_der(curve, is_public, Span::new(key), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn mldsa_sign(size: MlDsaSize, key: &KeyHandle, message: &[u8], context: &[u8]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_mldsa_sign(
- size,
- key.as_raw(),
- Span::new(message),
- Span::new(context),
- state,
- receive,
- )
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn mldsa_verify(
- size: MlDsaSize,
- key: &KeyHandle,
- message: &[u8],
- signature: &[u8],
- context: &[u8],
-) -> Result<bool, BackendError> {
- let mut value = false;
- // SAFETY: Inputs and output are borrowed for the call.
- let status = unsafe {
- ffi::crypto_mldsa_verify(
- size,
- key.as_raw(),
- Span::new(message),
- Span::new(signature),
- Span::new(context),
- &mut value,
- )
- };
- status.then_some(()).ok_or(BackendError)?;
- Ok(value)
-}
-
-pub fn mldsa_generate_key_pair(size: MlDsaSize, seed: &[u8]) -> Result<KeyPair, Utf16String> {
- let mut public_key = core::ptr::null_mut();
- let mut private_key = core::ptr::null_mut();
- // SAFETY: Inputs and output slots are borrowed for the call.
- let status =
- unsafe { ffi::crypto_mldsa_generate_key_pair(size, Span::new(seed), &mut public_key, &mut private_key) };
- result_from_error(status)?;
- // SAFETY: Success transfers ownership of both keys.
- Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
-}
-
-pub fn mldsa_read_public_key(size: MlDsaSize, bytes: &[u8]) -> Option<KeyHandle> {
- // SAFETY: The input is borrowed for the call.
- let raw = unsafe { ffi::crypto_mldsa_read_public_key(size, Span::new(bytes)) };
- // SAFETY: A non-null result transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }
-}
-
-pub fn mldsa_public_bytes(key: &KeyHandle) -> &[u8] {
- let mut bytes = Span::default();
- // SAFETY: The key owns the bytes returned by the native call.
- unsafe { ffi::crypto_mldsa_public_bytes(key.as_raw(), &mut bytes) };
- bytes.as_slice()
-}
-
-pub fn mldsa_seed_bytes(key: &KeyHandle) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) =
- receive_native_bytes(|state, receive| unsafe { ffi::crypto_mldsa_seed_bytes(key.as_raw(), state, receive) });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn mldsa_export_der(key: &KeyHandle, is_public: bool, oid: &[u32]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_mldsa_export_der(key.as_raw(), is_public, Span::new(oid), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn mlkem_generate_key_pair(size: MlKemSize, seed: &[u8]) -> Result<KeyPair, Utf16String> {
- let mut public_key = core::ptr::null_mut();
- let mut private_key = core::ptr::null_mut();
- // SAFETY: Inputs and output slots are borrowed for the call.
- let status =
- unsafe { ffi::crypto_mlkem_generate_key_pair(size, Span::new(seed), &mut public_key, &mut private_key) };
- result_from_error(status)?;
- // SAFETY: Success transfers ownership of both keys.
- Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
-}
-
-pub fn mlkem_read_public_key(bytes: &[u8]) -> Option<KeyHandle> {
- // SAFETY: The input is borrowed for the call.
- let raw = unsafe { ffi::crypto_mlkem_read_public_key(Span::new(bytes)) };
- // SAFETY: A non-null result transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }
-}
-
-pub fn mlkem_public_bytes(key: &KeyHandle) -> Vec<u8> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let ((), bytes) =
- receive_native_bytes(|state, receive| unsafe { ffi::crypto_mlkem_public_bytes(key.as_raw(), state, receive) });
- bytes
-}
-
-pub fn mlkem_seed_bytes(key: &KeyHandle) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) =
- receive_native_bytes(|state, receive| unsafe { ffi::crypto_mlkem_seed_bytes(key.as_raw(), state, receive) });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-/// Whether an ML-DSA or ML-KEM private key has its seed, which a key given in the expandedKey form does not.
-pub fn ml_private_key_has_seed(key: &KeyHandle) -> bool {
- // SAFETY: The key is borrowed for the call.
- unsafe { ffi::crypto_ml_private_key_has_seed(key.as_raw()) }
-}
-
-pub fn mlkem_export_der(key: &KeyHandle, is_public: bool, oid: &[u32]) -> Result<Vec<u8>, BackendError> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_mlkem_export_der(key.as_raw(), is_public, Span::new(oid), state, receive)
- });
- status.then_some(()).ok_or(BackendError)?;
- Ok(bytes)
-}
-
-pub fn mlkem_encapsulate(size: MlKemSize, key: &KeyHandle) -> Result<(Vec<u8>, Vec<u8>), Utf16String> {
- let mut first = Vec::new();
- let mut second = Vec::new();
- // SAFETY: Inputs and both output slots are borrowed for the call.
- let status = unsafe {
- ffi::crypto_mlkem_encapsulate(
- size,
- key.as_raw(),
- core::ptr::from_mut(&mut first).cast(),
- core::ptr::from_mut(&mut second).cast(),
- receive_bytes,
- )
- };
- result_from_error(status)?;
- Ok((first, second))
+) -> Result<bool, CryptoError> {
+ if matches!(curve, OkpCurve::Ed25519)
+ && (is_small_order_ed25519_point(public_key) || signature.get(..32).is_some_and(is_small_order_ed25519_point))
+ {
+ return Ok(false);
+ }
+ let key = Pkey::from_raw_public_key(curve.name(), public_key)?;
+ match curve {
+ OkpCurve::Ed25519 => openssl::digest_verify(&key, None, &[end_parameter()], message, signature),
+ OkpCurve::Ed448 => openssl::digest_verify(
+ &key,
+ None,
+ &openssl::context_string_parameters(context),
+ message,
+ signature,
+ ),
+ OkpCurve::X25519 | OkpCurve::X448 => Err(CryptoError::Invalid("The algorithm does not sign")),
+ }
}
-pub fn mlkem_decapsulate(size: MlKemSize, key: &KeyHandle, ciphertext: &[u8]) -> Result<Vec<u8>, Utf16String> {
- // SAFETY: Inputs and output are borrowed for the synchronous native call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_mlkem_decapsulate(size, key.as_raw(), Span::new(ciphertext), state, receive)
- });
- result_from_error(status)?;
- Ok(bytes)
+pub fn okp_export_der(curve: OkpCurve, is_public: bool, key: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ if is_public {
+ Pkey::from_raw_public_key(curve.name(), key)?.public_key_info()
+ } else {
+ // https://www.rfc-editor.org/rfc/rfc8410#section-7
+ // CurvePrivateKey ::= OCTET STRING
+ let private_key = SecretBytes::new(der::element(der::OCTET_STRING, &[key]));
+ Ok(der::private_key_info(
+ KeyAlgorithm::Okp(curve).oid(),
+ None,
+ &private_key,
+ ))
+ }
}
pub fn public_key_for_private_key(key: &KeyHandle, name: &Utf16String) -> Option<KeyHandle> {
- // SAFETY: The inputs are borrowed for the call.
- let raw = unsafe { ffi::crypto_public_key_for_private_key(key.as_raw(), name.raw_identity()) };
- // SAFETY: A non-null result transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }
-}
-
-pub fn rsa_read_key_metadata(key: &KeyHandle) -> Result<(u32, Vec<u8>), BackendError> {
- let mut modulus_length = 0;
- // SAFETY: The key and output slots live until the native call returns.
- let (success, exponent) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_rsa_read_key_metadata(key.as_raw(), &mut modulus_length, state, receive)
- });
- success.then_some((modulus_length, exponent)).ok_or(BackendError)
-}
-
-pub fn rsa_key_from_components(is_private: bool, components: &[&[u8]]) -> Option<KeyHandle> {
- if (is_private && !matches!(components.len(), 3 | 8)) || (!is_private && components.len() != 2) {
- return None;
+ if key.is_okp_private() {
+ let curve = [
+ ("Ed25519", OkpCurve::Ed25519),
+ ("Ed448", OkpCurve::Ed448),
+ ("X25519", OkpCurve::X25519),
+ ("X448", OkpCurve::X448),
+ ]
+ .into_iter()
+ .find_map(|(curve_name, curve)| (*name == curve_name).then_some(curve))?;
+ let public_key = okp_generate_public_key(curve, key.okp_bytes()).ok()?;
+ return Some(KeyHandle::from_okp_bytes(false, &public_key));
}
- let mut spans = [Span::default(); 8];
- for (span, component) in spans.iter_mut().zip(components) {
- *span = Span::new(component);
- }
- // SAFETY: The spans are live for the call and contain the required components.
- let raw = unsafe { ffi::crypto_rsa_key_from_jwk_components(is_private, Span::new(&spans[..components.len()])) };
- // SAFETY: A non-null result transfers ownership of the key.
- unsafe { KeyHandle::from_raw(raw) }
-}
-
-pub fn ec_sign(curve: EcCurve, key: &KeyHandle, digest: &[u8]) -> Result<(Vec<u8>, Vec<u8>), Utf16String> {
- let mut r = Vec::new();
- let mut s = Vec::new();
- // SAFETY: Inputs and both output slots are live for the synchronous call.
- let status = unsafe {
- ffi::crypto_ec_sign(
- curve,
- key.as_raw(),
- Span::new(digest),
- core::ptr::from_mut(&mut r).cast(),
- core::ptr::from_mut(&mut s).cast(),
- receive_bytes,
- )
- };
- result_from_error(status)?;
- Ok((r, s))
-}
-
-pub fn ec_compute_coordinate(curve: EcCurve, key: &KeyHandle, public_key: &KeyHandle) -> Result<Vec<u8>, Utf16String> {
- // SAFETY: The key handles and output slot are live for the synchronous call.
- let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
- ffi::crypto_ec_compute_coordinate(curve, key.as_raw(), public_key.as_raw(), state, receive)
- });
- result_from_error(status)?;
- Ok(bytes)
+ ml::public_key_for_private_key(key)
+ .or_else(|| ec::public_key_for_private_key(key))
+ .or_else(|| rsa::public_key_for_private_key(key))
}
diff --git a/Libraries/LibCrypto/Rust/src/ml.rs b/Libraries/LibCrypto/Rust/src/ml.rs
new file mode 100644
index 00000000000..b70b636d7ce
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/ml.rs
@@ -0,0 +1,452 @@
+/*
+ * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! ML-DSA and ML-KEM keys.
+
+use core::ffi::CStr;
+
+use crate::der;
+use crate::key::{HandleTag, Key, KeyDecodeError, KeyHandle, KeyPair, SecretBytes, StoredKey};
+use crate::openssl::{self, Pkey};
+use crate::{CryptoError, KeyAlgorithm, MlDsaSize, MlKemSize, sys};
+
+pub(crate) struct MlDsaPublicKey {
+ key: Pkey,
+ bytes: Vec<u8>,
+ size: MlDsaSize,
+}
+
+/// Any bytes make an ML-KEM public key. Web Crypto only runs the encapsulation key check of FIPS 203, section 7.2, when
+/// the key is used, so a key that fails it has no OpenSSL key or parameter set.
+pub(crate) struct MlKemPublicKey {
+ key: Option<Pkey>,
+ bytes: Vec<u8>,
+ size: Option<MlKemSize>,
+}
+
+/// An ML-DSA or ML-KEM private key, which is made from its seed.
+pub(crate) struct MlPrivateKey {
+ key: Pkey,
+ public_key: Vec<u8>,
+ parameter_set: ParameterSet,
+}
+
+/// An ML-DSA or ML-KEM parameter set.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum ParameterSet {
+ MlDsa(MlDsaSize),
+ MlKem(MlKemSize),
+}
+
+const SEED: &CStr = c"seed";
+
+impl MlDsaSize {
+ const ALL: [Self; 3] = [Self::MlDsa44, Self::MlDsa65, Self::MlDsa87];
+
+ fn public_key_size(self) -> usize {
+ match self {
+ Self::MlDsa44 => 1312,
+ Self::MlDsa65 => 1952,
+ Self::MlDsa87 => 2592,
+ }
+ }
+}
+
+impl MlKemSize {
+ const ALL: [Self; 3] = [Self::MlKem512, Self::MlKem768, Self::MlKem1024];
+
+ fn public_key_size(self) -> usize {
+ match self {
+ Self::MlKem512 => 800,
+ Self::MlKem768 => 1184,
+ Self::MlKem1024 => 1568,
+ }
+ }
+}
+
+impl ParameterSet {
+ fn name(self) -> &'static CStr {
+ match self {
+ Self::MlDsa(MlDsaSize::MlDsa44) => c"ML-DSA-44",
+ Self::MlDsa(MlDsaSize::MlDsa65) => c"ML-DSA-65",
+ Self::MlDsa(MlDsaSize::MlDsa87) => c"ML-DSA-87",
+ Self::MlKem(MlKemSize::MlKem512) => c"ML-KEM-512",
+ Self::MlKem(MlKemSize::MlKem768) => c"ML-KEM-768",
+ Self::MlKem(MlKemSize::MlKem1024) => c"ML-KEM-1024",
+ }
+ }
+
+ fn seed_size(self) -> usize {
+ match self {
+ Self::MlDsa(_) => 32,
+ Self::MlKem(_) => 64,
+ }
+ }
+
+ fn expanded_key_size(self) -> usize {
+ match self {
+ Self::MlDsa(MlDsaSize::MlDsa44) => 2560,
+ Self::MlDsa(MlDsaSize::MlDsa65) => 4032,
+ Self::MlDsa(MlDsaSize::MlDsa87) => 4896,
+ Self::MlKem(MlKemSize::MlKem512) => 1632,
+ Self::MlKem(MlKemSize::MlKem768) => 2400,
+ Self::MlKem(MlKemSize::MlKem1024) => 3168,
+ }
+ }
+}
+
+fn mldsa_public_key_from_bytes(bytes: &[u8]) -> Option<MlDsaPublicKey> {
+ let size = MlDsaSize::ALL
+ .into_iter()
+ .find(|size| size.public_key_size() == bytes.len())?;
+ let key = Pkey::from_raw_public_key(ParameterSet::MlDsa(size).name(), bytes).ok()?;
+ Some(MlDsaPublicKey {
+ key,
+ bytes: bytes.to_vec(),
+ size,
+ })
+}
+
+fn mlkem_public_key_from_bytes(bytes: &[u8]) -> MlKemPublicKey {
+ // NB: OpenSSL builds a key only from bytes of a parameter set's length whose coefficients are all below q, which
+ // are the two parts of the encapsulation key check.
+ let checked = MlKemSize::ALL
+ .into_iter()
+ .find(|size| size.public_key_size() == bytes.len())
+ .and_then(|size| {
+ Pkey::from_raw_public_key(ParameterSet::MlKem(size).name(), bytes)
+ .ok()
+ .map(|key| (key, size))
+ });
+ let (key, size) = checked.map_or((None, None), |(key, size)| (Some(key), Some(size)));
+ MlKemPublicKey {
+ key,
+ bytes: bytes.to_vec(),
+ size,
+ }
+}
+
+impl MlPrivateKey {
+ /// The key of `parameter_set` that `seed` makes, or a new key for an empty seed.
+ fn from_seed(parameter_set: ParameterSet, seed: &[u8]) -> Result<Self, CryptoError> {
+ let key = if seed.is_empty() {
+ let mut seed = SecretBytes::new(vec![0; parameter_set.seed_size()]);
+ openssl::fill_with_random(&mut seed)?;
+ private_key_from_seed(parameter_set, &seed)?
+ } else {
+ private_key_from_seed(parameter_set, seed)?
+ };
+ let public_key = key.raw_public_key()?;
+ Ok(Self {
+ key,
+ public_key,
+ parameter_set,
+ })
+ }
+
+ fn seed(&self) -> Result<SecretBytes, CryptoError> {
+ self.key.octet_string(SEED)
+ }
+
+ fn expanded_key(&self) -> Result<SecretBytes, CryptoError> {
+ self.key.raw_private_key()
+ }
+
+ fn public(&self) -> Option<Key> {
+ match self.parameter_set {
+ ParameterSet::MlDsa(_) => mldsa_public_key_from_bytes(&self.public_key).map(Key::MlDsaPublic),
+ ParameterSet::MlKem(_) => Some(Key::MlKemPublic(mlkem_public_key_from_bytes(&self.public_key))),
+ }
+ }
+}
+
+/// The private key of `parameter_set` that `seed` makes.
+// NB: The seed parameter points at the caller's buffer, and the key clears its own copy.
+fn private_key_from_seed(parameter_set: ParameterSet, seed: &[u8]) -> Result<Pkey, CryptoError> {
+ let mut params = [openssl::octet_string_parameter(c"seed", seed), openssl::end_parameter()];
+ Pkey::from_data(parameter_set.name(), sys::EVP_PKEY_KEYPAIR, params.as_mut_ptr())
+}
+
+fn private_key(key: &KeyHandle) -> &MlPrivateKey {
+ match &key.0 {
+ Key::MlPrivate(private_key) => private_key,
+ _ => panic!("The key is not an ML-DSA or ML-KEM private key"),
+ }
+}
+
+fn generate_key_pair(parameter_set: ParameterSet, seed: &[u8]) -> Result<KeyPair, CryptoError> {
+ let private_key = MlPrivateKey::from_seed(parameter_set, seed)?;
+ let public_key = private_key
+ .public()
+ .ok_or(CryptoError::Invalid("Invalid ML-DSA key length"))?;
+ Ok(KeyPair {
+ public_key: KeyHandle(public_key),
+ private_key: KeyHandle(Key::MlPrivate(private_key)),
+ })
+}
+
+pub fn mldsa_generate_key_pair(size: MlDsaSize, seed: &[u8]) -> Result<KeyPair, CryptoError> {
+ generate_key_pair(ParameterSet::MlDsa(size), seed)
+}
+
+pub fn mlkem_generate_key_pair(size: MlKemSize, seed: &[u8]) -> Result<KeyPair, CryptoError> {
+ generate_key_pair(ParameterSet::MlKem(size), seed)
+}
+
+pub fn mldsa_read_public_key(size: MlDsaSize, bytes: &[u8]) -> Option<KeyHandle> {
+ let public_key = mldsa_public_key_from_bytes(bytes)?;
+ (public_key.size == size).then(|| KeyHandle(Key::MlDsaPublic(public_key)))
+}
+
+pub fn mlkem_read_public_key(bytes: &[u8]) -> Option<KeyHandle> {
+ Some(KeyHandle(Key::MlKemPublic(mlkem_public_key_from_bytes(bytes))))
+}
+
+pub fn mldsa_public_bytes(key: &KeyHandle) -> &[u8] {
+ match &key.0 {
+ Key::MlDsaPublic(public_key) => &public_key.bytes,
+ Key::MlPrivate(private_key) => &private_key.public_key,
+ _ => panic!("The key is not an ML-DSA key"),
+ }
+}
+
+pub fn mlkem_public_bytes(key: &KeyHandle) -> Vec<u8> {
+ match &key.0 {
+ Key::MlKemPublic(public_key) => public_key.bytes.clone(),
+ _ => panic!("The key is not an ML-KEM public key"),
+ }
+}
+
+pub fn ml_seed_bytes(key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
+ Ok(private_key(key).seed()?.into_vec())
+}
+
+/// The SubjectPublicKeyInfo or PrivateKeyInfo of an ML-DSA or ML-KEM key of `algorithm`. A private key's privateKey is
+/// in the seed-only form.
+pub fn ml_export_der(key: &KeyHandle, is_public: bool, algorithm: KeyAlgorithm) -> Result<Vec<u8>, CryptoError> {
+ let oid = algorithm.oid();
+ match &key.0 {
+ Key::MlDsaPublic(public_key) if is_public => Ok(der::subject_public_key_info(oid, None, &public_key.bytes)),
+ Key::MlKemPublic(public_key) if is_public => Ok(der::subject_public_key_info(oid, None, &public_key.bytes)),
+ Key::MlPrivate(private_key) if !is_public => {
+ let seed = private_key.seed()?;
+ let seed_header = der::header(0x80, seed.len());
+ let mut encoded = SecretBytes::new(Vec::with_capacity(seed_header.len() + seed.len()));
+ encoded.extend_from_slice(&seed_header);
+ encoded.extend_from_slice(&seed);
+ Ok(der::private_key_info(oid, None, &encoded))
+ }
+ _ => Err(CryptoError::Backend),
+ }
+}
+
+pub fn mldsa_sign(size: MlDsaSize, key: &KeyHandle, message: &[u8], context: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let Key::MlPrivate(private_key) = &key.0 else {
+ return Err(CryptoError::Backend);
+ };
+ let parameter_set = ParameterSet::MlDsa(size);
+ if private_key.parameter_set != parameter_set {
+ return Err(CryptoError::Backend);
+ }
+ openssl::sign_message(&private_key.key, parameter_set.name(), message, context)
+}
+
+pub fn mldsa_verify(
+ size: MlDsaSize,
+ key: &KeyHandle,
+ message: &[u8],
+ signature: &[u8],
+ context: &[u8],
+) -> Result<bool, CryptoError> {
+ let Key::MlDsaPublic(public_key) = &key.0 else {
+ return Err(CryptoError::Backend);
+ };
+ if public_key.size != size {
+ return Err(CryptoError::Backend);
+ }
+ openssl::verify_message(
+ &public_key.key,
+ ParameterSet::MlDsa(size).name(),
+ message,
+ signature,
+ context,
+ )
+}
+
+pub fn mlkem_encapsulate(size: MlKemSize, key: &KeyHandle) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
+ let Key::MlKemPublic(public_key) = &key.0 else {
+ return Err(CryptoError::Invalid("The key is not an ML-KEM public key"));
+ };
+ let (Some(openssl_key), Some(key_size)) = (&public_key.key, public_key.size) else {
+ return Err(CryptoError::Invalid("The key fails the encapsulation key check"));
+ };
+ if key_size != size {
+ return Err(CryptoError::Invalid("The key fails the encapsulation key check"));
+ }
+ let (shared_key, ciphertext) = openssl::encapsulate(openssl_key)?;
+ Ok((shared_key.into_vec(), ciphertext))
+}
+
+pub fn mlkem_decapsulate(size: MlKemSize, key: &KeyHandle, ciphertext: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let Key::MlPrivate(private_key) = &key.0 else {
+ return Err(CryptoError::Invalid("The key is not an ML-KEM private key"));
+ };
+ if private_key.parameter_set != ParameterSet::MlKem(size) {
+ return Err(CryptoError::Invalid("The key is for a different ML-KEM parameter set"));
+ }
+ Ok(openssl::decapsulate(&private_key.key, ciphertext)?.into_vec())
+}
+
+pub(crate) fn public_key_for_private_key(key: &KeyHandle) -> Option<KeyHandle> {
+ let Key::MlPrivate(private_key) = &key.0 else {
+ return None;
+ };
+ private_key.public().map(KeyHandle)
+}
+
+struct ModuleLatticePrivateKey<'a> {
+ seed: Option<&'a [u8]>,
+ expanded_key: Option<&'a [u8]>,
+}
+
+// https://datatracker.ietf.org/doc/html/draft-ietf-lamps-kyber-certificates-11#autoid-7
+// https://www.rfc-editor.org/rfc/rfc9881.html#section-6
+fn parse_module_lattice_private_key(
+ der: &[u8],
+ seed_size: usize,
+ expanded_key_size: usize,
+) -> Result<ModuleLatticePrivateKey<'_>, CryptoError> {
+ // PrivateKey ::= CHOICE {
+ // seed [0] IMPLICIT OCTET STRING (SIZE (seed_size)),
+ // expandedKey OCTET STRING (SIZE (expanded_key_size)),
+ // both SEQUENCE {
+ // seed OCTET STRING (SIZE (seed_size)),
+ // expandedKey OCTET STRING (SIZE (expanded_key_size))
+ // }
+ // }
+ // NB: The sizes are fixed, so each choice has a single DER layout, and the input is a choice when its headers are
+ // those of that layout.
+ let seed_header = der::header(0x80, seed_size);
+ if der.len() == seed_header.len() + seed_size
+ && let Some(seed) = der.strip_prefix(seed_header.as_slice())
+ {
+ return Ok(ModuleLatticePrivateKey {
+ seed: Some(seed),
+ expanded_key: None,
+ });
+ }
+
+ let expanded_key_header = der::header(der::OCTET_STRING, expanded_key_size);
+ if der.len() == expanded_key_header.len() + expanded_key_size
+ && let Some(expanded_key) = der.strip_prefix(expanded_key_header.as_slice())
+ {
+ return Ok(ModuleLatticePrivateKey {
+ seed: None,
+ expanded_key: Some(expanded_key),
+ });
+ }
+
+ let both_seed_header = der::header(der::OCTET_STRING, seed_size);
+ let contents_length = both_seed_header.len() + seed_size + expanded_key_header.len() + expanded_key_size;
+ let sequence_header = der::header(der::SEQUENCE, contents_length);
+ if der.len() == sequence_header.len() + contents_length
+ && let Some(rest) = der.strip_prefix(sequence_header.as_slice())
+ && let Some(rest) = rest.strip_prefix(both_seed_header.as_slice())
+ {
+ let (seed, rest) = rest.split_at(seed_size);
+ if let Some(expanded_key) = rest.strip_prefix(expanded_key_header.as_slice()) {
+ return Ok(ModuleLatticePrivateKey {
+ seed: Some(seed),
+ expanded_key: Some(expanded_key),
+ });
+ }
+ }
+ Err(CryptoError::Invalid("Invalid module-lattice private key"))
+}
+
+/// The private key in the privateKey of a PKCS#8 PrivateKeyInfo of `algorithm`, an ML-DSA or ML-KEM algorithm, or None
+/// for a privateKey in the expandedKey form.
+// NB: A key in the expandedKey form, which Web Crypto rejects, has no seed to make an OpenSSL key from, and OpenSSL
+// would refuse an expanded key that is not valid before Web Crypto can reject the form.
+pub(crate) fn parse_private_key(algorithm: KeyAlgorithm, der: &[u8]) -> Result<Option<KeyHandle>, CryptoError> {
+ let parameter_set = match algorithm {
+ KeyAlgorithm::MlDsa(size) => ParameterSet::MlDsa(size),
+ KeyAlgorithm::MlKem(size) => ParameterSet::MlKem(size),
+ _ => unreachable!("The algorithm is ML-DSA or ML-KEM"),
+ };
+ let encoded = parse_module_lattice_private_key(der, parameter_set.seed_size(), parameter_set.expanded_key_size())?;
+ let Some(seed) = encoded.seed else {
+ return Ok(None);
+ };
+ let private_key = MlPrivateKey::from_seed(parameter_set, seed)?;
+ if let Some(expected) = encoded.expanded_key {
+ let expanded_key = private_key.expanded_key()?;
+ if *expanded_key != *expected {
+ return Err(CryptoError::Invalid("The expanded key does not match the seed"));
+ }
+ }
+ Ok(Some(KeyHandle(Key::MlPrivate(private_key))))
+}
+
+impl MlDsaPublicKey {
+ pub(crate) fn stored(&self) -> StoredKey {
+ StoredKey::new(HandleTag::MlDsaPublic, vec![SecretBytes::new(self.bytes.clone())])
+ }
+}
+
+impl MlKemPublicKey {
+ pub(crate) fn stored(&self) -> StoredKey {
+ StoredKey::new(HandleTag::MlKemPublic, vec![SecretBytes::new(self.bytes.clone())])
+ }
+}
+
+impl MlPrivateKey {
+ /// The stored form of the key: its seed, public key and expanded key.
+ pub(crate) fn stored(&self) -> StoredKey {
+ let tag = match self.parameter_set {
+ ParameterSet::MlDsa(_) => HandleTag::MlDsaPrivate,
+ ParameterSet::MlKem(_) => HandleTag::MlKemPrivate,
+ };
+ StoredKey::new(
+ tag,
+ vec![
+ self.seed().expect("OpenSSL gives the seed of a key made from one"),
+ SecretBytes::new(self.public_key.clone()),
+ self.expanded_key().expect("OpenSSL gives the expanded key"),
+ ],
+ )
+ }
+}
+
+/// The key that a stored handle of an ML-DSA or ML-KEM tag holds. A private key is rebuilt from its seed, with the
+/// parameter set that its public key's length names, and must give back that public key.
+pub(crate) fn decode_stored(tag: HandleTag, buffers: &[&[u8]]) -> Result<KeyHandle, KeyDecodeError> {
+ let invalid = || KeyDecodeError::InvalidComponents;
+ let parameter_set = match tag {
+ HandleTag::MlDsaPublic => {
+ return Ok(KeyHandle(Key::MlDsaPublic(
+ mldsa_public_key_from_bytes(buffers[0]).ok_or_else(invalid)?,
+ )));
+ }
+ HandleTag::MlKemPublic => return Ok(KeyHandle(Key::MlKemPublic(mlkem_public_key_from_bytes(buffers[0])))),
+ HandleTag::MlDsaPrivate => {
+ ParameterSet::MlDsa(mldsa_public_key_from_bytes(buffers[1]).ok_or_else(invalid)?.size)
+ }
+ HandleTag::MlKemPrivate => {
+ ParameterSet::MlKem(mlkem_public_key_from_bytes(buffers[1]).size.ok_or_else(invalid)?)
+ }
+ _ => return Err(invalid()),
+ };
+ if buffers[0].is_empty() {
+ return Err(invalid());
+ }
+ let private_key = MlPrivateKey::from_seed(parameter_set, buffers[0]).map_err(|_| invalid())?;
+ if private_key.public_key != buffers[1] {
+ return Err(invalid());
+ }
+ Ok(KeyHandle(Key::MlPrivate(private_key)))
+}
diff --git a/Libraries/LibCrypto/Rust/src/openssl.rs b/Libraries/LibCrypto/Rust/src/openssl.rs
new file mode 100644
index 00000000000..0938ff397ed
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/openssl.rs
@@ -0,0 +1,1386 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Safe wrappers around the OpenSSL calls that libcrypto_rust makes. A failed call's reasons are dropped from OpenSSL's
+//! error queue, and it fails with CryptoError::Backend.
+
+use core::ffi::{CStr, c_int, c_long, c_uint};
+use core::marker::PhantomData;
+use core::ptr::{self, NonNull};
+
+use crate::CryptoError;
+use crate::key::SecretBytes;
+use crate::sys;
+
+fn failed<T>() -> Result<T, CryptoError> {
+ // SAFETY: Clearing the error queue takes no arguments.
+ unsafe { sys::ERR_clear_error() };
+ Err(CryptoError::Backend)
+}
+
+fn check(result: c_int) -> Result<(), CryptoError> {
+ if result > 0 { Ok(()) } else { failed() }
+}
+
+/// An OpenSSL result that is 1 for true and 0 for false, such as a verification's.
+fn check_bool(result: c_int) -> Result<bool, CryptoError> {
+ match result {
+ 1 => Ok(true),
+ 0 => {
+ // SAFETY: Clearing the error queue takes no arguments.
+ unsafe { sys::ERR_clear_error() };
+ Ok(false)
+ }
+ _ => failed(),
+ }
+}
+
+/// `length` as the int that OpenSSL takes for some lengths.
+fn int_length(length: usize) -> Result<c_int, CryptoError> {
+ c_int::try_from(length).map_err(|_| CryptoError::Backend)
+}
+
+macro_rules! owned {
+ ($(#[$meta:meta])* $name:ident, $type:ident, $free:ident) => {
+ $(#[$meta])*
+ pub(crate) struct $name(NonNull<sys::$type>);
+
+ impl $name {
+ fn new(pointer: *mut sys::$type) -> Result<Self, CryptoError> {
+ NonNull::new(pointer).map_or_else(failed, |pointer| Ok(Self(pointer)))
+ }
+
+ pub(crate) fn as_ptr(&self) -> *mut sys::$type {
+ self.0.as_ptr()
+ }
+ }
+
+ impl Drop for $name {
+ fn drop(&mut self) {
+ // SAFETY: The pointer is owned, and is freed only here.
+ unsafe { sys::$free(self.0.as_ptr()) };
+ }
+ }
+ };
+}
+
+owned!(
+ /// A key, which OpenSSL does not change once it is built.
+ Pkey,
+ EVP_PKEY,
+ EVP_PKEY_free
+);
+owned!(PkeyContext, EVP_PKEY_CTX, EVP_PKEY_CTX_free);
+owned!(DigestContext, EVP_MD_CTX, EVP_MD_CTX_free);
+owned!(Digest, EVP_MD, EVP_MD_free);
+owned!(Kdf, EVP_KDF, EVP_KDF_free);
+owned!(KdfContext, EVP_KDF_CTX, EVP_KDF_CTX_free);
+owned!(Mac, EVP_MAC, EVP_MAC_free);
+owned!(MacContext, EVP_MAC_CTX, EVP_MAC_CTX_free);
+owned!(SignatureAlgorithm, EVP_SIGNATURE, EVP_SIGNATURE_free);
+owned!(CipherContext, EVP_CIPHER_CTX, EVP_CIPHER_CTX_free);
+owned!(
+ /// A big number, which is cleared when it is freed.
+ BigNum,
+ BIGNUM,
+ BN_clear_free
+);
+owned!(BigNumContext, BN_CTX, BN_CTX_free);
+owned!(Group, EC_GROUP, EC_GROUP_free);
+owned!(Point, EC_POINT, EC_POINT_free);
+owned!(EcdsaSignature, ECDSA_SIG, ECDSA_SIG_free);
+owned!(ParamArray, OSSL_PARAM, OSSL_PARAM_free);
+owned!(PublicKeyInfoPointer, X509_PUBKEY, X509_PUBKEY_free);
+owned!(
+ /// A PrivateKeyInfo, whose free clears the private key.
+ PrivateKeyInfoPointer,
+ PKCS8_PRIV_KEY_INFO,
+ PKCS8_PRIV_KEY_INFO_free
+);
+
+// SAFETY: OpenSSL keys are reference counted atomically and are not changed once built, so they can be shared and sent
+// between threads.
+unsafe impl Send for Pkey {}
+// SAFETY: See above.
+unsafe impl Sync for Pkey {}
+
+impl Clone for Pkey {
+ fn clone(&self) -> Self {
+ // SAFETY: The key is live; taking a reference keeps it alive for the clone.
+ let result = unsafe { sys::EVP_PKEY_up_ref(self.as_ptr()) };
+ assert_eq!(result, 1, "OpenSSL takes a reference to a key");
+ Self(self.0)
+ }
+}
+
+pub(crate) fn octet_string_parameter(name: &CStr, bytes: &[u8]) -> sys::OSSL_PARAM {
+ // SAFETY: Constructing a parameter only records the pointer and length, which the caller keeps alive.
+ unsafe { sys::OSSL_PARAM_construct_octet_string(name.as_ptr(), bytes.as_ptr().cast_mut().cast(), bytes.len()) }
+}
+
+pub(crate) fn utf8_parameter(name: &CStr, value: &'static CStr) -> sys::OSSL_PARAM {
+ // SAFETY: Constructing a parameter only records the pointer, a static string, and its length.
+ unsafe { sys::OSSL_PARAM_construct_utf8_string(name.as_ptr(), value.as_ptr().cast_mut(), value.count_bytes()) }
+}
+
+pub(crate) fn uint_parameter(name: &CStr, value: &mut c_uint) -> sys::OSSL_PARAM {
+ // SAFETY: Constructing a parameter only records the pointer, which the caller keeps alive.
+ unsafe { sys::OSSL_PARAM_construct_uint(name.as_ptr(), value) }
+}
+
+pub(crate) fn int_parameter(name: &CStr, value: &mut c_int) -> sys::OSSL_PARAM {
+ // SAFETY: Constructing a parameter only records the pointer, which the caller keeps alive.
+ unsafe { sys::OSSL_PARAM_construct_int(name.as_ptr(), value) }
+}
+
+pub(crate) fn end_parameter() -> sys::OSSL_PARAM {
+ // SAFETY: Constructing the end marker takes no pointers.
+ unsafe { sys::OSSL_PARAM_construct_end() }
+}
+
+/// Parameters that hold big numbers, which an OSSL_PARAM_BLD builds.
+// NB: The builder reads each big number and octet string when it builds the parameters, so the numbers live as long as
+// the builder, and the octet strings outlive it.
+pub(crate) struct ParamBuilder<'a> {
+ builder: NonNull<sys::OSSL_PARAM_BLD>,
+ numbers: Vec<BigNum>,
+ octets: PhantomData<&'a [u8]>,
+}
+
+impl Drop for ParamBuilder<'_> {
+ fn drop(&mut self) {
+ // SAFETY: The builder is owned, and is freed only here.
+ unsafe { sys::OSSL_PARAM_BLD_free(self.builder.as_ptr()) };
+ }
+}
+
+impl<'a> ParamBuilder<'a> {
+ pub(crate) fn new() -> Result<Self, CryptoError> {
+ // SAFETY: Making a builder takes no arguments.
+ let builder = NonNull::new(unsafe { sys::OSSL_PARAM_BLD_new() }).map_or_else(failed, Ok)?;
+ Ok(Self {
+ builder,
+ numbers: Vec::new(),
+ octets: PhantomData,
+ })
+ }
+
+ pub(crate) fn push_number(&mut self, name: &'static CStr, bytes: &[u8], secret: bool) -> Result<(), CryptoError> {
+ let number = BigNum::from_bytes(bytes, secret)?;
+ // SAFETY: The builder and number are live, and the number lives as long as the builder.
+ check(unsafe { sys::OSSL_PARAM_BLD_push_BN(self.builder.as_ptr(), name.as_ptr(), number.as_ptr()) })?;
+ self.numbers.push(number);
+ Ok(())
+ }
+
+ pub(crate) fn push_utf8(&mut self, name: &'static CStr, value: &'static CStr) -> Result<(), CryptoError> {
+ // SAFETY: The builder is live, and the strings are static.
+ check(unsafe { sys::OSSL_PARAM_BLD_push_utf8_string(self.builder.as_ptr(), name.as_ptr(), value.as_ptr(), 0) })
+ }
+
+ pub(crate) fn push_octets(&mut self, name: &'static CStr, bytes: &'a [u8]) -> Result<(), CryptoError> {
+ // SAFETY: The builder is live, and the bytes outlive it.
+ check(unsafe {
+ sys::OSSL_PARAM_BLD_push_octet_string(
+ self.builder.as_ptr(),
+ name.as_ptr(),
+ bytes.as_ptr().cast(),
+ bytes.len(),
+ )
+ })
+ }
+
+ pub(crate) fn push_uint(&mut self, name: &'static CStr, value: c_uint) -> Result<(), CryptoError> {
+ // SAFETY: The builder is live, and the name is static.
+ check(unsafe { sys::OSSL_PARAM_BLD_push_uint(self.builder.as_ptr(), name.as_ptr(), value) })
+ }
+
+ pub(crate) fn build(&self) -> Result<ParamArray, CryptoError> {
+ // SAFETY: The builder and the numbers and octet strings it was given are live.
+ ParamArray::new(unsafe { sys::OSSL_PARAM_BLD_to_param(self.builder.as_ptr()) })
+ }
+}
+
+impl BigNum {
+ pub(crate) fn from_bytes(bytes: &[u8], secret: bool) -> Result<Self, CryptoError> {
+ // SAFETY: Making a number takes no arguments.
+ let number = Self::new(unsafe { if secret { sys::BN_secure_new() } else { sys::BN_new() } })?;
+ // SAFETY: The bytes are live for the call, and the number is owned.
+ if unsafe { sys::BN_bin2bn(bytes.as_ptr(), int_length(bytes.len())?, number.as_ptr()) }.is_null() {
+ return failed();
+ }
+ Ok(number)
+ }
+
+ pub(crate) fn num_bits(&self) -> usize {
+ // SAFETY: The number is live.
+ usize::try_from(unsafe { sys::BN_num_bits(self.as_ptr()) }).unwrap_or_default()
+ }
+
+ pub(crate) fn is_odd(&self) -> bool {
+ // SAFETY: The number is live.
+ unsafe { sys::BN_is_odd(self.as_ptr()) == 1 }
+ }
+
+ pub(crate) fn is_less_than(&self, other: &Self) -> bool {
+ // SAFETY: Both numbers are live.
+ unsafe { sys::BN_cmp(self.as_ptr(), other.as_ptr()) < 0 }
+ }
+
+ pub(crate) fn incremented(&self) -> Result<Self, CryptoError> {
+ // SAFETY: Making a number takes no arguments.
+ let result = Self::new(unsafe { sys::BN_new() })?;
+ // SAFETY: All three numbers are live; BN_value_one() is static.
+ check(unsafe { sys::BN_add(result.as_ptr(), self.as_ptr(), sys::BN_value_one()) })?;
+ Ok(result)
+ }
+
+ /// The big-endian bytes of the number, padded with zeros to `length`.
+ pub(crate) fn to_padded(&self, length: usize) -> Result<SecretBytes, CryptoError> {
+ let mut bytes = SecretBytes::new(vec![0; length]);
+ // SAFETY: The buffer holds `length` bytes, and BN_bn2binpad fails if the number does not fit.
+ if unsafe { sys::BN_bn2binpad(self.as_ptr(), bytes.as_mut_ptr(), int_length(length)?) } < 0 {
+ return failed();
+ }
+ Ok(bytes)
+ }
+
+ /// The big-endian bytes of the number, without leading zeros.
+ pub(crate) fn to_bytes(&self) -> Result<SecretBytes, CryptoError> {
+ self.to_padded(self.num_bits().div_ceil(8))
+ }
+}
+
+impl Pkey {
+ fn context(&self) -> Result<PkeyContext, CryptoError> {
+ // SAFETY: The key is live; a non-null result is owned.
+ PkeyContext::new(unsafe { sys::EVP_PKEY_CTX_new_from_pkey(ptr::null_mut(), self.as_ptr(), ptr::null()) })
+ }
+
+ /// The key of the algorithm `name` that `params` describe, with the parts that `selection` names.
+ pub(crate) fn from_data(name: &CStr, selection: c_int, params: *mut sys::OSSL_PARAM) -> Result<Self, CryptoError> {
+ // SAFETY: The name is live; a non-null result is owned.
+ let context =
+ PkeyContext::new(unsafe { sys::EVP_PKEY_CTX_new_from_name(ptr::null_mut(), name.as_ptr(), ptr::null()) })?;
+ // SAFETY: The context is live.
+ check(unsafe { sys::EVP_PKEY_fromdata_init(context.as_ptr()) })?;
+ let mut key = ptr::null_mut();
+ // SAFETY: The context and the caller's parameters are live; a non-null result is owned.
+ check(unsafe { sys::EVP_PKEY_fromdata(context.as_ptr(), &raw mut key, selection, params) })?;
+ Self::new(key)
+ }
+
+ /// A new key of the algorithm `name`, with the generation parameters `params`, which end with the end marker.
+ pub(crate) fn generate(name: &CStr, params: Option<*const sys::OSSL_PARAM>) -> Result<Self, CryptoError> {
+ // SAFETY: The name is live; a non-null result is owned.
+ let context =
+ PkeyContext::new(unsafe { sys::EVP_PKEY_CTX_new_from_name(ptr::null_mut(), name.as_ptr(), ptr::null()) })?;
+ // SAFETY: The context is live.
+ check(unsafe { sys::EVP_PKEY_keygen_init(context.as_ptr()) })?;
+ if let Some(params) = params {
+ // SAFETY: The context and the caller's parameters are live.
+ check(unsafe { sys::EVP_PKEY_CTX_set_params(context.as_ptr(), params) })?;
+ }
+ let mut key = ptr::null_mut();
+ // SAFETY: The context is live; a non-null result is owned.
+ check(unsafe { sys::EVP_PKEY_generate(context.as_ptr(), &raw mut key) })?;
+ Self::new(key)
+ }
+
+ pub(crate) fn from_raw_public_key(name: &CStr, bytes: &[u8]) -> Result<Self, CryptoError> {
+ // SAFETY: The name and bytes are live for the call; a non-null result is owned.
+ Self::new(unsafe {
+ sys::EVP_PKEY_new_raw_public_key_ex(
+ ptr::null_mut(),
+ name.as_ptr(),
+ ptr::null(),
+ bytes.as_ptr(),
+ bytes.len(),
+ )
+ })
+ }
+
+ pub(crate) fn from_raw_private_key(name: &CStr, bytes: &[u8]) -> Result<Self, CryptoError> {
+ // SAFETY: The name and bytes are live for the call; a non-null result is owned.
+ Self::new(unsafe {
+ sys::EVP_PKEY_new_raw_private_key_ex(
+ ptr::null_mut(),
+ name.as_ptr(),
+ ptr::null(),
+ bytes.as_ptr(),
+ bytes.len(),
+ )
+ })
+ }
+
+ pub(crate) fn number(&self, name: &CStr) -> Option<BigNum> {
+ let mut number = ptr::null_mut();
+ // SAFETY: The key and name are live; a non-null result is owned.
+ let result = unsafe { sys::EVP_PKEY_get_bn_param(self.as_ptr(), name.as_ptr(), &raw mut number) };
+ if result != 1 {
+ // SAFETY: BN_clear_free accepts null; clearing the error queue takes no arguments.
+ unsafe {
+ sys::BN_clear_free(number);
+ sys::ERR_clear_error();
+ }
+ return None;
+ }
+ BigNum::new(number).ok()
+ }
+
+ /// The octet string parameter `name` of the key, such as an ML-DSA or ML-KEM key's seed.
+ pub(crate) fn octet_string(&self, name: &CStr) -> Result<SecretBytes, CryptoError> {
+ let mut size = 0;
+ // SAFETY: A null buffer asks for the size, which is written to `size`.
+ check(unsafe {
+ sys::EVP_PKEY_get_octet_string_param(self.as_ptr(), name.as_ptr(), ptr::null_mut(), 0, &raw mut size)
+ })?;
+ let mut bytes = SecretBytes::new(vec![0; size]);
+ // SAFETY: The buffer holds `size` bytes.
+ check(unsafe {
+ sys::EVP_PKEY_get_octet_string_param(self.as_ptr(), name.as_ptr(), bytes.as_mut_ptr(), size, &raw mut size)
+ })?;
+ bytes.truncate(size);
+ Ok(bytes)
+ }
+
+ pub(crate) fn raw_public_key(&self) -> Result<Vec<u8>, CryptoError> {
+ let mut size = 0;
+ // SAFETY: A null buffer asks for the size.
+ check(unsafe { sys::EVP_PKEY_get_raw_public_key(self.as_ptr(), ptr::null_mut(), &raw mut size) })?;
+ let mut bytes = vec![0; size];
+ // SAFETY: The buffer holds `size` bytes.
+ check(unsafe { sys::EVP_PKEY_get_raw_public_key(self.as_ptr(), bytes.as_mut_ptr(), &raw mut size) })?;
+ bytes.truncate(size);
+ Ok(bytes)
+ }
+
+ pub(crate) fn raw_private_key(&self) -> Result<SecretBytes, CryptoError> {
+ let mut size = 0;
+ // SAFETY: A null buffer asks for the size.
+ check(unsafe { sys::EVP_PKEY_get_raw_private_key(self.as_ptr(), ptr::null_mut(), &raw mut size) })?;
+ let mut bytes = SecretBytes::new(vec![0; size]);
+ // SAFETY: The buffer holds `size` bytes.
+ check(unsafe { sys::EVP_PKEY_get_raw_private_key(self.as_ptr(), bytes.as_mut_ptr(), &raw mut size) })?;
+ bytes.truncate(size);
+ Ok(bytes)
+ }
+
+ /// The size of the key's signatures and ciphertexts, in bytes.
+ pub(crate) fn size(&self) -> usize {
+ // SAFETY: The key is live.
+ usize::try_from(unsafe { sys::EVP_PKEY_get_size(self.as_ptr()) }).unwrap_or_default()
+ }
+
+ pub(crate) fn bits(&self) -> u32 {
+ // SAFETY: The key is live.
+ u32::try_from(unsafe { sys::EVP_PKEY_get_bits(self.as_ptr()) }).unwrap_or_default()
+ }
+
+ /// The DER SubjectPublicKeyInfo of the key, as OpenSSL writes it.
+ pub(crate) fn public_key_info(&self) -> Result<Vec<u8>, CryptoError> {
+ let encoded = encoding(self.as_ptr(), sys::i2d_PUBKEY);
+ if encoded.is_empty() {
+ return failed();
+ }
+ Ok(encoded.into_vec())
+ }
+
+ /// The DER encoding of the key's own structure, such as an RSAPrivateKey, as OpenSSL writes it.
+ fn private_key_structure(&self) -> SecretBytes {
+ encoding(self.as_ptr(), sys::i2d_PrivateKey)
+ }
+}
+
+pub(crate) struct KeyChecks {
+ pub(crate) public: bool,
+ pub(crate) private: bool,
+ pub(crate) pairwise: bool,
+}
+
+/// Runs OpenSSL's public, private and pairwise checks of `key`, the last two only when asked for.
+pub(crate) fn check_key(key: &Pkey, private: bool, pairwise: bool) -> Result<KeyChecks, CryptoError> {
+ let context = key.context()?;
+ // SAFETY: The context is live for each call.
+ let checks = unsafe {
+ KeyChecks {
+ public: sys::EVP_PKEY_public_check(context.as_ptr()) == 1,
+ private: !private || sys::EVP_PKEY_private_check(context.as_ptr()) == 1,
+ pairwise: !pairwise || sys::EVP_PKEY_pairwise_check(context.as_ptr()) == 1,
+ }
+ };
+ // NB: A failed check leaves its reasons queued.
+ // SAFETY: Clearing the error queue takes no arguments.
+ unsafe { sys::ERR_clear_error() };
+ Ok(checks)
+}
+
+/// Signs `message` with `key`, hashing it with the digest `digest_name` unless the algorithm takes none. The parameters
+/// end with the end marker.
+pub(crate) fn digest_sign(
+ key: &Pkey,
+ digest_name: Option<&CStr>,
+ params: &[sys::OSSL_PARAM],
+ message: &[u8],
+) -> Result<Vec<u8>, CryptoError> {
+ // SAFETY: Making a context takes no arguments.
+ let context = DigestContext::new(unsafe { sys::EVP_MD_CTX_new() })?;
+ // SAFETY: The context, key, name and parameters are live for the call.
+ check(unsafe {
+ sys::EVP_DigestSignInit_ex(
+ context.as_ptr(),
+ ptr::null_mut(),
+ digest_name.map_or(ptr::null(), CStr::as_ptr),
+ ptr::null_mut(),
+ ptr::null(),
+ key.as_ptr(),
+ params.as_ptr(),
+ )
+ })?;
+ let mut size = 0;
+ // SAFETY: A null signature asks for its size.
+ check(unsafe {
+ sys::EVP_DigestSign(
+ context.as_ptr(),
+ ptr::null_mut(),
+ &raw mut size,
+ message.as_ptr(),
+ message.len(),
+ )
+ })?;
+ let mut signature = vec![0; size];
+ // SAFETY: The signature buffer holds `size` bytes.
+ check(unsafe {
+ sys::EVP_DigestSign(
+ context.as_ptr(),
+ signature.as_mut_ptr(),
+ &raw mut size,
+ message.as_ptr(),
+ message.len(),
+ )
+ })?;
+ signature.truncate(size);
+ Ok(signature)
+}
+
+/// Verifies `signature` of `message` with `key`, as `digest_sign()` makes it.
+pub(crate) fn digest_verify(
+ key: &Pkey,
+ digest_name: Option<&CStr>,
+ params: &[sys::OSSL_PARAM],
+ message: &[u8],
+ signature: &[u8],
+) -> Result<bool, CryptoError> {
+ // SAFETY: Making a context takes no arguments.
+ let context = DigestContext::new(unsafe { sys::EVP_MD_CTX_new() })?;
+ // SAFETY: The context, key, name and parameters are live for the call.
+ check(unsafe {
+ sys::EVP_DigestVerifyInit_ex(
+ context.as_ptr(),
+ ptr::null_mut(),
+ digest_name.map_or(ptr::null(), CStr::as_ptr),
+ ptr::null_mut(),
+ ptr::null(),
+ key.as_ptr(),
+ params.as_ptr(),
+ )
+ })?;
+ // SAFETY: The context and both buffers are live for the call.
+ check_bool(unsafe {
+ sys::EVP_DigestVerify(
+ context.as_ptr(),
+ signature.as_ptr(),
+ signature.len(),
+ message.as_ptr(),
+ message.len(),
+ )
+ })
+}
+
+/// Signs `digest`, a message's hash, with `key`.
+pub(crate) fn sign_digest(key: &Pkey, digest: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let context = key.context()?;
+ // SAFETY: The context is live.
+ check(unsafe { sys::EVP_PKEY_sign_init(context.as_ptr()) })?;
+ let mut size = 0;
+ // SAFETY: A null signature asks for its size.
+ check(unsafe {
+ sys::EVP_PKEY_sign(
+ context.as_ptr(),
+ ptr::null_mut(),
+ &raw mut size,
+ digest.as_ptr(),
+ digest.len(),
+ )
+ })?;
+ let mut signature = vec![0; size];
+ // SAFETY: The signature buffer holds `size` bytes.
+ check(unsafe {
+ sys::EVP_PKEY_sign(
+ context.as_ptr(),
+ signature.as_mut_ptr(),
+ &raw mut size,
+ digest.as_ptr(),
+ digest.len(),
+ )
+ })?;
+ signature.truncate(size);
+ Ok(signature)
+}
+
+/// Verifies `signature` of `digest`, a message's hash, with `key`.
+pub(crate) fn verify_digest(key: &Pkey, digest: &[u8], signature: &[u8]) -> Result<bool, CryptoError> {
+ let context = key.context()?;
+ // SAFETY: The context is live.
+ check(unsafe { sys::EVP_PKEY_verify_init(context.as_ptr()) })?;
+ // SAFETY: The context and both buffers are live for the call.
+ check_bool(unsafe {
+ sys::EVP_PKEY_verify(
+ context.as_ptr(),
+ signature.as_ptr(),
+ signature.len(),
+ digest.as_ptr(),
+ digest.len(),
+ )
+ })
+}
+
+/// Signs `message` with `key` by the message signature algorithm `algorithm` (such as "ML-DSA-44"), with a context
+/// string when one is given.
+pub(crate) fn sign_message(
+ key: &Pkey,
+ algorithm: &CStr,
+ message: &[u8],
+ context: &[u8],
+) -> Result<Vec<u8>, CryptoError> {
+ let key_context = key.context()?;
+ // SAFETY: The name is live; a non-null result is owned.
+ let signature_algorithm =
+ SignatureAlgorithm::new(unsafe { sys::EVP_SIGNATURE_fetch(ptr::null_mut(), algorithm.as_ptr(), ptr::null()) })?;
+ let params = optional_context_string_parameters(context);
+ // SAFETY: The context, algorithm, parameters and buffers are live for each call, and the signature buffer holds the
+ // size that the first call gives.
+ unsafe {
+ check(sys::EVP_PKEY_sign_message_init(
+ key_context.as_ptr(),
+ signature_algorithm.as_ptr(),
+ params.as_ptr(),
+ ))?;
+ let mut size = 0;
+ check(sys::EVP_PKEY_sign(
+ key_context.as_ptr(),
+ ptr::null_mut(),
+ &raw mut size,
+ message.as_ptr(),
+ message.len(),
+ ))?;
+ let mut signature = vec![0; size];
+ check(sys::EVP_PKEY_sign(
+ key_context.as_ptr(),
+ signature.as_mut_ptr(),
+ &raw mut size,
+ message.as_ptr(),
+ message.len(),
+ ))?;
+ signature.truncate(size);
+ Ok(signature)
+ }
+}
+
+/// Verifies `signature` of `message` with `key`, as `sign_message()` makes it.
+pub(crate) fn verify_message(
+ key: &Pkey,
+ algorithm: &CStr,
+ message: &[u8],
+ signature: &[u8],
+ context: &[u8],
+) -> Result<bool, CryptoError> {
+ let key_context = key.context()?;
+ // SAFETY: The name is live; a non-null result is owned.
+ let signature_algorithm =
+ SignatureAlgorithm::new(unsafe { sys::EVP_SIGNATURE_fetch(ptr::null_mut(), algorithm.as_ptr(), ptr::null()) })?;
+ let params = optional_context_string_parameters(context);
+ // SAFETY: The context, algorithm, parameters and buffers are live for each call.
+ unsafe {
+ check(sys::EVP_PKEY_verify_message_init(
+ key_context.as_ptr(),
+ signature_algorithm.as_ptr(),
+ params.as_ptr(),
+ ))?;
+ check_bool(sys::EVP_PKEY_verify(
+ key_context.as_ptr(),
+ signature.as_ptr(),
+ signature.len(),
+ message.as_ptr(),
+ message.len(),
+ ))
+ }
+}
+
+pub(crate) fn context_string_parameters(context: &[u8]) -> [sys::OSSL_PARAM; 2] {
+ [octet_string_parameter(c"context-string", context), end_parameter()]
+}
+
+fn optional_context_string_parameters(context: &[u8]) -> [sys::OSSL_PARAM; 2] {
+ if context.is_empty() {
+ [end_parameter(), end_parameter()]
+ } else {
+ context_string_parameters(context)
+ }
+}
+
+/// Encrypts `input` with `key`, with the parameters `params`, which end with the end marker.
+pub(crate) fn encrypt(key: &Pkey, params: &[sys::OSSL_PARAM], input: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let context = key.context()?;
+ // SAFETY: The context and parameters are live.
+ check(unsafe { sys::EVP_PKEY_encrypt_init_ex(context.as_ptr(), params.as_ptr()) })?;
+ let mut size = 0;
+ // SAFETY: A null output asks for its size.
+ check(unsafe {
+ sys::EVP_PKEY_encrypt(
+ context.as_ptr(),
+ ptr::null_mut(),
+ &raw mut size,
+ input.as_ptr(),
+ input.len(),
+ )
+ })?;
+ let mut output = vec![0; size];
+ // SAFETY: The output holds `size` bytes.
+ check(unsafe {
+ sys::EVP_PKEY_encrypt(
+ context.as_ptr(),
+ output.as_mut_ptr(),
+ &raw mut size,
+ input.as_ptr(),
+ input.len(),
+ )
+ })?;
+ output.truncate(size);
+ Ok(output)
+}
+
+/// Decrypts `input` with `key`, with the parameters `params`, which end with the end marker.
+pub(crate) fn decrypt(key: &Pkey, params: &[sys::OSSL_PARAM], input: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let context = key.context()?;
+ // SAFETY: The context and parameters are live.
+ check(unsafe { sys::EVP_PKEY_decrypt_init_ex(context.as_ptr(), params.as_ptr()) })?;
+ let mut size = 0;
+ // SAFETY: A null output asks for its size.
+ check(unsafe {
+ sys::EVP_PKEY_decrypt(
+ context.as_ptr(),
+ ptr::null_mut(),
+ &raw mut size,
+ input.as_ptr(),
+ input.len(),
+ )
+ })?;
+ let mut output = vec![0; size];
+ // SAFETY: The output holds `size` bytes.
+ check(unsafe {
+ sys::EVP_PKEY_decrypt(
+ context.as_ptr(),
+ output.as_mut_ptr(),
+ &raw mut size,
+ input.as_ptr(),
+ input.len(),
+ )
+ })?;
+ output.truncate(size);
+ Ok(output)
+}
+
+/// The secret that `key` and the public key `peer` agree on. OpenSSL checks the peer when `validate_peer` is set.
+pub(crate) fn derive(key: &Pkey, peer: &Pkey, validate_peer: bool) -> Result<Vec<u8>, CryptoError> {
+ let context = key.context()?;
+ // SAFETY: The context and peer are live for each call, and the output holds the size the first call gives.
+ unsafe {
+ check(sys::EVP_PKEY_derive_init(context.as_ptr()))?;
+ check(sys::EVP_PKEY_derive_set_peer_ex(
+ context.as_ptr(),
+ peer.as_ptr(),
+ c_int::from(validate_peer),
+ ))?;
+ let mut size = 0;
+ check(sys::EVP_PKEY_derive(context.as_ptr(), ptr::null_mut(), &raw mut size))?;
+ let mut secret = vec![0; size];
+ check(sys::EVP_PKEY_derive(
+ context.as_ptr(),
+ secret.as_mut_ptr(),
+ &raw mut size,
+ ))?;
+ secret.truncate(size);
+ Ok(secret)
+ }
+}
+
+/// A new shared key encapsulated to `key`, with its ciphertext.
+pub(crate) fn encapsulate(key: &Pkey) -> Result<(SecretBytes, Vec<u8>), CryptoError> {
+ let context = key.context()?;
+ // SAFETY: The context and buffers are live for each call, and the buffers hold the sizes the first call gives.
+ unsafe {
+ check(sys::EVP_PKEY_encapsulate_init(context.as_ptr(), ptr::null()))?;
+ let (mut ciphertext_size, mut shared_key_size) = (0, 0);
+ check(sys::EVP_PKEY_encapsulate(
+ context.as_ptr(),
+ ptr::null_mut(),
+ &raw mut ciphertext_size,
+ ptr::null_mut(),
+ &raw mut shared_key_size,
+ ))?;
+ let mut ciphertext = vec![0; ciphertext_size];
+ let mut shared_key = SecretBytes::new(vec![0; shared_key_size]);
+ check(sys::EVP_PKEY_encapsulate(
+ context.as_ptr(),
+ ciphertext.as_mut_ptr(),
+ &raw mut ciphertext_size,
+ shared_key.as_mut_ptr(),
+ &raw mut shared_key_size,
+ ))?;
+ ciphertext.truncate(ciphertext_size);
+ shared_key.truncate(shared_key_size);
+ Ok((shared_key, ciphertext))
+ }
+}
+
+/// The shared key that `ciphertext` encapsulates to `key`.
+pub(crate) fn decapsulate(key: &Pkey, ciphertext: &[u8]) -> Result<SecretBytes, CryptoError> {
+ let context = key.context()?;
+ // SAFETY: The context and buffers are live for each call, and the buffer holds the size the first call gives.
+ unsafe {
+ check(sys::EVP_PKEY_decapsulate_init(context.as_ptr(), ptr::null()))?;
+ let mut size = 0;
+ check(sys::EVP_PKEY_decapsulate(
+ context.as_ptr(),
+ ptr::null_mut(),
+ &raw mut size,
+ ciphertext.as_ptr(),
+ ciphertext.len(),
+ ))?;
+ let mut shared_key = SecretBytes::new(vec![0; size]);
+ check(sys::EVP_PKEY_decapsulate(
+ context.as_ptr(),
+ shared_key.as_mut_ptr(),
+ &raw mut size,
+ ciphertext.as_ptr(),
+ ciphertext.len(),
+ ))?;
+ shared_key.truncate(size);
+ Ok(shared_key)
+ }
+}
+
+/// The uncompressed public point of the private value `scalar` on the curve `nid`, or None if `scalar` is not in
+/// [1, n - 1].
+pub(crate) fn ec_public_point(nid: c_int, scalar: &[u8]) -> Result<Option<Vec<u8>>, CryptoError> {
+ // SAFETY: Making a group takes the curve's NID; a non-null result is owned.
+ let group = Group::new(unsafe { sys::EC_GROUP_new_by_curve_name(nid) })?;
+ let scalar = BigNum::from_bytes(scalar, true)?;
+ // SAFETY: The group is live, and owns its order.
+ let order = unsafe { sys::EC_GROUP_get0_order(group.as_ptr()) };
+ // SAFETY: Both numbers are live.
+ // NB: SEC 1 requires d to be in [1, n − 1].
+ if scalar.num_bits() == 0 || unsafe { sys::BN_cmp(scalar.as_ptr(), order) } >= 0 {
+ return Ok(None);
+ }
+
+ // SAFETY: Making a context takes no arguments.
+ let context = BigNumContext::new(unsafe { sys::BN_CTX_new() })?;
+ // SAFETY: The group is live; a non-null result is owned.
+ let point = Point::new(unsafe { sys::EC_POINT_new(group.as_ptr()) })?;
+ // SAFETY: The group, point, scalar and context are live.
+ check(unsafe {
+ sys::EC_POINT_mul(
+ group.as_ptr(),
+ point.as_ptr(),
+ scalar.as_ptr(),
+ ptr::null(),
+ ptr::null(),
+ context.as_ptr(),
+ )
+ })?;
+ // SAFETY: A null buffer asks for the size.
+ let size = unsafe {
+ sys::EC_POINT_point2oct(
+ group.as_ptr(),
+ point.as_ptr(),
+ sys::POINT_CONVERSION_UNCOMPRESSED,
+ ptr::null_mut(),
+ 0,
+ context.as_ptr(),
+ )
+ };
+ let mut encoded = vec![0; size];
+ // SAFETY: The buffer holds `size` bytes.
+ let written = unsafe {
+ sys::EC_POINT_point2oct(
+ group.as_ptr(),
+ point.as_ptr(),
+ sys::POINT_CONVERSION_UNCOMPRESSED,
+ encoded.as_mut_ptr(),
+ size,
+ context.as_ptr(),
+ )
+ };
+ if size == 0 || written != size {
+ return failed();
+ }
+ Ok(Some(encoded))
+}
+
+/// The ECDSA signature (r, s) of `digest` by `key`, each of `scalar_size` bytes.
+pub(crate) fn ecdsa_sign(key: &Pkey, digest: &[u8], scalar_size: usize) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
+ let encoded = sign_digest(key, digest)?;
+ let mut cursor = encoded.as_ptr();
+ // SAFETY: The cursor points into `encoded`, of the length given; a non-null result is owned.
+ let signature = EcdsaSignature::new(unsafe {
+ sys::d2i_ECDSA_SIG(ptr::null_mut(), &raw mut cursor, int_length(encoded.len())?.into())
+ })?;
+ let (mut r, mut s) = (ptr::null(), ptr::null());
+ // SAFETY: The signature is live, and owns r and s.
+ unsafe { sys::ECDSA_SIG_get0(signature.as_ptr(), &raw mut r, &raw mut s) };
+ let padded = |number: *const sys::BIGNUM| -> Result<Vec<u8>, CryptoError> {
+ let mut bytes = vec![0; scalar_size];
+ // SAFETY: The number is live while the signature is, and the buffer holds `scalar_size` bytes.
+ if unsafe { sys::BN_bn2binpad(number, bytes.as_mut_ptr(), int_length(scalar_size)?) } < 0 {
+ return failed();
+ }
+ Ok(bytes)
+ };
+ Ok((padded(r)?, padded(s)?))
+}
+
+/// Verifies the ECDSA signature (r, s) of `digest` with `key`.
+pub(crate) fn ecdsa_verify(key: &Pkey, digest: &[u8], r: &[u8], s: &[u8]) -> Result<bool, CryptoError> {
+ // SAFETY: Making a signature takes no arguments.
+ let signature = EcdsaSignature::new(unsafe { sys::ECDSA_SIG_new() })?;
+ let r = BigNum::from_bytes(r, false)?;
+ let s = BigNum::from_bytes(s, false)?;
+ // SAFETY: The signature takes r and s; they are not freed here once it has.
+ check(unsafe { sys::ECDSA_SIG_set0(signature.as_ptr(), r.as_ptr(), s.as_ptr()) })?;
+ core::mem::forget(r);
+ core::mem::forget(s);
+ let encoded = encoding(signature.as_ptr(), sys::i2d_ECDSA_SIG);
+ if encoded.is_empty() {
+ return failed();
+ }
+ verify_digest(key, digest, &encoded)
+}
+
+/// The digest `name` (such as "SHA256") of `data`.
+pub(crate) fn digest(name: &CStr, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let mut output = vec![0; 64];
+ let mut size = 0;
+ // SAFETY: The name and data are live, and the output holds 64 bytes, the size of the largest digest.
+ check(unsafe {
+ sys::EVP_Q_digest(
+ ptr::null_mut(),
+ name.as_ptr(),
+ ptr::null(),
+ data.as_ptr().cast(),
+ data.len(),
+ output.as_mut_ptr(),
+ &raw mut size,
+ )
+ })?;
+ output.truncate(size);
+ Ok(output)
+}
+
+/// `output.len()` bytes of the extendable-output function `name` (such as "SHAKE128") of the parts of `data`.
+pub(crate) fn extendable_output(name: &CStr, data: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError> {
+ // SAFETY: The name is live; a non-null result is owned.
+ let digest = Digest::new(unsafe { sys::EVP_MD_fetch(ptr::null_mut(), name.as_ptr(), ptr::null()) })?;
+ // SAFETY: Making a context takes no arguments.
+ let context = DigestContext::new(unsafe { sys::EVP_MD_CTX_new() })?;
+ // SAFETY: The context, digest and buffers are live for each call.
+ unsafe {
+ check(sys::EVP_DigestInit_ex(
+ context.as_ptr(),
+ digest.as_ptr(),
+ ptr::null_mut(),
+ ))?;
+ for part in data {
+ check(sys::EVP_DigestUpdate(
+ context.as_ptr(),
+ part.as_ptr().cast(),
+ part.len(),
+ ))?;
+ }
+ check(sys::EVP_DigestFinalXOF(
+ context.as_ptr(),
+ output.as_mut_ptr(),
+ output.len(),
+ ))
+ }
+}
+
+/// The MAC `name` (such as "HMAC") of `message` under `key`, `output_size` bytes long, with the parameters `params`,
+/// which end with the end marker.
+pub(crate) fn mac(
+ name: &CStr,
+ key: &[u8],
+ message: &[u8],
+ output_size: usize,
+ params: &[sys::OSSL_PARAM],
+) -> Result<Vec<u8>, CryptoError> {
+ // SAFETY: The name is live; a non-null result is owned.
+ let mac = Mac::new(unsafe { sys::EVP_MAC_fetch(ptr::null_mut(), name.as_ptr(), ptr::null()) })?;
+ // SAFETY: The MAC is live; a non-null result is owned.
+ let context = MacContext::new(unsafe { sys::EVP_MAC_CTX_new(mac.as_ptr()) })?;
+ // SAFETY: The context, key, parameters and buffers are live for each call, and the output holds `output_size` bytes.
+ unsafe {
+ check(sys::EVP_MAC_init(
+ context.as_ptr(),
+ key.as_ptr(),
+ key.len(),
+ params.as_ptr(),
+ ))?;
+ check(sys::EVP_MAC_update(context.as_ptr(), message.as_ptr(), message.len()))?;
+ let mut output = vec![0; output_size];
+ let mut written = 0;
+ check(sys::EVP_MAC_final(
+ context.as_ptr(),
+ output.as_mut_ptr(),
+ &raw mut written,
+ output.len(),
+ ))?;
+ if written != output_size {
+ return failed();
+ }
+ Ok(output)
+ }
+}
+
+/// Derives `output.len()` bytes with the KDF `name` (such as "HKDF") and the parameters `params`, which end with the
+/// end marker.
+// NB: The parameters point at the caller's buffers, so OpenSSL copies secrets only into the KDF context, which clears
+// them.
+pub(crate) fn kdf(name: &CStr, params: &[sys::OSSL_PARAM], output: &mut [u8]) -> Result<(), CryptoError> {
+ // SAFETY: The name is live; a non-null result is owned.
+ let kdf = Kdf::new(unsafe { sys::EVP_KDF_fetch(ptr::null_mut(), name.as_ptr(), ptr::null()) })?;
+ // SAFETY: The KDF is live; a non-null result is owned.
+ let context = KdfContext::new(unsafe { sys::EVP_KDF_CTX_new(kdf.as_ptr()) })?;
+ // SAFETY: The context, parameters and output are live, and the output holds its length.
+ check(unsafe { sys::EVP_KDF_derive(context.as_ptr(), output.as_mut_ptr(), output.len(), params.as_ptr()) })
+}
+
+pub(crate) fn fill_with_random(bytes: &mut [u8]) -> Result<(), CryptoError> {
+ for chunk in bytes.chunks_mut(c_int::MAX as usize) {
+ // SAFETY: The chunk holds the length given.
+ check(unsafe { sys::RAND_bytes(chunk.as_mut_ptr(), int_length(chunk.len())?) })?;
+ }
+ Ok(())
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) struct Cipher(*const sys::EVP_CIPHER);
+
+impl Cipher {
+ pub(crate) fn from_static(getter: unsafe extern "C" fn() -> *const sys::EVP_CIPHER) -> Self {
+ // SAFETY: The getters return static ciphers.
+ Self(unsafe { getter() })
+ }
+}
+
+// NB: OpenSSL takes cipher input lengths as int, so input goes to it in pieces of at most this size.
+const MAXIMUM_UPDATE_LENGTH: usize = 1 << 30;
+// NB: Cipher updates write at most a block, or a key wrap's integrity check, more than their input.
+const MAXIMUM_UPDATE_GROWTH: usize = 32;
+
+impl CipherContext {
+ pub(crate) fn create() -> Result<Self, CryptoError> {
+ // SAFETY: Making a context takes no arguments.
+ Self::new(unsafe { sys::EVP_CIPHER_CTX_new() })
+ }
+
+ /// Sets up the context to encrypt or decrypt with whichever of the cipher, key and IV are given. The key and IV must
+ /// be of the sizes the cipher takes.
+ pub(crate) fn init(
+ &mut self,
+ encrypt: bool,
+ cipher: Option<Cipher>,
+ key: Option<&[u8]>,
+ iv: Option<&[u8]>,
+ ) -> Result<(), CryptoError> {
+ // SAFETY: The context, cipher and buffers are live for the call.
+ check(unsafe {
+ sys::EVP_CipherInit_ex(
+ self.as_ptr(),
+ cipher.map_or(ptr::null(), |cipher| cipher.0),
+ ptr::null_mut(),
+ key.map_or(ptr::null(), <[u8]>::as_ptr),
+ iv.map_or(ptr::null(), <[u8]>::as_ptr),
+ c_int::from(encrypt),
+ )
+ })
+ }
+
+ fn control(&mut self, kind: c_int, argument: usize, pointer: *mut u8) -> Result<(), CryptoError> {
+ // SAFETY: The context is live, and the pointer is null or holds `argument` bytes.
+ check(unsafe { sys::EVP_CIPHER_CTX_ctrl(self.as_ptr(), kind, int_length(argument)?, pointer.cast()) })
+ }
+
+ pub(crate) fn set_iv_length(&mut self, length: usize) -> Result<(), CryptoError> {
+ self.control(sys::EVP_CTRL_AEAD_SET_IVLEN, length, ptr::null_mut())
+ }
+
+ pub(crate) fn set_tag_length(&mut self, length: usize) -> Result<(), CryptoError> {
+ self.control(sys::EVP_CTRL_AEAD_SET_TAG, length, ptr::null_mut())
+ }
+
+ pub(crate) fn set_tag(&mut self, tag: &[u8]) -> Result<(), CryptoError> {
+ // NB: OpenSSL copies the tag, and does not write to it.
+ self.control(sys::EVP_CTRL_AEAD_SET_TAG, tag.len(), tag.as_ptr().cast_mut())
+ }
+
+ pub(crate) fn tag(&mut self, length: usize) -> Result<Vec<u8>, CryptoError> {
+ let mut tag = vec![0; length];
+ self.control(sys::EVP_CTRL_AEAD_GET_TAG, length, tag.as_mut_ptr())?;
+ Ok(tag)
+ }
+
+ pub(crate) fn allow_key_wrapping(&mut self) {
+ // SAFETY: The context is live.
+ unsafe { sys::EVP_CIPHER_CTX_set_flags(self.as_ptr(), sys::EVP_CIPHER_CTX_FLAG_WRAP_ALLOW) };
+ }
+
+ pub(crate) fn add_additional_data(&mut self, data: &[u8]) -> Result<(), CryptoError> {
+ for chunk in data.chunks(MAXIMUM_UPDATE_LENGTH) {
+ let mut written = 0;
+ // SAFETY: A null output passes the chunk as additional data.
+ check(unsafe {
+ sys::EVP_CipherUpdate(
+ self.as_ptr(),
+ ptr::null_mut(),
+ &raw mut written,
+ chunk.as_ptr(),
+ int_length(chunk.len())?,
+ )
+ })?;
+ }
+ Ok(())
+ }
+
+ pub(crate) fn update(&mut self, input: &[u8], output: &mut Vec<u8>) -> Result<(), CryptoError> {
+ for chunk in input.chunks(MAXIMUM_UPDATE_LENGTH) {
+ self.update_whole(chunk, output)?;
+ }
+ Ok(())
+ }
+
+ /// Passes all of `input` to OpenSSL in one update, as key wrapping needs, which fails for input whose length does
+ /// not fit in an int.
+ pub(crate) fn update_whole(&mut self, input: &[u8], output: &mut Vec<u8>) -> Result<(), CryptoError> {
+ let input_length = int_length(input.len())?;
+ output.reserve(input.len() + MAXIMUM_UPDATE_GROWTH);
+ let mut written = 0;
+ // SAFETY: The output has room for the input and the most that an update writes beyond it.
+ check(unsafe {
+ sys::EVP_CipherUpdate(
+ self.as_ptr(),
+ output.as_mut_ptr().add(output.len()),
+ &raw mut written,
+ input.as_ptr(),
+ input_length,
+ )
+ })?;
+ // SAFETY: OpenSSL wrote `written` bytes past the end.
+ unsafe { output.set_len(output.len() + usize::try_from(written).unwrap_or_default()) };
+ Ok(())
+ }
+
+ pub(crate) fn finalize(&mut self, output: &mut Vec<u8>) -> Result<(), CryptoError> {
+ output.reserve(MAXIMUM_UPDATE_GROWTH);
+ let mut written = 0;
+ // SAFETY: The output has room for the most that finalizing writes.
+ check(unsafe {
+ sys::EVP_CipherFinal_ex(self.as_ptr(), output.as_mut_ptr().add(output.len()), &raw mut written)
+ })?;
+ // SAFETY: OpenSSL wrote `written` bytes past the end.
+ unsafe { output.set_len(output.len() + usize::try_from(written).unwrap_or_default()) };
+ Ok(())
+ }
+}
+
+/// The DER encoding that an i2d function gives of `object`, or nothing if it fails.
+fn encoding<T>(object: *const T, i2d: unsafe extern "C" fn(*const T, *mut *mut u8) -> c_int) -> SecretBytes {
+ // SAFETY: A null output asks for the length.
+ let length = unsafe { i2d(object, ptr::null_mut()) };
+ let Ok(length) = usize::try_from(length) else {
+ // SAFETY: Clearing the error queue takes no arguments.
+ unsafe { sys::ERR_clear_error() };
+ return SecretBytes::new(Vec::new());
+ };
+ let mut encoded = SecretBytes::new(vec![0; length]);
+ let mut output = encoded.as_mut_ptr();
+ // SAFETY: The buffer holds the length the first call gave.
+ unsafe { i2d(object, &raw mut output) };
+ encoded
+}
+
+/// The kinds of key the parsers treat differently.
+#[derive(PartialEq, Eq)]
+pub(crate) enum KeyKind {
+ Rsa,
+ Ec,
+ MlKem,
+ MlDsa,
+ Other,
+}
+
+pub(crate) struct AlgorithmIdentifier {
+ // The contents of the DER encoding of the algorithm's object identifier.
+ pub(crate) oid: Vec<u8>,
+ // The parameters, when they are an object identifier, such as the named curve of an EC key.
+ pub(crate) curve: Option<Vec<u8>>,
+ parameters_type: c_int,
+}
+
+impl AlgorithmIdentifier {
+ pub(crate) fn has_parameters(&self) -> bool {
+ self.parameters_type != sys::V_ASN1_UNDEF
+ }
+}
+
+pub(crate) struct PublicKeyInfo {
+ pub(crate) algorithm: AlgorithmIdentifier,
+ pub(crate) raw_key: Vec<u8>,
+ pub(crate) consumed: usize,
+ // The key OpenSSL decoded, which it does not for ML-KEM.
+ pub(crate) key: Option<Pkey>,
+}
+
+pub(crate) struct PrivateKeyInfo {
+ pub(crate) algorithm: AlgorithmIdentifier,
+ pub(crate) raw_key: SecretBytes,
+ pub(crate) consumed: usize,
+ // The key OpenSSL decoded, which it does not for ML-DSA and ML-KEM.
+ pub(crate) key: Option<Pkey>,
+}
+
+fn object_identifier(object: *const sys::ASN1_OBJECT) -> Vec<u8> {
+ // SAFETY: The object is live, and owns the data of the length it gives.
+ unsafe { ak::slice_from_raw_parts(sys::OBJ_get0_data(object), sys::OBJ_length(object)).to_vec() }
+}
+
+fn algorithm_identifier(algorithm: *const sys::X509_ALGOR) -> AlgorithmIdentifier {
+ let mut object = ptr::null();
+ let mut parameters_type = 0;
+ let mut parameters = ptr::null();
+ // SAFETY: The algorithm is live, and the outputs are live locals.
+ unsafe {
+ sys::X509_ALGOR_get0(
+ &raw mut object,
+ &raw mut parameters_type,
+ &raw mut parameters,
+ algorithm,
+ );
+ };
+ let curve = (parameters_type == sys::V_ASN1_OBJECT).then(|| object_identifier(parameters.cast()));
+ AlgorithmIdentifier {
+ oid: object_identifier(object),
+ curve,
+ parameters_type,
+ }
+}
+
+// NB: The structure is in DER, so its SEQUENCE's length takes one byte, or one more than the count in that byte's low
+// bits. Version 0 follows as 02 01 00.
+fn has_version_zero(der: &[u8]) -> bool {
+ let Some(&length_byte) = der.get(1) else {
+ return false;
+ };
+ let header_size = 2 + if length_byte & 0x80 != 0 {
+ usize::from(length_byte & 0x7f)
+ } else {
+ 0
+ };
+ der.get(header_size..header_size + 3) == Some(&[0x02, 0x01, 0x00])
+}
+
+/// Parses the DER SubjectPublicKeyInfo at the start of `data`, which must be the encoding OpenSSL gives back for it.
+pub(crate) fn parse_subject_public_key_info(
+ data: &[u8],
+ kind_of: impl Fn(&[u8]) -> KeyKind,
+) -> Result<PublicKeyInfo, &'static str> {
+ let invalid = "Invalid SubjectPublicKeyInfo";
+ let mut cursor = data.as_ptr();
+ // SAFETY: The cursor points into `data`, of the length given; a non-null result is owned.
+ let public_key_info = PublicKeyInfoPointer::new(unsafe {
+ sys::d2i_X509_PUBKEY(
+ ptr::null_mut(),
+ &raw mut cursor,
+ c_long::try_from(data.len()).unwrap_or(c_long::MAX),
+ )
+ })
+ .map_err(|_| invalid)?;
+ // SAFETY: d2i advanced the cursor within `data`.
+ let consumed = unsafe { cursor.offset_from(data.as_ptr()) } as usize;
+ let input = &data[..consumed];
+
+ let mut algorithm = ptr::null_mut();
+ let mut key_bits = ptr::null();
+ let mut key_size = 0;
+ // SAFETY: The structure is live, and the outputs are live locals.
+ if unsafe {
+ sys::X509_PUBKEY_get0_param(
+ ptr::null_mut(),
+ &raw mut key_bits,
+ &raw mut key_size,
+ &raw mut algorithm,
+ public_key_info.as_ptr(),
+ )
+ } != 1
+ {
+ return failed().map_err(|_| invalid);
+ }
+ let algorithm = algorithm_identifier(algorithm);
+ let key_size = usize::try_from(key_size).unwrap_or_default();
+ // SAFETY: OpenSSL gives the key's bits, of `key_size` bytes, which the structure owns.
+ let raw_key = unsafe { ak::slice_from_raw_parts(key_bits, key_size) }.to_vec();
+
+ // NB: OpenSSL runs the ML-KEM encapsulation key check when it decodes the key, but Web Crypto runs it at
+ // encapsulation. So an ML-KEM key is only checked to be in DER, without parameters.
+ if kind_of(&algorithm.oid) == KeyKind::MlKem {
+ if algorithm.has_parameters() {
+ return Err("The algorithm takes no parameters");
+ }
+ // NB: The BIT STRING's contents end the encoding, and are its count of unused bits followed by the key.
+ if *encoding(public_key_info.as_ptr(), sys::i2d_X509_PUBKEY) != *input || input[consumed - key_size - 1] != 0 {
+ return Err("SubjectPublicKeyInfo is not in DER");
+ }
+ return Ok(PublicKeyInfo {
+ algorithm,
+ raw_key,
+ consumed,
+ key: None,
+ });
+ }
+
+ // SAFETY: The structure is live; a non-null result is owned.
+ let key = Pkey::new(unsafe { sys::X509_PUBKEY_get(public_key_info.as_ptr()) })
+ .map_err(|_| "Invalid or unsupported public key")?;
+
+ // NB: OpenSSL accepts BER, and parameters that an algorithm does not use. Its own encoding of the key is the DER
+ // encoding with the parameters that the algorithm takes, so any other input is not valid.
+ if key
+ .public_key_info()
+ .map_err(|_| "SubjectPublicKeyInfo is not in DER")?
+ != input
+ {
+ return Err("SubjectPublicKeyInfo is not in DER");
+ }
+ Ok(PublicKeyInfo {
+ algorithm,
+ raw_key,
+ consumed,
+ key: Some(key),
+ })
+}
+
+/// Parses the DER PrivateKeyInfo at the start of `data`, which must be the encoding OpenSSL gives back for it.
+pub(crate) fn parse_private_key_info(
+ data: &[u8],
+ kind_of: impl Fn(&[u8]) -> KeyKind,
+) -> Result<PrivateKeyInfo, &'static str> {
+ let invalid = "Invalid PrivateKeyInfo";
+ let mut cursor = data.as_ptr();
+ // SAFETY: The cursor points into `data`, of the length given; a non-null result is owned.
+ let private_key_info = PrivateKeyInfoPointer::new(unsafe {
+ sys::d2i_PKCS8_PRIV_KEY_INFO(
+ ptr::null_mut(),
+ &raw mut cursor,
+ c_long::try_from(data.len()).unwrap_or(c_long::MAX),
+ )
+ })
+ .map_err(|_| invalid)?;
+ // SAFETY: d2i advanced the cursor within `data`.
+ let consumed = unsafe { cursor.offset_from(data.as_ptr()) } as usize;
+ let input = &data[..consumed];
+
+ if *encoding(private_key_info.as_ptr(), sys::i2d_PKCS8_PRIV_KEY_INFO) != *input {
+ return Err("PrivateKeyInfo is not in DER");
+ }
+
+ // NB: OpenSSL also takes the version 1 OneAsymmetricKey of RFC 5958.
+ if !has_version_zero(input) {
+ return Err("Unsupported PrivateKeyInfo version");
+ }
+
+ let mut algorithm = ptr::null();
+ let mut private_key = ptr::null();
+ let mut private_key_size = 0;
+ // SAFETY: The structure is live, and the outputs are live locals.
+ if unsafe {
+ sys::PKCS8_pkey_get0(
+ ptr::null_mut(),
+ &raw mut private_key,
+ &raw mut private_key_size,
+ &raw mut algorithm,
+ private_key_info.as_ptr(),
+ )
+ } != 1
+ {
+ return failed().map_err(|_| invalid);
+ }
+ let algorithm = algorithm_identifier(algorithm);
+ let private_key_size = usize::try_from(private_key_size).unwrap_or_default();
+ // SAFETY: OpenSSL gives the private key's octets, of `private_key_size` bytes, which the structure owns.
+ let raw_key = unsafe { ak::slice_from_raw_parts(private_key, private_key_size) };
+ let kind = kind_of(&algorithm.oid);
+
+ // https://www.rfc-editor.org/rfc/rfc8410#section-9
+ // For all of the OIDs, the parameters MUST be absent.
+ // https://www.rfc-editor.org/rfc/rfc9881#section-2
+ // The contents of the parameters component for each algorithm MUST be absent.
+ // NB: ML-KEM's parameters are absent likewise, and the outer encoding check above keeps whatever parameters were
+ // given.
+ if kind != KeyKind::Rsa && kind != KeyKind::Ec && algorithm.has_parameters() {
+ return Err("The algorithm takes no parameters");
+ }
+
+ // NB: The ML-DSA and ML-KEM privateKey choices are parsed after this, since OpenSSL also takes forms that Web Crypto
+ // does not, and refuses an expandedKey that is not valid before Web Crypto can reject that form.
+ let mut decoded_key = None;
+ if kind != KeyKind::MlDsa && kind != KeyKind::MlKem {
+ // SAFETY: The structure is live; a non-null result is owned.
+ let key = Pkey::new(unsafe { sys::EVP_PKCS82PKEY(private_key_info.as_ptr()) })
+ .map_err(|_| "Invalid or unsupported private key")?;
+
+ if kind == KeyKind::Rsa {
+ // https://www.rfc-editor.org/rfc/rfc3279#section-2.3.1
+ // The parameters field MUST have ASN.1 type NULL for this algorithm identifier.
+ if algorithm.parameters_type != sys::V_ASN1_NULL {
+ return Err("RSA parameters must be NULL");
+ }
+
+ // NB: OpenSSL accepts BER in the RSAPrivateKey, so it must be the key's own DER encoding.
+ if *key.private_key_structure() != *raw_key {
+ return Err("RSAPrivateKey is not in DER");
+ }
+
+ // NB: OpenSSL also takes other versions, and otherPrimeInfos even in version 0. Keys of more than two primes
+ // are not supported, as in JWK import.
+ if !has_version_zero(raw_key) {
+ return Err("Unsupported RSAPrivateKey version");
+ }
+ if key.number(c"rsa-factor3").is_some() {
+ return Err("RSA keys of more than two primes are not supported");
+ }
+ }
+ decoded_key = Some(key);
+ }
+
+ // NB: The private key is copied only once it has been checked.
+ Ok(PrivateKeyInfo {
+ algorithm,
+ raw_key: SecretBytes::new(raw_key.to_vec()),
+ consumed,
+ key: decoded_key,
+ })
+}
diff --git a/Libraries/LibCrypto/Rust/src/rsa.rs b/Libraries/LibCrypto/Rust/src/rsa.rs
new file mode 100644
index 00000000000..8d60c2fd886
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/rsa.rs
@@ -0,0 +1,444 @@
+/*
+ * Copyright (c) 2020, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2024-2025, Altomani Gianluca <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! RSA keys.
+
+use core::ffi::{CStr, c_int};
+
+use crate::key::{HandleTag, Key, KeyDecodeError, KeyHandle, KeyPair, SecretBytes, StoredKey};
+use crate::openssl::{
+ self, BigNum, ParamBuilder, Pkey, end_parameter, int_parameter, octet_string_parameter, utf8_parameter,
+};
+use crate::{CryptoError, KeyAlgorithm, RsaJwkInteger, ShaHashKind, der, sys};
+
+pub(crate) struct RsaPublicKey {
+ key: Pkey,
+}
+
+/// A private key of only n, e and d has no CRT components.
+pub(crate) struct RsaPrivateKey {
+ key: Pkey,
+ has_crt_components: bool,
+}
+
+impl RsaJwkInteger {
+ /// The name of the key's parameter that holds the integer, as OpenSSL takes it.
+ fn name(&self) -> &'static CStr {
+ match self {
+ Self::Modulus => c"n",
+ Self::PublicExponent => c"e",
+ Self::PrivateExponent => c"d",
+ Self::Prime1 => c"rsa-factor1",
+ Self::Prime2 => c"rsa-factor2",
+ Self::Exponent1 => c"rsa-exponent1",
+ Self::Exponent2 => c"rsa-exponent2",
+ Self::Coefficient => c"rsa-coefficient1",
+ }
+ }
+}
+
+/// The integer `integer` of `key`, without leading zeros, or nothing if the key does not have it.
+fn integer(key: &Pkey, integer: RsaJwkInteger) -> Result<SecretBytes, CryptoError> {
+ match key.number(integer.name()) {
+ Some(number) => number.to_bytes(),
+ None => Ok(SecretBytes::new(Vec::new())),
+ }
+}
+
+// https://www.rfc-editor.org/rfc/rfc8017#section-3.1
+// [...] the RSA public exponent e is an integer between 3 and n - 1 [...]
+// NB: An odd e above 1 is at least 3.
+fn public_exponent_is_valid(key: &Pkey) -> bool {
+ let (Some(n), Some(e)) = (key.number(c"n"), key.number(c"e")) else {
+ return false;
+ };
+ e.is_odd() && e.num_bits() > 1 && e.is_less_than(&n)
+}
+
+impl RsaPublicKey {
+ fn from_components(modulus: &[u8], public_exponent: &[u8]) -> Result<Self, CryptoError> {
+ let mut builder = ParamBuilder::new()?;
+ builder.push_number(c"n", modulus, false)?;
+ builder.push_number(c"e", public_exponent, false)?;
+ let params = builder.build()?;
+ Ok(Self {
+ key: Pkey::from_data(c"RSA", sys::EVP_PKEY_PUBLIC_KEY, params.as_ptr())?,
+ })
+ }
+
+ fn is_valid(&self) -> Result<bool, CryptoError> {
+ if !public_exponent_is_valid(&self.key) {
+ return Ok(false);
+ }
+ Ok(openssl::check_key(&self.key, false, false)?.public)
+ }
+}
+
+impl RsaPrivateKey {
+ fn from_components(
+ modulus: &[u8],
+ public_exponent: &[u8],
+ private_exponent: &[u8],
+ crt_components: Option<[&[u8]; 5]>,
+ ) -> Result<Self, CryptoError> {
+ let mut builder = ParamBuilder::new()?;
+ builder.push_number(c"n", modulus, false)?;
+ builder.push_number(c"e", public_exponent, false)?;
+ builder.push_number(c"d", private_exponent, true)?;
+ if let Some(crt_components) = crt_components {
+ let names = [
+ RsaJwkInteger::Prime1,
+ RsaJwkInteger::Prime2,
+ RsaJwkInteger::Exponent1,
+ RsaJwkInteger::Exponent2,
+ RsaJwkInteger::Coefficient,
+ ];
+ for (integer, bytes) in names.into_iter().zip(crt_components) {
+ builder.push_number(integer.name(), bytes, true)?;
+ }
+ }
+ let params = builder.build()?;
+ Ok(Self {
+ key: Pkey::from_data(c"RSA", sys::EVP_PKEY_KEYPAIR, params.as_ptr())?,
+ has_crt_components: crt_components.is_some(),
+ })
+ }
+
+ fn from_key(key: Pkey) -> Self {
+ let has_crt_components = key.number(RsaJwkInteger::Prime1.name()).is_some();
+ Self {
+ key,
+ has_crt_components,
+ }
+ }
+
+ fn component(&self, component: RsaJwkInteger) -> Result<SecretBytes, CryptoError> {
+ let is_crt_component = !matches!(
+ component,
+ RsaJwkInteger::Modulus | RsaJwkInteger::PublicExponent | RsaJwkInteger::PrivateExponent
+ );
+ if is_crt_component && !self.has_crt_components {
+ return Ok(SecretBytes::new(Vec::new()));
+ }
+ integer(&self.key, component)
+ }
+
+ fn public_key(&self) -> Result<RsaPublicKey, CryptoError> {
+ RsaPublicKey::from_components(
+ &integer(&self.key, RsaJwkInteger::Modulus)?,
+ &integer(&self.key, RsaJwkInteger::PublicExponent)?,
+ )
+ }
+
+ fn is_valid(&self) -> Result<bool, CryptoError> {
+ if !public_exponent_is_valid(&self.key) {
+ return Ok(false);
+ }
+ // NB: The pairwise check needs the prime factors, which a key of only n, e and d does not have.
+ let checks = openssl::check_key(&self.key, true, self.has_crt_components)?;
+ Ok(checks.public && checks.private && checks.pairwise)
+ }
+}
+
+fn public_key(key: &KeyHandle) -> &RsaPublicKey {
+ match &key.0 {
+ Key::RsaPublic(public_key) => public_key,
+ _ => panic!("The key is not an RSA public key"),
+ }
+}
+
+fn private_key(key: &KeyHandle) -> &RsaPrivateKey {
+ match &key.0 {
+ Key::RsaPrivate(private_key) => private_key,
+ _ => panic!("The key is not an RSA private key"),
+ }
+}
+
+pub fn rsa_key_is_valid(key: &KeyHandle) -> Result<bool, CryptoError> {
+ match &key.0 {
+ Key::RsaPublic(public_key) => public_key.is_valid(),
+ Key::RsaPrivate(private_key) => private_key.is_valid(),
+ _ => panic!("The key is not an RSA key"),
+ }
+}
+
+pub fn rsa_validate_modulus_length(modulus_length: u32) -> bool {
+ // OpenSSL refuses to generate keys with shorter moduli, and OPENSSL_RSA_MAX_MODULUS_BITS caps them.
+ (512..=16384).contains(&modulus_length)
+}
+
+pub fn rsa_generate_key_pair(modulus_length: u32, exponent: &[u8]) -> Result<KeyPair, CryptoError> {
+ if !rsa_validate_modulus_length(modulus_length) {
+ return Err(CryptoError::Backend);
+ }
+ let mut builder = ParamBuilder::new()?;
+ builder.push_uint(c"bits", modulus_length)?;
+ builder.push_number(c"e", exponent, false)?;
+ let params = builder.build()?;
+ let private_key = RsaPrivateKey::from_key(Pkey::generate(c"RSA", Some(params.as_ptr()))?);
+ let public_key = private_key.public_key()?;
+ Ok(KeyPair {
+ public_key: KeyHandle(Key::RsaPublic(public_key)),
+ private_key: KeyHandle(Key::RsaPrivate(private_key)),
+ })
+}
+
+pub fn rsa_read_key_metadata(key: &KeyHandle) -> Result<(u32, Vec<u8>), CryptoError> {
+ let key = match &key.0 {
+ Key::RsaPublic(public_key) => &public_key.key,
+ Key::RsaPrivate(private_key) => &private_key.key,
+ _ => panic!("The key is not an RSA key"),
+ };
+ Ok((key.bits(), integer(key, RsaJwkInteger::PublicExponent)?.into_vec()))
+}
+
+pub fn rsa_key_from_components(is_private: bool, components: &[&[u8]]) -> Option<KeyHandle> {
+ if !is_private {
+ let [modulus, public_exponent] = components else {
+ return None;
+ };
+ return Some(KeyHandle(Key::RsaPublic(
+ RsaPublicKey::from_components(modulus, public_exponent).ok()?,
+ )));
+ }
+ let crt_components = match components {
+ [_, _, _] => None,
+ // NB: A JWK of a key without CRT components may carry them empty.
+ [_, _, _, crt @ ..] if crt.len() == 5 => crt
+ .iter()
+ .any(|component| !component.is_empty())
+ .then(|| [crt[0], crt[1], crt[2], crt[3], crt[4]]),
+ _ => return None,
+ };
+ let private_key =
+ RsaPrivateKey::from_components(components[0], components[1], components[2], crt_components).ok()?;
+ Some(KeyHandle(Key::RsaPrivate(private_key)))
+}
+
+// NB: OpenSSL writes a SubjectPublicKeyInfo of rsaEncryption with NULL parameters.
+pub fn rsa_export_der(key: &KeyHandle, is_public: bool) -> Result<Vec<u8>, CryptoError> {
+ if is_public {
+ return public_key(key).key.public_key_info();
+ }
+ let private_key = private_key(key);
+ if !private_key.has_crt_components {
+ return Err(CryptoError::Backend);
+ }
+ let integers = [
+ RsaJwkInteger::Modulus,
+ RsaJwkInteger::PublicExponent,
+ RsaJwkInteger::PrivateExponent,
+ RsaJwkInteger::Prime1,
+ RsaJwkInteger::Prime2,
+ RsaJwkInteger::Exponent1,
+ RsaJwkInteger::Exponent2,
+ RsaJwkInteger::Coefficient,
+ ]
+ .map(|integer| self::integer(&private_key.key, integer));
+ let integers = integers.into_iter().collect::<Result<Vec<_>, _>>()?;
+ let integers: Vec<&[u8]> = integers.iter().map(|integer| &**integer).collect();
+ let encoded = SecretBytes::new(der::rsa_private_key(&integers));
+ // https://www.rfc-editor.org/rfc/rfc3279#section-2.3.1
+ // The parameters field MUST have ASN.1 type NULL for this algorithm identifier.
+ Ok(der::private_key_info(
+ KeyAlgorithm::Rsa.oid(),
+ Some(&der::NULL),
+ &encoded,
+ ))
+}
+
+pub fn rsa_export_jwk_integer(key: &KeyHandle, component: RsaJwkInteger) -> Result<Vec<u8>, CryptoError> {
+ match &key.0 {
+ Key::RsaPublic(public_key) => match component {
+ RsaJwkInteger::Modulus | RsaJwkInteger::PublicExponent => {
+ Ok(integer(&public_key.key, component)?.into_vec())
+ }
+ _ => panic!("A public key has only n and e"),
+ },
+ Key::RsaPrivate(private_key) => Ok(private_key.component(component)?.into_vec()),
+ _ => panic!("The key is not an RSA key"),
+ }
+}
+
+pub fn rsa_oaep_cipher(
+ encrypt: bool,
+ hash_kind: ShaHashKind,
+ key: &KeyHandle,
+ label: &[u8],
+ input: &[u8],
+) -> Result<Vec<u8>, CryptoError> {
+ let mut params = vec![
+ utf8_parameter(c"pad-mode", c"oaep"),
+ utf8_parameter(c"digest", hash_kind.name()),
+ utf8_parameter(c"mgf1-digest", hash_kind.name()),
+ ];
+ // NB: OpenSSL copies the label.
+ if !label.is_empty() {
+ params.push(octet_string_parameter(c"oaep-label", label));
+ }
+ params.push(end_parameter());
+ if encrypt {
+ return openssl::encrypt(&public_key(key).key, &params, input);
+ }
+
+ let key = &private_key(key).key;
+ if input.len() != key.size() {
+ return Err(CryptoError::Backend);
+ }
+ openssl::decrypt(key, &params, input)
+}
+
+/// The padding of an RSA signature.
+#[derive(Clone, Copy)]
+pub enum RsaSignaturePadding {
+ Pkcs1,
+ Pss { salt_length: u32 },
+}
+
+impl RsaSignaturePadding {
+ // NB: OpenSSL takes the salt length as an int and gives negative values special meanings, such as salt length
+ // auto-detection, so a length that does not fit in an int must never reach it. No RSA key is large enough for
+ // such a salt.
+ fn pss_salt_length(self) -> Result<Option<c_int>, ()> {
+ match self {
+ Self::Pkcs1 => Ok(None),
+ Self::Pss { salt_length } => c_int::try_from(salt_length).map(Some).map_err(|_| ()),
+ }
+ }
+}
+
+/// The signature parameters of the padding, which point at `salt_length`.
+fn signature_parameters(hash_kind: ShaHashKind, salt_length: Option<&mut c_int>) -> Vec<sys::OSSL_PARAM> {
+ match salt_length {
+ Some(salt_length) => vec![
+ utf8_parameter(c"pad-mode", c"pss"),
+ utf8_parameter(c"mgf1-digest", hash_kind.name()),
+ int_parameter(c"saltlen", salt_length),
+ end_parameter(),
+ ],
+ None => vec![utf8_parameter(c"pad-mode", c"pkcs1"), end_parameter()],
+ }
+}
+
+pub fn rsa_sign(
+ hash_kind: ShaHashKind,
+ key: &KeyHandle,
+ padding: RsaSignaturePadding,
+ message: &[u8],
+) -> Result<Vec<u8>, CryptoError> {
+ let mut salt_length = padding.pss_salt_length().map_err(|_| CryptoError::Backend)?;
+ let params = signature_parameters(hash_kind, salt_length.as_mut());
+ openssl::digest_sign(&private_key(key).key, Some(hash_kind.name()), &params, message)
+}
+
+pub fn rsa_verify(
+ hash_kind: ShaHashKind,
+ key: &KeyHandle,
+ padding: RsaSignaturePadding,
+ message: &[u8],
+ signature: &[u8],
+) -> Result<bool, CryptoError> {
+ let Ok(mut salt_length) = padding.pss_salt_length() else {
+ return Ok(false);
+ };
+ let public_key = public_key(key);
+ if signature.len() != public_key.key.size() {
+ return Ok(false);
+ }
+ // NB: Keys are checked in full when they are imported, so this only keeps the rule on e, which is cheap.
+ if !public_exponent_is_valid(&public_key.key) {
+ return Ok(false);
+ }
+ let params = signature_parameters(hash_kind, salt_length.as_mut());
+ openssl::digest_verify(&public_key.key, Some(hash_kind.name()), &params, message, signature)
+}
+
+/// Whether the big-endian `exponent` is at least 3, is odd, and is less than 2^modulus_length - 1.
+pub fn rsa_validate_public_exponent(exponent: &[u8], modulus_length: u32) -> bool {
+ let Ok(exponent) = BigNum::from_bytes(exponent, false) else {
+ return false;
+ };
+ if !exponent.is_odd() || exponent.num_bits() < 2 {
+ return false;
+ }
+ // NB: exponent < 2^modulus_length - 1 exactly when exponent + 1 has at most modulus_length bits.
+ exponent
+ .incremented()
+ .is_ok_and(|incremented| u32::try_from(incremented.num_bits()).is_ok_and(|bits| bits <= modulus_length))
+}
+
+/// The big-endian `exponent` with no leading zero bytes.
+pub fn rsa_export_public_exponent(exponent: &[u8]) -> Vec<u8> {
+ let leading_zeros = exponent.iter().take_while(|&&byte| byte == 0).count();
+ exponent[leading_zeros..].to_vec()
+}
+
+pub(crate) fn public_key_for_private_key(key: &KeyHandle) -> Option<KeyHandle> {
+ let Key::RsaPrivate(private_key) = &key.0 else {
+ return None;
+ };
+ Some(KeyHandle(Key::RsaPublic(private_key.public_key().ok()?)))
+}
+
+pub(crate) fn from_public_key(key: Pkey) -> KeyHandle {
+ KeyHandle(Key::RsaPublic(RsaPublicKey { key }))
+}
+
+pub(crate) fn from_private_key(key: Pkey) -> KeyHandle {
+ KeyHandle(Key::RsaPrivate(RsaPrivateKey::from_key(key)))
+}
+
+impl RsaPublicKey {
+ /// The stored form of the key: n and e.
+ pub(crate) fn stored(&self) -> StoredKey {
+ let integer = |component| integer(&self.key, component).expect("OpenSSL gives an RSA key's components");
+ StoredKey::new(
+ HandleTag::RsaPublic,
+ vec![integer(RsaJwkInteger::Modulus), integer(RsaJwkInteger::PublicExponent)],
+ )
+ }
+}
+
+impl RsaPrivateKey {
+ /// The stored form of the key: n, d, e and then its CRT components, which a key without them stores empty.
+ pub(crate) fn stored(&self) -> StoredKey {
+ let buffers = [
+ RsaJwkInteger::Modulus,
+ RsaJwkInteger::PrivateExponent,
+ RsaJwkInteger::PublicExponent,
+ RsaJwkInteger::Prime1,
+ RsaJwkInteger::Prime2,
+ RsaJwkInteger::Exponent1,
+ RsaJwkInteger::Exponent2,
+ RsaJwkInteger::Coefficient,
+ ]
+ .into_iter()
+ .map(|integer| self.component(integer).expect("OpenSSL gives an RSA key's components"))
+ .collect();
+ StoredKey::new(HandleTag::RsaPrivate, buffers)
+ }
+}
+
+/// The key that a stored handle of an RSA tag holds.
+pub(crate) fn decode_stored(tag: HandleTag, buffers: &[&[u8]]) -> Result<KeyHandle, KeyDecodeError> {
+ let invalid = |_| KeyDecodeError::InvalidComponents;
+ match tag {
+ HandleTag::RsaPublic => Ok(KeyHandle(Key::RsaPublic(
+ RsaPublicKey::from_components(buffers[0], buffers[1]).map_err(invalid)?,
+ ))),
+ HandleTag::RsaPrivate => {
+ // NB: A key without CRT components stores them empty.
+ let crt_components =
+ (!buffers[3].is_empty()).then(|| [buffers[3], buffers[4], buffers[5], buffers[6], buffers[7]]);
+ let private_key =
+ RsaPrivateKey::from_components(buffers[0], buffers[2], buffers[1], crt_components).map_err(invalid)?;
+ Ok(KeyHandle(Key::RsaPrivate(private_key)))
+ }
+ _ => Err(KeyDecodeError::InvalidComponents),
+ }
+}
diff --git a/Libraries/LibCrypto/Rust/src/sys.rs b/Libraries/LibCrypto/Rust/src/sys.rs
new file mode 100644
index 00000000000..6a9f416d0db
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/sys.rs
@@ -0,0 +1,451 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The OpenSSL 3 functions that libcrypto_rust calls. The libraries that link the crate link OpenSSL.
+
+#![allow(non_camel_case_types, clippy::upper_case_acronyms)]
+
+use core::ffi::{c_char, c_int, c_long, c_uint, c_void};
+
+macro_rules! opaque_types {
+ ($($name:ident),* $(,)?) => {
+ $(
+ #[repr(C)]
+ pub(crate) struct $name {
+ _private: [u8; 0],
+ }
+ )*
+ };
+}
+
+opaque_types!(
+ ASN1_OBJECT,
+ BIGNUM,
+ BN_CTX,
+ ECDSA_SIG,
+ EC_GROUP,
+ EC_POINT,
+ EVP_CIPHER,
+ EVP_CIPHER_CTX,
+ EVP_KDF,
+ EVP_KDF_CTX,
+ EVP_MAC,
+ EVP_MAC_CTX,
+ EVP_MD,
+ EVP_MD_CTX,
+ EVP_PKEY,
+ EVP_PKEY_CTX,
+ EVP_SIGNATURE,
+ OSSL_LIB_CTX,
+ OSSL_PARAM_BLD,
+ PKCS8_PRIV_KEY_INFO,
+ X509_ALGOR,
+ X509_PUBKEY,
+);
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub(crate) struct OSSL_PARAM {
+ key: *const c_char,
+ data_type: c_uint,
+ data: *mut c_void,
+ data_size: usize,
+ return_size: usize,
+}
+
+pub(crate) const EVP_PKEY_PUBLIC_KEY: c_int = 0x86;
+pub(crate) const EVP_PKEY_KEYPAIR: c_int = 0x87;
+
+pub(crate) const EVP_CIPHER_CTX_FLAG_WRAP_ALLOW: c_int = 0x1;
+pub(crate) const EVP_CTRL_AEAD_SET_IVLEN: c_int = 0x9;
+pub(crate) const EVP_CTRL_AEAD_GET_TAG: c_int = 0x10;
+pub(crate) const EVP_CTRL_AEAD_SET_TAG: c_int = 0x11;
+
+pub(crate) const V_ASN1_UNDEF: c_int = -1;
+pub(crate) const V_ASN1_NULL: c_int = 5;
+pub(crate) const V_ASN1_OBJECT: c_int = 6;
+
+pub(crate) const NID_X9_62_PRIME256V1: c_int = 415;
+pub(crate) const NID_SECP384R1: c_int = 715;
+pub(crate) const NID_SECP521R1: c_int = 716;
+
+pub(crate) const POINT_CONVERSION_UNCOMPRESSED: c_int = 4;
+
+unsafe extern "C" {
+ pub(crate) fn ERR_clear_error();
+ pub(crate) fn RAND_bytes(buffer: *mut u8, length: c_int) -> c_int;
+
+ pub(crate) fn OSSL_PARAM_construct_octet_string(key: *const c_char, buffer: *mut c_void, size: usize)
+ -> OSSL_PARAM;
+ pub(crate) fn OSSL_PARAM_construct_utf8_string(key: *const c_char, buffer: *mut c_char, size: usize) -> OSSL_PARAM;
+ pub(crate) fn OSSL_PARAM_construct_uint(key: *const c_char, buffer: *mut c_uint) -> OSSL_PARAM;
+ pub(crate) fn OSSL_PARAM_construct_int(key: *const c_char, buffer: *mut c_int) -> OSSL_PARAM;
+ pub(crate) fn OSSL_PARAM_construct_end() -> OSSL_PARAM;
+ pub(crate) fn OSSL_PARAM_BLD_new() -> *mut OSSL_PARAM_BLD;
+ pub(crate) fn OSSL_PARAM_BLD_free(builder: *mut OSSL_PARAM_BLD);
+ pub(crate) fn OSSL_PARAM_BLD_push_BN(
+ builder: *mut OSSL_PARAM_BLD,
+ key: *const c_char,
+ value: *const BIGNUM,
+ ) -> c_int;
+ pub(crate) fn OSSL_PARAM_BLD_push_utf8_string(
+ builder: *mut OSSL_PARAM_BLD,
+ key: *const c_char,
+ value: *const c_char,
+ size: usize,
+ ) -> c_int;
+ pub(crate) fn OSSL_PARAM_BLD_push_octet_string(
+ builder: *mut OSSL_PARAM_BLD,
+ key: *const c_char,
+ value: *const c_void,
+ size: usize,
+ ) -> c_int;
+ pub(crate) fn OSSL_PARAM_BLD_push_uint(builder: *mut OSSL_PARAM_BLD, key: *const c_char, value: c_uint) -> c_int;
+ pub(crate) fn OSSL_PARAM_BLD_to_param(builder: *mut OSSL_PARAM_BLD) -> *mut OSSL_PARAM;
+ pub(crate) fn OSSL_PARAM_free(params: *mut OSSL_PARAM);
+
+ pub(crate) fn BN_new() -> *mut BIGNUM;
+ pub(crate) fn BN_secure_new() -> *mut BIGNUM;
+ pub(crate) fn BN_clear_free(number: *mut BIGNUM);
+ pub(crate) fn BN_bin2bn(bytes: *const u8, length: c_int, number: *mut BIGNUM) -> *mut BIGNUM;
+ pub(crate) fn BN_bn2binpad(number: *const BIGNUM, bytes: *mut u8, length: c_int) -> c_int;
+ pub(crate) fn BN_num_bits(number: *const BIGNUM) -> c_int;
+ pub(crate) fn BN_is_odd(number: *const BIGNUM) -> c_int;
+ pub(crate) fn BN_cmp(left: *const BIGNUM, right: *const BIGNUM) -> c_int;
+ pub(crate) fn BN_add(result: *mut BIGNUM, left: *const BIGNUM, right: *const BIGNUM) -> c_int;
+ pub(crate) fn BN_value_one() -> *const BIGNUM;
+ pub(crate) fn BN_CTX_new() -> *mut BN_CTX;
+ pub(crate) fn BN_CTX_free(context: *mut BN_CTX);
+
+ pub(crate) fn EC_GROUP_new_by_curve_name(nid: c_int) -> *mut EC_GROUP;
+ pub(crate) fn EC_GROUP_free(group: *mut EC_GROUP);
+ pub(crate) fn EC_GROUP_get0_order(group: *const EC_GROUP) -> *const BIGNUM;
+ pub(crate) fn EC_POINT_new(group: *const EC_GROUP) -> *mut EC_POINT;
+ pub(crate) fn EC_POINT_free(point: *mut EC_POINT);
+ pub(crate) fn EC_POINT_mul(
+ group: *const EC_GROUP,
+ result: *mut EC_POINT,
+ generator_scalar: *const BIGNUM,
+ point: *const EC_POINT,
+ point_scalar: *const BIGNUM,
+ context: *mut BN_CTX,
+ ) -> c_int;
+ pub(crate) fn EC_POINT_point2oct(
+ group: *const EC_GROUP,
+ point: *const EC_POINT,
+ form: c_int,
+ buffer: *mut u8,
+ length: usize,
+ context: *mut BN_CTX,
+ ) -> usize;
+ pub(crate) fn ECDSA_SIG_new() -> *mut ECDSA_SIG;
+ pub(crate) fn ECDSA_SIG_free(signature: *mut ECDSA_SIG);
+ pub(crate) fn ECDSA_SIG_set0(signature: *mut ECDSA_SIG, r: *mut BIGNUM, s: *mut BIGNUM) -> c_int;
+ pub(crate) fn ECDSA_SIG_get0(signature: *const ECDSA_SIG, r: *mut *const BIGNUM, s: *mut *const BIGNUM);
+ pub(crate) fn d2i_ECDSA_SIG(
+ signature: *mut *mut ECDSA_SIG,
+ input: *mut *const u8,
+ length: c_long,
+ ) -> *mut ECDSA_SIG;
+ pub(crate) fn i2d_ECDSA_SIG(signature: *const ECDSA_SIG, output: *mut *mut u8) -> c_int;
+
+ pub(crate) fn EVP_Q_digest(
+ library_context: *mut OSSL_LIB_CTX,
+ name: *const c_char,
+ properties: *const c_char,
+ data: *const c_void,
+ data_length: usize,
+ digest: *mut u8,
+ digest_length: *mut usize,
+ ) -> c_int;
+ pub(crate) fn EVP_MD_fetch(
+ library_context: *mut OSSL_LIB_CTX,
+ name: *const c_char,
+ properties: *const c_char,
+ ) -> *mut EVP_MD;
+ pub(crate) fn EVP_MD_free(digest: *mut EVP_MD);
+ pub(crate) fn EVP_MD_CTX_new() -> *mut EVP_MD_CTX;
+ pub(crate) fn EVP_MD_CTX_free(context: *mut EVP_MD_CTX);
+ pub(crate) fn EVP_DigestInit_ex(context: *mut EVP_MD_CTX, digest: *const EVP_MD, engine: *mut c_void) -> c_int;
+ pub(crate) fn EVP_DigestUpdate(context: *mut EVP_MD_CTX, data: *const c_void, length: usize) -> c_int;
+ pub(crate) fn EVP_DigestFinalXOF(context: *mut EVP_MD_CTX, output: *mut u8, length: usize) -> c_int;
+ pub(crate) fn EVP_DigestSignInit_ex(
+ context: *mut EVP_MD_CTX,
+ key_context: *mut *mut EVP_PKEY_CTX,
+ digest_name: *const c_char,
+ library_context: *mut OSSL_LIB_CTX,
+ properties: *const c_char,
+ key: *mut EVP_PKEY,
+ params: *const OSSL_PARAM,
+ ) -> c_int;
+ pub(crate) fn EVP_DigestVerifyInit_ex(
+ context: *mut EVP_MD_CTX,
+ key_context: *mut *mut EVP_PKEY_CTX,
+ digest_name: *const c_char,
+ library_context: *mut OSSL_LIB_CTX,
+ properties: *const c_char,
+ key: *mut EVP_PKEY,
+ params: *const OSSL_PARAM,
+ ) -> c_int;
+ pub(crate) fn EVP_DigestSign(
+ context: *mut EVP_MD_CTX,
+ signature: *mut u8,
+ signature_length: *mut usize,
+ data: *const u8,
+ data_length: usize,
+ ) -> c_int;
+ pub(crate) fn EVP_DigestVerify(
+ context: *mut EVP_MD_CTX,
+ signature: *const u8,
+ signature_length: usize,
+ data: *const u8,
+ data_length: usize,
+ ) -> c_int;
+
+ pub(crate) fn EVP_KDF_fetch(
+ library_context: *mut OSSL_LIB_CTX,
+ name: *const c_char,
+ properties: *const c_char,
+ ) -> *mut EVP_KDF;
+ pub(crate) fn EVP_KDF_free(kdf: *mut EVP_KDF);
+ pub(crate) fn EVP_KDF_CTX_new(kdf: *mut EVP_KDF) -> *mut EVP_KDF_CTX;
+ pub(crate) fn EVP_KDF_CTX_free(context: *mut EVP_KDF_CTX);
+ pub(crate) fn EVP_KDF_derive(
+ context: *mut EVP_KDF_CTX,
+ key: *mut u8,
+ key_length: usize,
+ params: *const OSSL_PARAM,
+ ) -> c_int;
+ pub(crate) fn EVP_MAC_fetch(
+ library_context: *mut OSSL_LIB_CTX,
+ name: *const c_char,
+ properties: *const c_char,
+ ) -> *mut EVP_MAC;
+ pub(crate) fn EVP_MAC_free(mac: *mut EVP_MAC);
+ pub(crate) fn EVP_MAC_CTX_new(mac: *mut EVP_MAC) -> *mut EVP_MAC_CTX;
+ pub(crate) fn EVP_MAC_CTX_free(context: *mut EVP_MAC_CTX);
+ pub(crate) fn EVP_MAC_init(
+ context: *mut EVP_MAC_CTX,
+ key: *const u8,
+ key_length: usize,
+ params: *const OSSL_PARAM,
+ ) -> c_int;
+ pub(crate) fn EVP_MAC_update(context: *mut EVP_MAC_CTX, data: *const u8, length: usize) -> c_int;
+ pub(crate) fn EVP_MAC_final(
+ context: *mut EVP_MAC_CTX,
+ output: *mut u8,
+ output_length: *mut usize,
+ output_size: usize,
+ ) -> c_int;
+
+ pub(crate) fn EVP_CIPHER_CTX_new() -> *mut EVP_CIPHER_CTX;
+ pub(crate) fn EVP_CIPHER_CTX_free(context: *mut EVP_CIPHER_CTX);
+ pub(crate) fn EVP_CipherInit_ex(
+ context: *mut EVP_CIPHER_CTX,
+ cipher: *const EVP_CIPHER,
+ engine: *mut c_void,
+ key: *const u8,
+ iv: *const u8,
+ encrypt: c_int,
+ ) -> c_int;
+ pub(crate) fn EVP_CipherUpdate(
+ context: *mut EVP_CIPHER_CTX,
+ output: *mut u8,
+ output_length: *mut c_int,
+ input: *const u8,
+ input_length: c_int,
+ ) -> c_int;
+ pub(crate) fn EVP_CipherFinal_ex(context: *mut EVP_CIPHER_CTX, output: *mut u8, output_length: *mut c_int)
+ -> c_int;
+ pub(crate) fn EVP_CIPHER_CTX_ctrl(
+ context: *mut EVP_CIPHER_CTX,
+ kind: c_int,
+ argument: c_int,
+ pointer: *mut c_void,
+ ) -> c_int;
+ pub(crate) fn EVP_CIPHER_CTX_set_flags(context: *mut EVP_CIPHER_CTX, flags: c_int);
+ pub(crate) fn EVP_aes_128_cbc() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_192_cbc() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_256_cbc() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_128_ctr() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_192_ctr() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_256_ctr() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_128_gcm() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_192_gcm() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_256_gcm() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_128_ocb() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_192_ocb() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_256_ocb() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_128_wrap() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_192_wrap() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_aes_256_wrap() -> *const EVP_CIPHER;
+ pub(crate) fn EVP_chacha20_poly1305() -> *const EVP_CIPHER;
+
+ pub(crate) fn EVP_PKEY_free(key: *mut EVP_PKEY);
+ pub(crate) fn EVP_PKEY_up_ref(key: *mut EVP_PKEY) -> c_int;
+ pub(crate) fn EVP_PKEY_CTX_new_from_name(
+ library_context: *mut OSSL_LIB_CTX,
+ name: *const c_char,
+ properties: *const c_char,
+ ) -> *mut EVP_PKEY_CTX;
+ pub(crate) fn EVP_PKEY_CTX_new_from_pkey(
+ library_context: *mut OSSL_LIB_CTX,
+ key: *mut EVP_PKEY,
+ properties: *const c_char,
+ ) -> *mut EVP_PKEY_CTX;
+ pub(crate) fn EVP_PKEY_CTX_free(context: *mut EVP_PKEY_CTX);
+ pub(crate) fn EVP_PKEY_CTX_set_params(context: *mut EVP_PKEY_CTX, params: *const OSSL_PARAM) -> c_int;
+ pub(crate) fn EVP_PKEY_fromdata_init(context: *mut EVP_PKEY_CTX) -> c_int;
+ pub(crate) fn EVP_PKEY_fromdata(
+ context: *mut EVP_PKEY_CTX,
+ key: *mut *mut EVP_PKEY,
+ selection: c_int,
+ params: *mut OSSL_PARAM,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_keygen_init(context: *mut EVP_PKEY_CTX) -> c_int;
+ pub(crate) fn EVP_PKEY_generate(context: *mut EVP_PKEY_CTX, key: *mut *mut EVP_PKEY) -> c_int;
+ pub(crate) fn EVP_PKEY_get_bn_param(key: *const EVP_PKEY, name: *const c_char, number: *mut *mut BIGNUM) -> c_int;
+ pub(crate) fn EVP_PKEY_get_octet_string_param(
+ key: *const EVP_PKEY,
+ name: *const c_char,
+ buffer: *mut u8,
+ size: usize,
+ length: *mut usize,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_get_raw_public_key(key: *const EVP_PKEY, buffer: *mut u8, length: *mut usize) -> c_int;
+ pub(crate) fn EVP_PKEY_get_raw_private_key(key: *const EVP_PKEY, buffer: *mut u8, length: *mut usize) -> c_int;
+ pub(crate) fn EVP_PKEY_new_raw_public_key_ex(
+ library_context: *mut OSSL_LIB_CTX,
+ key_type: *const c_char,
+ properties: *const c_char,
+ bytes: *const u8,
+ length: usize,
+ ) -> *mut EVP_PKEY;
+ pub(crate) fn EVP_PKEY_new_raw_private_key_ex(
+ library_context: *mut OSSL_LIB_CTX,
+ key_type: *const c_char,
+ properties: *const c_char,
+ bytes: *const u8,
+ length: usize,
+ ) -> *mut EVP_PKEY;
+ pub(crate) fn EVP_PKEY_get_size(key: *const EVP_PKEY) -> c_int;
+ pub(crate) fn EVP_PKEY_get_bits(key: *const EVP_PKEY) -> c_int;
+ pub(crate) fn EVP_PKEY_public_check(context: *mut EVP_PKEY_CTX) -> c_int;
+ pub(crate) fn EVP_PKEY_private_check(context: *mut EVP_PKEY_CTX) -> c_int;
+ pub(crate) fn EVP_PKEY_pairwise_check(context: *mut EVP_PKEY_CTX) -> c_int;
+ pub(crate) fn EVP_PKEY_sign_init(context: *mut EVP_PKEY_CTX) -> c_int;
+ pub(crate) fn EVP_PKEY_sign(
+ context: *mut EVP_PKEY_CTX,
+ signature: *mut u8,
+ signature_length: *mut usize,
+ data: *const u8,
+ data_length: usize,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_verify_init(context: *mut EVP_PKEY_CTX) -> c_int;
+ pub(crate) fn EVP_PKEY_verify(
+ context: *mut EVP_PKEY_CTX,
+ signature: *const u8,
+ signature_length: usize,
+ data: *const u8,
+ data_length: usize,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_encrypt_init_ex(context: *mut EVP_PKEY_CTX, params: *const OSSL_PARAM) -> c_int;
+ pub(crate) fn EVP_PKEY_encrypt(
+ context: *mut EVP_PKEY_CTX,
+ output: *mut u8,
+ output_length: *mut usize,
+ input: *const u8,
+ input_length: usize,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_decrypt_init_ex(context: *mut EVP_PKEY_CTX, params: *const OSSL_PARAM) -> c_int;
+ pub(crate) fn EVP_PKEY_decrypt(
+ context: *mut EVP_PKEY_CTX,
+ output: *mut u8,
+ output_length: *mut usize,
+ input: *const u8,
+ input_length: usize,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_derive_init(context: *mut EVP_PKEY_CTX) -> c_int;
+ pub(crate) fn EVP_PKEY_derive_set_peer_ex(
+ context: *mut EVP_PKEY_CTX,
+ peer: *mut EVP_PKEY,
+ validate: c_int,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_derive(context: *mut EVP_PKEY_CTX, key: *mut u8, key_length: *mut usize) -> c_int;
+ pub(crate) fn EVP_SIGNATURE_fetch(
+ library_context: *mut OSSL_LIB_CTX,
+ name: *const c_char,
+ properties: *const c_char,
+ ) -> *mut EVP_SIGNATURE;
+ pub(crate) fn EVP_SIGNATURE_free(signature: *mut EVP_SIGNATURE);
+ pub(crate) fn EVP_PKEY_sign_message_init(
+ context: *mut EVP_PKEY_CTX,
+ algorithm: *mut EVP_SIGNATURE,
+ params: *const OSSL_PARAM,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_verify_message_init(
+ context: *mut EVP_PKEY_CTX,
+ algorithm: *mut EVP_SIGNATURE,
+ params: *const OSSL_PARAM,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_encapsulate_init(context: *mut EVP_PKEY_CTX, params: *const OSSL_PARAM) -> c_int;
+ pub(crate) fn EVP_PKEY_encapsulate(
+ context: *mut EVP_PKEY_CTX,
+ ciphertext: *mut u8,
+ ciphertext_length: *mut usize,
+ shared_key: *mut u8,
+ shared_key_length: *mut usize,
+ ) -> c_int;
+ pub(crate) fn EVP_PKEY_decapsulate_init(context: *mut EVP_PKEY_CTX, params: *const OSSL_PARAM) -> c_int;
+ pub(crate) fn EVP_PKEY_decapsulate(
+ context: *mut EVP_PKEY_CTX,
+ shared_key: *mut u8,
+ shared_key_length: *mut usize,
+ ciphertext: *const u8,
+ ciphertext_length: usize,
+ ) -> c_int;
+
+ pub(crate) fn i2d_PUBKEY(key: *const EVP_PKEY, output: *mut *mut u8) -> c_int;
+ pub(crate) fn i2d_PrivateKey(key: *const EVP_PKEY, output: *mut *mut u8) -> c_int;
+ pub(crate) fn EVP_PKCS82PKEY(private_key_info: *const PKCS8_PRIV_KEY_INFO) -> *mut EVP_PKEY;
+ pub(crate) fn d2i_PKCS8_PRIV_KEY_INFO(
+ private_key_info: *mut *mut PKCS8_PRIV_KEY_INFO,
+ input: *mut *const u8,
+ length: c_long,
+ ) -> *mut PKCS8_PRIV_KEY_INFO;
+ pub(crate) fn i2d_PKCS8_PRIV_KEY_INFO(private_key_info: *const PKCS8_PRIV_KEY_INFO, output: *mut *mut u8) -> c_int;
+ pub(crate) fn PKCS8_PRIV_KEY_INFO_free(private_key_info: *mut PKCS8_PRIV_KEY_INFO);
+ pub(crate) fn PKCS8_pkey_get0(
+ algorithm_object: *mut *const ASN1_OBJECT,
+ key: *mut *const u8,
+ key_length: *mut c_int,
+ algorithm: *mut *const X509_ALGOR,
+ private_key_info: *const PKCS8_PRIV_KEY_INFO,
+ ) -> c_int;
+ pub(crate) fn d2i_X509_PUBKEY(
+ public_key: *mut *mut X509_PUBKEY,
+ input: *mut *const u8,
+ length: c_long,
+ ) -> *mut X509_PUBKEY;
+ pub(crate) fn i2d_X509_PUBKEY(public_key: *const X509_PUBKEY, output: *mut *mut u8) -> c_int;
+ pub(crate) fn X509_PUBKEY_free(public_key: *mut X509_PUBKEY);
+ pub(crate) fn X509_PUBKEY_get0_param(
+ algorithm_object: *mut *mut ASN1_OBJECT,
+ key: *mut *const u8,
+ key_length: *mut c_int,
+ algorithm: *mut *mut X509_ALGOR,
+ public_key: *const X509_PUBKEY,
+ ) -> c_int;
+ pub(crate) fn X509_PUBKEY_get(public_key: *const X509_PUBKEY) -> *mut EVP_PKEY;
+ pub(crate) fn X509_ALGOR_get0(
+ object: *mut *const ASN1_OBJECT,
+ parameters_type: *mut c_int,
+ parameters: *mut *const c_void,
+ algorithm: *const X509_ALGOR,
+ );
+ pub(crate) fn OBJ_length(object: *const ASN1_OBJECT) -> usize;
+ pub(crate) fn OBJ_get0_data(object: *const ASN1_OBJECT) -> *const u8;
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rs
index b433d414fc8..7a21cb766ed 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rs
@@ -118,9 +118,17 @@ impl Crypto {
// https://w3c.github.io/webcrypto/#dfn-generate-a-random-uuid
fn generate_random_uuid() -> Utf16String {
// 1. Let bytes be a byte sequence of length 16.
+ let mut bytes = [0u8; 16];
+
// 2. Fill bytes with cryptographically secure random bytes.
+ libcrypto_rust::fill_with_random(&mut bytes);
+
// 3. Set the 4 most significant bits of bytes[6], which represent the UUID version, to 0100.
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
+
// 4. Set the 2 most significant bits of bytes[8], which represent the UUID variant, to 10.
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
+
// 5. Return the string concatenation of «
// hexadecimal representation of bytes[0], hexadecimal representation of bytes[1], hexadecimal representation of
// bytes[2], hexadecimal representation of bytes[3],
@@ -135,8 +143,16 @@ fn generate_random_uuid() -> Utf16String {
// of bytes[12], hexadecimal representation of bytes[13], hexadecimal representation of bytes[14], hexadecimal
// representation of bytes[15]
// ».
- // NB: The native service performs these steps.
- libcrypto_rust::generate_random_uuid()
+ const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";
+ let mut uuid = Vec::with_capacity(36);
+ for (index, byte) in bytes.into_iter().enumerate() {
+ if matches!(index, 4 | 6 | 8 | 10) {
+ uuid.push(b'-');
+ }
+ uuid.push(HEX_DIGITS[usize::from(byte >> 4)]);
+ uuid.push(HEX_DIGITS[usize::from(byte & 0x0f)]);
+ }
+ Utf16String::from_ascii(&uuid)
}
/// # Safety
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index 91891d05259..016f277231d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -14,8 +14,8 @@ use std::rc::Rc;
use ak::{Utf16String, Utf16StringUnits};
use libcrypto_rust::{
- Argon2Inputs, Argon2Type, Asn1Structure, Asn1Value, BackendError, CShakeKind, EcCurve, KeyHandle, KeyInfo, KeyPair,
- KmacKind, MlDsaSize, MlKemSize, OkpCurve, RsaJwkInteger, ShaHashKind,
+ Argon2Inputs, Argon2Type, CShakeKind, CryptoError, EcCurve, KeyAlgorithm, KeyHandle, KeyInfo, KeyPair, KmacKind,
+ MlDsaSize, MlKemSize, OkpCurve, RsaJwkInteger, RsaSignaturePadding, ShaHashKind,
};
use libjs_rust::api::{
ErrorKind, ErrorType, Gc, Object, PropertyKey, Realm, Trace, TypedArrayBase, TypedArrayKind, Value, Vm,
@@ -109,27 +109,20 @@ fn base64_url_bytes_encode(bytes: &[u8]) -> Utf16String {
}
// https://w3c.github.io/webcrypto/#concept-parse-an-asn1-structure
-fn parse_an_asn1_structure(
- data: &[u8],
- structure: Asn1Structure,
+// NB: The structure is given as its parser, whose errors are reported with `error_format`.
+fn parse_an_asn1_structure<'a, T>(
+ data: &'a [u8],
+ structure: impl FnOnce(&'a [u8]) -> Result<(T, bool), CryptoError>,
+ error_format: &str,
exact_data: bool,
-) -> Result<Asn1Value<'_>, Utf16String> {
+) -> Result<T, Utf16String> {
// 1. Let data be a sequence of bytes to be parsed.
// 2. Let structure be the ASN.1 structure to be parsed.
// 3. Let exactData be an optional boolean value. If it is not supplied, let it be initialized to true.
// 4. Parse data according to the Distinguished Encoding Rules of [X690], using structure as the ASN.1 structure to be decoded.
- let parsed = libcrypto_rust::decode_asn1_structure(data, structure);
- if let Err(detail) = parsed {
- let message = match structure {
- Asn1Structure::SubjectPublicKeyInfo => "Error parsing subjectPublicKeyInfo: {}",
- Asn1Structure::PrivateKeyInfo => "Error parsing privateKeyInfo: {}",
- Asn1Structure::OctetString => "Read of kind OctetString failed: {}",
- };
- return Err(libjs_rust::api::utf16_formatted(message, &[&detail]));
- }
-
- let (value, all_consumed) = parsed.expect("the ASN.1 structure was parsed");
+ let (value, all_consumed) =
+ structure(data).map_err(|detail| libjs_rust::api::utf16_formatted(error_format, &[&detail.message()]))?;
// 5. If exactData was specified, and all of the bytes of data were not consumed during the parsing phase, then throw a DataError.
if exact_data && !all_consumed {
@@ -143,25 +136,31 @@ fn parse_an_asn1_structure(
}
// https://w3c.github.io/webcrypto/#concept-parse-a-spki
-fn parse_a_subject_public_key_info(data: &[u8]) -> Result<KeyInfo, Utf16String> {
+fn parse_a_subject_public_key_info(data: &[u8]) -> WebIdlResult<KeyInfo> {
// When this specification says to parse a subjectPublicKeyInfo, the user agent must parse an ASN.1 structure,
// with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of subjectPublicKeyInfo,
// as specified in [RFC5280], and exactData set to true.
- let Asn1Value::KeyInfo(key_info) = parse_an_asn1_structure(data, Asn1Structure::SubjectPublicKeyInfo, true)? else {
- unreachable!("the ASN.1 structure is key info")
- };
- Ok(key_info)
+ parse_an_asn1_structure(
+ data,
+ libcrypto_rust::parse_subject_public_key_info,
+ "Error parsing subjectPublicKeyInfo: {}",
+ true,
+ )
+ .map_err(|message| Exception::Dom("DataError", message))
}
// https://w3c.github.io/webcrypto/#concept-parse-a-privateKeyInfo
-fn parse_a_private_key_info(data: &[u8]) -> Result<KeyInfo, Utf16String> {
+fn parse_a_private_key_info(data: &[u8]) -> WebIdlResult<KeyInfo> {
// When this specification says to parse a PrivateKeyInfo, the user agent must parse an ASN.1 structure
// with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of PrivateKeyInfo,
// as specified in [RFC5208], and exactData set to true.
- let Asn1Value::KeyInfo(key_info) = parse_an_asn1_structure(data, Asn1Structure::PrivateKeyInfo, true)? else {
- unreachable!("the ASN.1 structure is key info")
- };
- Ok(key_info)
+ parse_an_asn1_structure(
+ data,
+ libcrypto_rust::parse_private_key_info,
+ "Error parsing privateKeyInfo: {}",
+ true,
+ )
+ .map_err(|message| Exception::Dom("DataError", message))
}
#[derive(Clone, Trace)]
@@ -526,7 +525,7 @@ impl AlgorithmMethods for CShakeParams {
if let Err(detail) = result {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Hash function failed: {}", &[&detail]),
+ libjs_rust::api::utf16_formatted("Hash function failed: {}", &[&detail.message()]),
));
}
@@ -577,7 +576,7 @@ impl AlgorithmMethods for CShakeParams {
if let Err(detail) = result {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Hash function failed: {}", &[&detail]),
+ libjs_rust::api::utf16_formatted("Hash function failed: {}", &[&detail.message()]),
));
}
@@ -1575,11 +1574,11 @@ impl AlgorithmMethods for KmacKeyGenParams {
let length = if let Some(length) = normalized_algorithm.length {
length
} else {
- let Some(kind) = kmac_kind_from_algorithm_name(&algorithm.name) else {
- return Err(dom_error("OperationError", b"Unsupported KMAC algorithm"));
- };
-
- libcrypto_rust::kmac_default_key_length(kind)
+ match kmac_kind_from_algorithm_name(&algorithm.name) {
+ Some(KmacKind::Kmac128) => 128,
+ Some(KmacKind::Kmac256) => 256,
+ None => return Err(dom_error("OperationError", b"Unsupported KMAC algorithm")),
+ }
};
validate_kmac_key_length(length)?;
@@ -1802,11 +1801,11 @@ impl AlgorithmMethods for KmacImportParams {
// 1. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":
// 1. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":
else {
- let Some(kind) = kmac_kind_from_algorithm_name(&algorithm.name) else {
- return Err(dom_error("OperationError", b"Unsupported KMAC algorithm"));
- };
-
- libcrypto_rust::kmac_default_key_length(kind)
+ match kmac_kind_from_algorithm_name(&algorithm.name) {
+ Some(KmacKind::Kmac128) => 128,
+ Some(KmacKind::Kmac256) => 256,
+ None => return Err(dom_error("OperationError", b"Unsupported KMAC algorithm")),
+ }
};
// 2. Return length.
@@ -2442,7 +2441,7 @@ impl AlgorithmMethods for Argon2Params {
if let Err(detail) = result {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Hashing function failed: {}", &[&detail]),
+ libjs_rust::api::utf16_formatted("Hashing function failed: {}", &[&detail.message()]),
));
}
@@ -2496,7 +2495,6 @@ impl AlgorithmMethods for Argon2Params {
parallelism: normalized_algorithm.parallelism,
memory: normalized_algorithm.memory,
passes: normalized_algorithm.passes,
- version: 0x13,
secret_value: secret_value.map(Bytes::as_slice),
associated_data: associated_data.map(Bytes::as_slice),
tag_length: length.expect("validation requires a length") / 8,
@@ -2508,7 +2506,7 @@ impl AlgorithmMethods for Argon2Params {
if let Err(detail) = result {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Hashing function failed: {}", &[&detail]),
+ libjs_rust::api::utf16_formatted("Hashing function failed: {}", &[&detail.message()]),
));
}
@@ -3900,26 +3898,20 @@ impl AlgorithmMethods for AesGcm {
// Section 7.1 of [NIST-SP800-38D] using AES as the block cipher, the iv member of normalizedAlgorithm as the
// IV input parameter, additionalData as the A input parameter, tagLength as the t pre-requisite and
// plaintext as the input plaintext.
- let encrypted = libcrypto_rust::aes_gcm_encrypt(
+ // 7. Let ciphertext be equal to C | T, where '|' denotes concatenation.
+ // NB: LibCrypto gives C | T.
+ let ciphertext = libcrypto_rust::aes_gcm_cipher(
+ true,
key.byte_handle_bytes(),
plaintext.as_slice(),
normalized_algorithm.iv.as_slice(),
additional_data,
tag_length / 8,
);
- let Ok((mut ciphertext, tag)) = encrypted else {
+ let Ok(ciphertext) = ciphertext else {
return Err(dom_error("OperationError", b"Encryption failed"));
};
- // 7. Let ciphertext be equal to C | T, where '|' denotes concatenation.
- if ciphertext.try_reserve_exact(tag.len()).is_err() {
- return cx
- .vm()
- .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])
- .map_err(Into::into);
- }
- ciphertext.extend_from_slice(&tag);
-
// 8. Return ciphertext.
Ok(Bytes::new(ciphertext))
}
@@ -3972,23 +3964,8 @@ impl AlgorithmMethods for AesGcm {
}
// 5. Let tag be the last tagLength bits of ciphertext.
- let tag_bytes = tag_length / 8;
- let split = ciphertext.as_slice().len() - tag_bytes;
- let copy_bytes = |bytes: &[u8]| -> WebIdlResult<Vec<u8>> {
- let mut copy = Vec::new();
- if copy.try_reserve_exact(bytes.len()).is_err() {
- return cx
- .vm()
- .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])
- .map_err(Into::into);
- }
- copy.extend_from_slice(bytes);
- Ok(copy)
- };
- let tag = copy_bytes(&ciphertext.as_slice()[split..])?;
// 6. Let actualCiphertext be the result of removing the last tagLength bits from ciphertext.
- let actual_ciphertext = copy_bytes(&ciphertext.as_slice()[..split])?;
-
+ // NB: LibCrypto splits the tag from the ciphertext.
// 7. Let additionalData be the additionalData member of normalizedAlgorithm if present or an empty byte
// sequence otherwise.
let additional_data = normalized_algorithm
@@ -4001,12 +3978,13 @@ impl AlgorithmMethods for AesGcm {
// input parameter, tagLength as the t pre-requisite, actualCiphertext as the input ciphertext, C and tag as
// the authentication tag, T.
// If the result of the algorithm is the indication of inauthenticity, "FAIL": throw an OperationError
- let plaintext = libcrypto_rust::aes_gcm_decrypt(
+ let plaintext = libcrypto_rust::aes_gcm_cipher(
+ false,
key.byte_handle_bytes(),
- &actual_ciphertext,
+ ciphertext.as_slice(),
normalized_algorithm.iv.as_slice(),
additional_data,
- &tag,
+ tag_length / 8,
)
.map(Bytes::new);
@@ -4557,7 +4535,7 @@ impl AlgorithmMethods for AesOcb {
if let Err(detail) = ciphertext {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Encryption failed: {}", &[&detail]),
+ libjs_rust::api::utf16_formatted("Encryption failed: {}", &[&detail.message()]),
));
}
@@ -4645,7 +4623,7 @@ impl AlgorithmMethods for AesOcb {
if let Err(detail) = plaintext {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Decryption failed: {}", &[&detail]),
+ libjs_rust::api::utf16_formatted("Decryption failed: {}", &[&detail.message()]),
));
}
@@ -5051,7 +5029,7 @@ impl AlgorithmMethods for ChaCha20Poly1305 {
if let Err(detail) = ciphertext {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Encryption failed: {}", &[&detail]),
+ libjs_rust::api::utf16_formatted("Encryption failed: {}", &[&detail.message()]),
));
}
@@ -5114,7 +5092,7 @@ impl AlgorithmMethods for ChaCha20Poly1305 {
if let Err(detail) = plaintext {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Decryption failed: {}", &[&detail]),
+ libjs_rust::api::utf16_formatted("Decryption failed: {}", &[&detail.message()]),
));
}
@@ -5511,15 +5489,6 @@ impl RsaParameters {
}
}
-fn parse_key_info(data: &Bytes, structure: Asn1Structure) -> WebIdlResult<KeyInfo> {
- let parsed = match structure {
- Asn1Structure::SubjectPublicKeyInfo => parse_a_subject_public_key_info(data.as_slice()),
- Asn1Structure::PrivateKeyInfo => parse_a_private_key_info(data.as_slice()),
- Asn1Structure::OctetString => unreachable!("octet strings are not key info"),
- };
- parsed.map_err(|message| Exception::Dom("DataError", message))
-}
-
// https://w3c.github.io/webcrypto/#dfn-validate-rsa-key-generation-parameters
fn validate_rsa_key_generation_parameters(normalized_algorithm: &RsaKeyGenParams) -> WebIdlResult<()> {
// 1. Let modulusLength be the modulusLength member of normalizedAlgorithm.
@@ -5895,11 +5864,11 @@ impl AlgorithmMethods for RsaOaep {
// 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.
// 3. If an error occurred while parsing, then throw a DataError.
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let mut spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
// is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
- if !spki.has_rsa_encryption_oid() {
+ if spki.algorithm() != Some(KeyAlgorithm::Rsa) {
return Err(dom_error(
"DataError",
b"Algorithm object identifier is not the rsaEncryption object identifier",
@@ -5910,7 +5879,7 @@ impl AlgorithmMethods for RsaOaep {
// with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure
// specified in Section A.1.1 of [RFC3447], and exactData set to true.
// NOTE: We already did this in parse_a_subject_public_key_info
- let public_key = spki.rsa_key();
+ let public_key = spki.take_key();
// 6. If an error occurred while parsing, or it can be determined that publicKey is not
// a valid public key according to [RFC3447], then throw a DataError.
@@ -5946,11 +5915,11 @@ impl AlgorithmMethods for RsaOaep {
// 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.
// 3. If an error occurred while parsing, then throw a DataError.
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let mut private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo
// is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
- if !private_key_info.has_rsa_encryption_oid() {
+ if private_key_info.algorithm() != Some(KeyAlgorithm::Rsa) {
return Err(dom_error(
"DataError",
b"Algorithm object identifier is not the rsaEncryption object identifier",
@@ -5961,7 +5930,7 @@ impl AlgorithmMethods for RsaOaep {
// with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure
// specified in Section A.1.2 of [RFC3447], and exactData set to true.
// NOTE: We already did this in parse_a_private_key_info
- let rsa_private_key = private_key_info.rsa_key();
+ let rsa_private_key = private_key_info.take_key();
// 6. If an error occurred while parsing, or if rsaPrivateKey is not
// a valid RSA private key according to [RFC3447], then throw a DataError.
@@ -6497,9 +6466,15 @@ impl AlgorithmMethods for RsaPss {
};
// 4. Let signature be the signature, S, that results from performing the operation.
- let signature =
- libcrypto_rust::rsa_pss_sign(hash_kind, key.handle(), pss_params.salt_length, message.as_slice())
- .map(Bytes::new);
+ let signature = libcrypto_rust::rsa_sign(
+ hash_kind,
+ key.handle(),
+ RsaSignaturePadding::Pss {
+ salt_length: pss_params.salt_length,
+ },
+ message.as_slice(),
+ )
+ .map(Bytes::new);
if signature.is_err() {
return Err(dom_error("OperationError", b"Failed to sign message"));
}
@@ -6554,10 +6529,12 @@ impl AlgorithmMethods for RsaPss {
};
// 3. Let result be a boolean with the value true if the result of the operation was "valid signature" and the value false otherwise.
- let verified = libcrypto_rust::rsa_pss_verify(
+ let verified = libcrypto_rust::rsa_verify(
hash_kind,
key.handle(),
- pss_params.salt_length,
+ RsaSignaturePadding::Pss {
+ salt_length: pss_params.salt_length,
+ },
message.as_slice(),
signature.as_slice(),
);
@@ -6603,11 +6580,11 @@ impl AlgorithmMethods for RsaPss {
// 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.
// 3. If an error occurred while parsing, then throw a DataError.
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let mut spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
// is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
- if !spki.has_rsa_encryption_oid() {
+ if spki.algorithm() != Some(KeyAlgorithm::Rsa) {
return Err(dom_error(
"DataError",
b"Algorithm object identifier is not the rsaEncryption object identifier",
@@ -6618,7 +6595,7 @@ impl AlgorithmMethods for RsaPss {
// with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure
// specified in Section A.1.1 of [RFC3447], and exactData set to true.
// NOTE: We already did this in parse_a_subject_public_key_info
- let public_key = spki.rsa_key();
+ let public_key = spki.take_key();
// 6. If an error occurred while parsing, or it can be determined that publicKey is not
// a valid public key according to [RFC3447], then throw a DataError.
@@ -6654,11 +6631,11 @@ impl AlgorithmMethods for RsaPss {
// 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.
// 3. If an error occurred while parsing, then throw a DataError.
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let mut private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo
// is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
- if !private_key_info.has_rsa_encryption_oid() {
+ if private_key_info.algorithm() != Some(KeyAlgorithm::Rsa) {
return Err(dom_error(
"DataError",
b"Algorithm object identifier is not the rsaEncryption object identifier",
@@ -6669,7 +6646,7 @@ impl AlgorithmMethods for RsaPss {
// with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure
// specified in Section A.1.2 of [RFC3447], and exactData set to true.
// NOTE: We already did this in parse_a_private_key_info
- let rsa_private_key = private_key_info.rsa_key();
+ let rsa_private_key = private_key_info.take_key();
// 6. If an error occurred while parsing, or if rsaPrivateKey is not
// a valid RSA private key according to [RFC3447], then throw a DataError.
@@ -7201,7 +7178,9 @@ impl AlgorithmMethods for RsassaPkcs1 {
};
// 4. Let signature be the value S that results from performing the operation.
- let signature = libcrypto_rust::rsa_pkcs1_sign(hash_kind, key.handle(), message.as_slice()).map(Bytes::new);
+ let signature =
+ libcrypto_rust::rsa_sign(hash_kind, key.handle(), RsaSignaturePadding::Pkcs1, message.as_slice())
+ .map(Bytes::new);
if signature.is_err() {
return Err(dom_error("OperationError", b"Failed to sign message"));
}
@@ -7253,8 +7232,13 @@ impl AlgorithmMethods for RsassaPkcs1 {
// 3. Let result be a boolean with value true if the result of the operation was "valid signature" and the value
// false otherwise.
- let verified =
- libcrypto_rust::rsa_pkcs1_verify(hash_kind, key.handle(), message.as_slice(), signature.as_slice());
+ let verified = libcrypto_rust::rsa_verify(
+ hash_kind,
+ key.handle(),
+ RsaSignaturePadding::Pkcs1,
+ message.as_slice(),
+ signature.as_slice(),
+ );
if verified.is_err() {
return Err(dom_error("OperationError", b"Failed to verify message"));
}
@@ -7298,11 +7282,11 @@ impl AlgorithmMethods for RsassaPkcs1 {
// 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.
// 3. If an error occurred while parsing, then throw a DataError.
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let mut spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
// is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
- if !spki.has_rsa_encryption_oid() {
+ if spki.algorithm() != Some(KeyAlgorithm::Rsa) {
return Err(dom_error(
"DataError",
b"Algorithm object identifier is not the rsaEncryption object identifier",
@@ -7313,7 +7297,7 @@ impl AlgorithmMethods for RsassaPkcs1 {
// with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure
// specified in Section A.1.1 of [RFC3447], and exactData set to true.
// NOTE: We already did this in parse_a_subject_public_key_info
- let public_key = spki.rsa_key();
+ let public_key = spki.take_key();
// 6. If an error occurred while parsing, or it can be determined that publicKey is not
// a valid public key according to [RFC3447], then throw a DataError.
@@ -7349,11 +7333,11 @@ impl AlgorithmMethods for RsassaPkcs1 {
// 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.
// 3. If an error occurred while parsing, then throw a DataError.
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let mut private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo
// is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
- if !private_key_info.has_rsa_encryption_oid() {
+ if private_key_info.algorithm() != Some(KeyAlgorithm::Rsa) {
return Err(dom_error(
"DataError",
b"Algorithm object identifier is not the rsaEncryption object identifier",
@@ -7364,7 +7348,7 @@ impl AlgorithmMethods for RsassaPkcs1 {
// with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure
// specified in Section A.1.2 of [RFC3447], and exactData set to true.
// NOTE: We already did this in parse_a_private_key_info
- let rsa_private_key = private_key_info.rsa_key();
+ let rsa_private_key = private_key_info.take_key();
// 6. If an error occurred while parsing, or if rsaPrivateKey is not
// a valid RSA private key according to [RFC3447], then throw a DataError.
@@ -7831,10 +7815,6 @@ fn ec_curve_from_name(named_curve: &Utf16String) -> Option<EcCurve> {
}
}
-const SECP256R1_OID: [u32; 7] = [1, 2, 840, 10045, 3, 1, 7];
-const SECP384R1_OID: [u32; 5] = [1, 3, 132, 0, 34];
-const SECP521R1_OID: [u32; 5] = [1, 3, 132, 0, 35];
-
fn ec_key_from_coordinates(vm: &Vm, x: &Bytes, y: &Bytes, d: Option<&Bytes>) -> WebIdlResult<Ref<CryptoKey>> {
let Some(key) = libcrypto_rust::ec_key_from_coordinates(x.as_slice(), y.as_slice(), d.map(Bytes::as_slice)) else {
return Err(dom_error("DataError", b"Invalid key"));
@@ -7847,33 +7827,30 @@ fn ec_parse_raw_public_key(vm: &Vm, curve: EcCurve, key_bytes: &Bytes) -> WebIdl
return Err(dom_error("DataError", b"Failed to parse key"));
};
let key = CryptoKey::create(vm, key);
- let Ok(is_valid) = ec_key_is_valid(curve, key) else {
- return Err(dom_error("DataError", b"Failed to verify key"));
- };
- if !is_valid {
+ if !ec_key_is_valid(curve, key) {
return Err(dom_error("DataError", b"Invalid key"));
}
Ok(key)
}
-fn ec_key_is_valid(curve: EcCurve, key: Ref<CryptoKey>) -> Result<bool, BackendError> {
+fn ec_key_is_valid(curve: EcCurve, key: Ref<CryptoKey>) -> bool {
libcrypto_rust::ec_key_is_valid(curve, key.handle())
}
-fn ec_export_der(curve: EcCurve, key: Ref<CryptoKey>, is_public: bool) -> Result<Bytes, BackendError> {
+fn ec_export_der(curve: EcCurve, key: Ref<CryptoKey>, is_public: bool) -> Result<Bytes, CryptoError> {
libcrypto_rust::ec_export_der(curve, key.handle(), is_public).map(Bytes::new)
}
-fn ec_export_uncompressed(key: Ref<CryptoKey>) -> Result<Bytes, BackendError> {
+fn ec_export_uncompressed(key: Ref<CryptoKey>) -> Result<Bytes, CryptoError> {
libcrypto_rust::ec_export_uncompressed(key.handle()).map(Bytes::new)
}
-fn ec_export_public_coordinates(key: Ref<CryptoKey>) -> Result<(Bytes, Bytes), BackendError> {
+fn ec_export_public_coordinates(key: Ref<CryptoKey>) -> Result<(Bytes, Bytes), CryptoError> {
let (x, y) = libcrypto_rust::ec_export_public_coordinates(key.handle())?;
Ok((Bytes::new(x), Bytes::new(y)))
}
-fn ec_export_private_scalar(key: Ref<CryptoKey>) -> Result<Bytes, BackendError> {
+fn ec_export_private_scalar(key: Ref<CryptoKey>) -> Result<Bytes, CryptoError> {
libcrypto_rust::ec_export_private_scalar(key.handle()).map(Bytes::new)
}
@@ -8078,7 +8055,12 @@ impl AlgorithmMethods for Ecdsa {
let signature = libcrypto_rust::ec_sign(curve, d, m.as_slice());
let (r_bytes, s_bytes) = match signature {
Ok(signature) => signature,
- Err(message) => return Err(Exception::Dom("OperationError", message)),
+ Err(message) => {
+ return Err(Exception::Dom(
+ "OperationError",
+ Utf16String::from_utf8(message.message()),
+ ));
+ }
};
// 3. Let result be an empty byte sequence.
@@ -8189,7 +8171,10 @@ impl AlgorithmMethods for Ecdsa {
// message, (r, s) as the signature and using params as the EC domain parameters, and Q as the public key.
let verification = libcrypto_rust::ec_verify(curve, q, m.as_slice(), r, s);
if let Err(message) = verification {
- return Err(Exception::Dom("OperationError", message));
+ return Err(Exception::Dom(
+ "OperationError",
+ Utf16String::from_utf8(message.message()),
+ ));
}
result = verification.expect("LibCrypto returns the verification result");
} else {
@@ -8265,38 +8250,38 @@ impl AlgorithmMethods for Ecdsa {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let mut spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
// is not equal to the id-ecPublicKey object identifier defined in [RFC5480], then throw a DataError.
- if !spki.has_ec_public_key_oid() {
+ if spki.algorithm() != Some(KeyAlgorithm::Ec) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 5. If the parameters field of the algorithm AlgorithmIdentifier field of spki is absent, then throw a DataError.
- if spki.ec_parameters().is_none() {
+ if !spki.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
// 6. Let params be the parameters field of the algorithm AlgorithmIdentifier field of spki.
- let ec_params = spki.ec_parameters().expect("the algorithm parameters are present");
+ let ec_params = spki.named_curve();
// 7. If params is not an instance of the ECParameters ASN.1 type defined in [RFC5480] that specifies a namedCurve, then throw a DataError.
// 8. Let namedCurve be a string whose initial value is undefined.
let mut named_curve = Utf16String::default();
// 9. If params is equivalent to the secp256r1 object identifier defined in [RFC5480]:
- if ec_params == SECP256R1_OID {
+ if ec_params == Some(EcCurve::P256) {
// Set namedCurve "P-256".
named_curve = Utf16String::from_ascii(b"P-256");
}
// If params is equivalent to the secp384r1 object identifier defined in [RFC5480]:
- else if ec_params == SECP384R1_OID {
+ else if ec_params == Some(EcCurve::P384) {
// Set namedCurve "P-384".
named_curve = Utf16String::from_ascii(b"P-384");
}
// If params is equivalent to the secp521r1 object identifier defined in [RFC5480]:
- else if ec_params == SECP521R1_OID {
+ else if ec_params == Some(EcCurve::P521) {
// Set namedCurve "P-521".
named_curve = Utf16String::from_ascii(b"P-521");
}
@@ -8307,7 +8292,7 @@ impl AlgorithmMethods for Ecdsa {
// defined in Section 2.3.4 of [SEC1] using the subjectPublicKey field of spki. The uncompressed
// point format MUST be supported.
// The uncompressed point format MUST be supported.
- let public_key = spki.ec_key();
+ let public_key = spki.take_key();
// 2. If the implementation does not support the compressed point format and a compressed point is provided, throw a DataError.
// 3. If a decode error occurs or an identity point is found, throw a DataError.
@@ -8329,10 +8314,7 @@ impl AlgorithmMethods for Ecdsa {
// 12. If the public key value is not a valid point on the Elliptic Curve identified
// by the namedCurve member of normalizedAlgorithm throw a DataError.
let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");
- let Ok(maybe_valid) = ec_key_is_valid(curve, key) else {
- return Err(dom_error("DataError", b"Failed to verify key"));
- };
- if !maybe_valid {
+ if !ec_key_is_valid(curve, key) {
return Err(dom_error("DataError", b"Invalid key"));
}
@@ -8365,41 +8347,39 @@ impl AlgorithmMethods for Ecdsa {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let mut private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo
// is not equal to the id-ecPublicKey object identifier defined in [RFC5480], then throw a DataError.
- if !private_key_info.has_ec_public_key_oid() {
+ if private_key_info.algorithm() != Some(KeyAlgorithm::Ec) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 5. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field
// of privateKeyInfo is not present, then throw a DataError.
- if private_key_info.ec_parameters().is_none() {
+ if !private_key_info.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
// 6. Let params be the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.
- let ec_params = private_key_info
- .ec_parameters()
- .expect("the algorithm parameters are present");
+ let ec_params = private_key_info.named_curve();
// 7. If params is not an instance of the ECParameters ASN.1 type defined in [RFC5480] that specifies a namedCurve, then throw a DataError.
// 8. Let namedCurve be a string whose initial value is undefined.
let mut named_curve = Utf16String::default();
// 9. If params is equivalent to the secp256r1 object identifier defined in [RFC5480]:
- if ec_params == SECP256R1_OID {
+ if ec_params == Some(EcCurve::P256) {
// Set namedCurve "P-256".
named_curve = Utf16String::from_ascii(b"P-256");
}
// If params is equivalent to the secp384r1 object identifier defined in [RFC5480]:
- else if ec_params == SECP384R1_OID {
+ else if ec_params == Some(EcCurve::P384) {
// Set namedCurve "P-384".
named_curve = Utf16String::from_ascii(b"P-384");
}
// If params is equivalent to the secp521r1 object identifier defined in [RFC5480]:
- else if ec_params == SECP521R1_OID {
+ else if ec_params == Some(EcCurve::P521) {
// Set namedCurve "P-521".
named_curve = Utf16String::from_ascii(b"P-521");
}
@@ -8411,16 +8391,13 @@ impl AlgorithmMethods for Ecdsa {
// structure specified in Section 3 of [RFC5915], and exactData set to true.
// NOTE: We already did this in parse_a_private_key_info
// 2. If an error occurred while parsing, then throw a DataError.
- let ec_private_key = private_key_info.ec_key();
+ let ec_private_key = private_key_info.take_key();
// 3. If the parameters field of ecPrivateKey is present, and is not an instance of the namedCurve ASN.1
// type defined in [RFC5480], or does not contain the same object identifier as the parameters field
// of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo, then throw a
// DataError.
- if !private_key_info.ec_private_parameters_match() {
- return Err(dom_error("DataError", b"Invalid algorithm parameters"));
- }
-
+ // NB: LibCrypto rejects such an ecPrivateKey while parsing.
// 4. Let key be a new CryptoKey that represents the Elliptic Curve private key identified
// by performing the conversion steps defined in Section 3 of [RFC5915] using ecPrivateKey.
key = CryptoKey::create(cx.vm(), ec_private_key);
@@ -8440,10 +8417,7 @@ impl AlgorithmMethods for Ecdsa {
// 12. If the private key value is not a valid point on the Elliptic Curve identified by the namedCurve
// member of normalizedAlgorithm throw a DataError.
let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");
- let Ok(maybe_valid) = ec_key_is_valid(curve, key) else {
- return Err(dom_error("DataError", b"Failed to verify key"));
- };
- if !maybe_valid {
+ if !ec_key_is_valid(curve, key) {
return Err(dom_error("DataError", b"Invalid key"));
}
@@ -8623,10 +8597,7 @@ impl AlgorithmMethods for Ecdsa {
// 10. If the key value is not a valid point on the Elliptic Curve identified
// by the namedCurve member of normalizedAlgorithm throw a DataError.
let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");
- let Ok(maybe_valid) = ec_key_is_valid(curve, key) else {
- return Err(dom_error("DataError", b"Failed to verify key"));
- };
- if !maybe_valid {
+ if !ec_key_is_valid(curve, key) {
return Err(dom_error("DataError", b"Invalid key"));
}
@@ -9173,7 +9144,7 @@ impl AlgorithmMethods for Ecdh {
Err(detail) => {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Failed to compute secret: {}", &[&detail]),
+ libjs_rust::api::utf16_formatted("Failed to compute secret: {}", &[&detail.message()]),
));
}
};
@@ -9270,38 +9241,38 @@ impl AlgorithmMethods for Ecdh {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let mut spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
// is not equal to the id-ecPublicKey object identifier defined in [RFC5480], then throw a DataError.
- if !spki.has_ec_public_key_oid() {
+ if spki.algorithm() != Some(KeyAlgorithm::Ec) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 5. If the parameters field of the algorithm AlgorithmIdentifier field of spki is absent, then throw a DataError.
- if spki.ec_parameters().is_none() {
+ if !spki.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
// 6. Let params be the parameters field of the algorithm AlgorithmIdentifier field of spki.
- let ec_params = spki.ec_parameters().expect("the algorithm parameters are present");
+ let ec_params = spki.named_curve();
// 7. If params is not an instance of the ECParameters ASN.1 type defined in [RFC5480] that specifies a namedCurve, then throw a DataError.
// 8. Let namedCurve be a string whose initial value is undefined.
let mut named_curve = Utf16String::default();
// 9. If params is equivalent to the secp256r1 object identifier defined in [RFC5480]:
- if ec_params == SECP256R1_OID {
+ if ec_params == Some(EcCurve::P256) {
// Set namedCurve "P-256".
named_curve = Utf16String::from_ascii(b"P-256");
}
// If params is equivalent to the secp384r1 object identifier defined in [RFC5480]:
- else if ec_params == SECP384R1_OID {
+ else if ec_params == Some(EcCurve::P384) {
// Set namedCurve "P-384".
named_curve = Utf16String::from_ascii(b"P-384");
}
// If params is equivalent to the secp521r1 object identifier defined in [RFC5480]:
- else if ec_params == SECP521R1_OID {
+ else if ec_params == Some(EcCurve::P521) {
// Set namedCurve "P-521".
named_curve = Utf16String::from_ascii(b"P-521");
}
@@ -9312,7 +9283,7 @@ impl AlgorithmMethods for Ecdh {
// defined in Section 2.3.4 of [SEC1] to the subjectPublicKey field of spki. The uncompressed point
// format MUST be supported.
// The uncompressed point format MUST be supported.
- let public_key = spki.ec_key();
+ let public_key = spki.take_key();
// 2. If the implementation does not support the compressed point format and a compressed point is provided, throw a DataError.
// 3. If a decode error occurs or an identity point is found, throw a DataError.
@@ -9334,10 +9305,7 @@ impl AlgorithmMethods for Ecdh {
// 12. If the key value is not a valid point on the Elliptic Curve identified
// by the namedCurve member of normalizedAlgorithm throw a DataError.
let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");
- let Ok(maybe_valid) = ec_key_is_valid(curve, key) else {
- return Err(dom_error("DataError", b"Failed to verify key"));
- };
- if !maybe_valid {
+ if !ec_key_is_valid(curve, key) {
return Err(dom_error("DataError", b"Invalid key"));
}
@@ -9370,42 +9338,40 @@ impl AlgorithmMethods for Ecdh {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let mut private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of
// privateKeyInfo is not equal to the id-ecPublicKey object identifier defined in [RFC5480], throw a
// DataError.
- if !private_key_info.has_ec_public_key_oid() {
+ if private_key_info.algorithm() != Some(KeyAlgorithm::Ec) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 5. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of
// privateKeyInfo is not present, throw a DataError.
- if private_key_info.ec_parameters().is_none() {
+ if !private_key_info.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
// 6. Let params be the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.
- let ec_params = private_key_info
- .ec_parameters()
- .expect("the algorithm parameters are present");
+ let ec_params = private_key_info.named_curve();
// 7. If params is not an instance of the ECParameters ASN.1 type defined in [RFC5480] that specifies a namedCurve, then throw a DataError.
// 8. Let namedCurve be a string whose initial value is undefined.
let mut named_curve = Utf16String::default();
// 9. If params is equivalent to the secp256r1 object identifier defined in [RFC5480]:
- if ec_params == SECP256R1_OID {
+ if ec_params == Some(EcCurve::P256) {
// Set namedCurve to "P-256".
named_curve = Utf16String::from_ascii(b"P-256");
}
// If params is equivalent to the secp384r1 object identifier defined in [RFC5480]:
- else if ec_params == SECP384R1_OID {
+ else if ec_params == Some(EcCurve::P384) {
// Set namedCurve to "P-384".
named_curve = Utf16String::from_ascii(b"P-384");
}
// If params is equivalent to the secp521r1 object identifier defined in [RFC5480]:
- else if ec_params == SECP521R1_OID {
+ else if ec_params == Some(EcCurve::P521) {
// Set namedCurve to "P-521".
named_curve = Utf16String::from_ascii(b"P-521");
}
@@ -9417,16 +9383,13 @@ impl AlgorithmMethods for Ecdh {
// structure specified in Section 3 of [RFC5915], and exactData set to true.
// NOTE: We already did this in parse_a_private_key_info
// 2. If an error occurred while parsing, then throw a DataError.
- let ec_private_key = private_key_info.ec_key();
+ let ec_private_key = private_key_info.take_key();
// 3. If the parameters field of ecPrivateKey is present, and is not an instance
// of the namedCurve ASN.1 type defined in [RFC5480], or does not contain
// the same object identifier as the parameters field of the privateKeyAlgorithm
// PrivateKeyAlgorithmIdentifier field of privateKeyInfo, throw a DataError.
- if !private_key_info.ec_private_parameters_match() {
- return Err(dom_error("DataError", b"Invalid algorithm parameters"));
- }
-
+ // NB: LibCrypto rejects such an ecPrivateKey while parsing.
// 4. Let key be a new CryptoKey that represents the Elliptic Curve private key identified
// by performing the conversion steps defined in Section 3 of [RFC5915] using ecPrivateKey.
key = CryptoKey::create(cx.vm(), ec_private_key);
@@ -9446,10 +9409,7 @@ impl AlgorithmMethods for Ecdh {
// 12. If the key value is not a valid point on the Elliptic Curve identified
// by the namedCurve member of normalizedAlgorithm throw a DataError.
let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");
- let Ok(maybe_valid) = ec_key_is_valid(curve, key) else {
- return Err(dom_error("DataError", b"Failed to verify key"));
- };
- if !maybe_valid {
+ if !ec_key_is_valid(curve, key) {
return Err(dom_error("DataError", b"Invalid key"));
}
@@ -9591,10 +9551,7 @@ impl AlgorithmMethods for Ecdh {
// 11. If the key value is not a valid point on the Elliptic Curve identified
// by the namedCurve member of normalizedAlgorithm throw a DataError.
let curve = ec_curve_from_name(&named_curve).expect("the named curve is supported");
- let Ok(maybe_valid) = ec_key_is_valid(curve, key) else {
- return Err(dom_error("DataError", b"Failed to verify key"));
- };
- if !maybe_valid {
+ if !ec_key_is_valid(curve, key) {
return Err(dom_error("DataError", b"Invalid key"));
}
@@ -9931,11 +9888,13 @@ impl Ed448Params {
}
fn parse_octet_string(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Vec<u8>> {
- let Asn1Value::OctetString(octets) = parse_an_asn1_structure(bytes, Asn1Structure::OctetString, true)
- .map_err(|message| Exception::Dom("DataError", message))?
- else {
- unreachable!("the ASN.1 structure is an octet string")
- };
+ let octets = parse_an_asn1_structure(
+ bytes,
+ libcrypto_rust::parse_octet_string,
+ "Read of kind OctetString failed: {}",
+ true,
+ )
+ .map_err(|message| Exception::Dom("DataError", message))?;
copy_bytes(vm, octets)
}
@@ -10086,16 +10045,16 @@ impl AlgorithmMethods for Ed25519 {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
// is not equal to the id-Ed25519 object identifier defined in [RFC8410], then throw a DataError.
- if !spki.has_okp_oid(OkpCurve::Ed25519) {
+ if spki.algorithm() != Some(KeyAlgorithm::Okp(OkpCurve::Ed25519)) {
return Err(dom_error("DataError", b"Invalid algorithm identifier"));
}
// 5. If the parameters field of the algorithm AlgorithmIdentifier field of spki is present, then throw a DataError.
- if spki.ec_parameters().is_some() {
+ if spki.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -10132,17 +10091,17 @@ impl AlgorithmMethods for Ed25519 {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field
// of privateKeyInfo is not equal to the id-Ed25519 object identifier defined in [RFC8410], then throw a DataError.
- if !private_key_info.has_okp_oid(OkpCurve::Ed25519) {
+ if private_key_info.algorithm() != Some(KeyAlgorithm::Okp(OkpCurve::Ed25519)) {
return Err(dom_error("DataError", b"Invalid algorithm identifier"));
}
// 5. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo is present,
// then throw a DataError.
- if private_key_info.ec_parameters().is_some() {
+ if private_key_info.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -10549,7 +10508,10 @@ impl AlgorithmMethods for Ed25519 {
&[],
);
if let Err(error) = verified {
- return Err(Exception::Dom("OperationError", error));
+ return Err(Exception::Dom(
+ "OperationError",
+ Utf16String::from_utf8(error.message()),
+ ));
}
// 6. Return result.
@@ -10687,16 +10649,16 @@ impl AlgorithmMethods for Ed448 {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
// is not equal to the id-Ed448 object identifier defined in [RFC8410], then throw a DataError.
- if !spki.has_okp_oid(OkpCurve::Ed448) {
+ if spki.algorithm() != Some(KeyAlgorithm::Okp(OkpCurve::Ed448)) {
return Err(dom_error("DataError", b"Invalid algorithm identifier"));
}
// 5. If the parameters field of the algorithm AlgorithmIdentifier field of spki is present, then throw a DataError.
- if spki.ec_parameters().is_some() {
+ if spki.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -10734,17 +10696,17 @@ impl AlgorithmMethods for Ed448 {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field
// of privateKeyInfo is not equal to the id-Ed448 object identifier defined in [RFC8410], then throw a DataError.
- if !private_key_info.has_okp_oid(OkpCurve::Ed448) {
+ if private_key_info.algorithm() != Some(KeyAlgorithm::Okp(OkpCurve::Ed448)) {
return Err(dom_error("DataError", b"Invalid algorithm identifier"));
}
// 5. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo is present,
// then throw a DataError.
- if private_key_info.ec_parameters().is_some() {
+ if private_key_info.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -11165,7 +11127,10 @@ impl AlgorithmMethods for Ed448 {
context,
);
if let Err(error) = verified {
- return Err(Exception::Dom("OperationError", error));
+ return Err(Exception::Dom(
+ "OperationError",
+ Utf16String::from_utf8(error.message()),
+ ));
}
// 7. Let result be a boolean with the value true if the signature is valid
@@ -11417,16 +11382,16 @@ impl AlgorithmMethods for X25519 {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
// is not equal to the id-X25519 object identifier defined in [RFC8410], then throw a DataError.
- if !spki.has_okp_oid(OkpCurve::X25519) {
+ if spki.algorithm() != Some(KeyAlgorithm::Okp(OkpCurve::X25519)) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 5. If the parameters field of the algorithm AlgorithmIdentifier field of spki is present, then throw a DataError.
- if spki.ec_parameters().is_some() {
+ if spki.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -11463,16 +11428,16 @@ impl AlgorithmMethods for X25519 {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo
// is not equal to the id-X25519 object identifier defined in [RFC8410], then throw a DataError.
- if !private_key_info.has_okp_oid(OkpCurve::X25519) {
+ if private_key_info.algorithm() != Some(KeyAlgorithm::Okp(OkpCurve::X25519)) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 5. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo is present, then throw a DataError.
- if private_key_info.ec_parameters().is_some() {
+ if private_key_info.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -12125,15 +12090,15 @@ impl AlgorithmMethods for X448 {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki is not equal to the id-X448 object identifier defined in [RFC8410], then throw a DataError.
- if !spki.has_okp_oid(OkpCurve::X448) {
+ if spki.algorithm() != Some(KeyAlgorithm::Okp(OkpCurve::X448)) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 5. If the parameters field of the algorithm AlgorithmIdentifier field of spki is present, then throw a DataError.
- if spki.ec_parameters().is_some() {
+ if spki.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -12173,15 +12138,15 @@ impl AlgorithmMethods for X448 {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo is not equal to the id-X448 object identifier defined in [RFC8410], then throw a DataError.
- if !private_key_info.has_okp_oid(OkpCurve::X448) {
+ if private_key_info.algorithm() != Some(KeyAlgorithm::Okp(OkpCurve::X448)) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 5. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo is present, then throw a DataError.
- if private_key_info.ec_parameters().is_some() {
+ if private_key_info.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -12401,10 +12366,6 @@ impl AlgorithmMethods for X448 {
type ContextParams = Ed448Params;
-const ML_DSA_44_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 3, 17];
-const ML_DSA_65_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 3, 18];
-const ML_DSA_87_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 3, 19];
-
fn mldsa_size(name: &Utf16String) -> MlDsaSize {
if matches!(name.as_units(), Utf16StringUnits::Ascii(b"ML-DSA-44")) {
MlDsaSize::MlDsa44
@@ -12425,7 +12386,7 @@ fn mldsa_read_public_key(vm: &Vm, size: MlDsaSize, bytes: &[u8]) -> WebIdlResult
Ok(CryptoKey::create(vm, key))
}
-fn generate_mldsa_key_pair_from_seed(name: &Utf16String, seed: &Bytes) -> Result<KeyPair, Utf16String> {
+fn generate_mldsa_key_pair_from_seed(name: &Utf16String, seed: &Bytes) -> Result<KeyPair, CryptoError> {
if matches!(name.as_units(), Utf16StringUnits::Ascii(b"ML-DSA-44")) {
return libcrypto_rust::mldsa_generate_key_pair(MlDsaSize::MlDsa44, seed.as_slice());
}
@@ -12438,8 +12399,8 @@ fn generate_mldsa_key_pair_from_seed(name: &Utf16String, seed: &Bytes) -> Result
unreachable!("the name identifies an ML-DSA parameter set")
}
-fn mldsa_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, oid: &[u32]) -> WebIdlResult<Bytes> {
- let result = libcrypto_rust::mldsa_export_der(key.handle(), is_public, oid).map(Bytes::new);
+fn mldsa_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, algorithm: KeyAlgorithm) -> WebIdlResult<Bytes> {
+ let result = libcrypto_rust::ml_export_der(key.handle(), is_public, algorithm).map(Bytes::new);
if result.is_err() {
return Err(out_of_memory(vm));
}
@@ -12704,22 +12665,22 @@ impl AlgorithmMethods for MlDsa {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the name member of normalizedAlgorithm is "ML-DSA-44":
let expected_oid = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-DSA-44")) {
// Let expectedOid be id-ml-dsa-44 (2.16.840.1.101.3.4.3.17).
- ML_DSA_44_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa44)
}
// If the name member of normalizedAlgorithm is "ML-DSA-65":
else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-DSA-65")) {
// Let expectedOid be id-ml-dsa-65 (2.16.840.1.101.3.4.3.18).
- ML_DSA_65_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa65)
}
// If the name member of normalizedAlgorithm is "ML-DSA-87":
else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-DSA-87")) {
// Let expectedOid be id-ml-dsa-87 (2.16.840.1.101.3.4.3.19).
- ML_DSA_87_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa87)
}
// Otherwise:
else {
@@ -12729,12 +12690,12 @@ impl AlgorithmMethods for MlDsa {
// 5. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki is not equal
// to expectedOid, then throw a DataError.
- if spki.oid() != expected_oid {
+ if spki.algorithm() != Some(expected_oid) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 6. If the parameters field of the algorithm AlgorithmIdentifier field of spki is present, then throw a DataError.
- if spki.ec_parameters().is_some() {
+ if spki.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -12771,7 +12732,7 @@ impl AlgorithmMethods for MlDsa {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let mut private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the name member of normalizedAlgorithm is "ML-DSA-44":
// Let expectedOid be id-ml-dsa-44 (2.16.840.1.101.3.4.3.17). Let asn1Structure be the ASN.1
@@ -12785,24 +12746,24 @@ impl AlgorithmMethods for MlDsa {
// 4. Otherwise:
// throw a NotSupportedError.
let expected_oid = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-DSA-44")) {
- ML_DSA_44_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa44)
} else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-DSA-65")) {
- ML_DSA_65_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa65)
} else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-DSA-87")) {
- ML_DSA_87_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa87)
} else {
return Err(dom_error("NotSupportedError", b"Invalid algorithm"));
};
// 5. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of
// privateKeyInfo is not equal to expectedOid, then throw a DataError.
- if private_key_info.oid() != expected_oid {
+ if private_key_info.algorithm() != Some(expected_oid) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 6. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of
// privateKeyInfo is present, then throw a DataError.
- if private_key_info.ec_parameters().is_some() {
+ if private_key_info.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -12811,13 +12772,10 @@ impl AlgorithmMethods for MlDsa {
// true.
// NOTE: We already did this in parse_a_private_key_info
// 8. If an error occurred while parsing, then throw a DataError.
- let ml_dsa_private_key = private_key_info.mldsa_private_key();
-
// 9. If mlDsaPrivateKey represents an ML-DSA key in the expandedKey format, or if mlDsaPrivateKey
// represents an ML-DSA key in the both format and the both format is not supported, throw a
// NotSupportedError.
- // NB: A key in the expandedKey format has no seed.
- if !libcrypto_rust::ml_private_key_has_seed(&ml_dsa_private_key) {
+ if private_key_info.is_ml_expanded_key_form() {
return Err(dom_error(
"NotSupportedError",
b"ML-DSA private keys in the expandedKey format are not supported",
@@ -12829,7 +12787,7 @@ impl AlgorithmMethods for MlDsa {
// NB: LibCrypto checks the correspondence between the seed and expanded key while parsing.
// 11. Let key be a new CryptoKey that represents the ML-DSA private key identified by mlDsaPrivateKey.
- key = CryptoKey::create(cx.vm(), ml_dsa_private_key);
+ key = CryptoKey::create(cx.vm(), private_key_info.take_key());
// 12. Set the [[type]] internal slot of key to "private"
key.set_type(KeyType::Private);
@@ -12897,7 +12855,7 @@ impl AlgorithmMethods for MlDsa {
let key_pair = maybe_key_pair.map_err(|error| {
Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Key generation failed: {}", &[&error]),
+ libjs_rust::api::utf16_formatted("Key generation failed: {}", &[&error.message()]),
)
})?;
let private_key = key_pair.private_key;
@@ -12977,7 +12935,7 @@ impl AlgorithmMethods for MlDsa {
let key_pair = maybe_key_pair.map_err(|error| {
Exception::Dom(
"DataError",
- libjs_rust::api::utf16_formatted("Invalid seed: {}", &[&error]),
+ libjs_rust::api::utf16_formatted("Invalid seed: {}", &[&error.message()]),
)
})?;
let KeyPair {
@@ -13072,16 +13030,16 @@ impl AlgorithmMethods for MlDsa {
// throw a NotSupportedError.
// * Set the subjectPublicKey field to keyData.
let algorithm_oid = if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-DSA-44")) {
- ML_DSA_44_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa44)
} else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-DSA-65")) {
- ML_DSA_65_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa65)
} else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-DSA-87")) {
- ML_DSA_87_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa87)
} else {
return Err(dom_error("NotSupportedError", b"Invalid algorithm"));
};
- let data = mldsa_export_der(vm, key, true, &algorithm_oid)?;
+ let data = mldsa_export_der(vm, key, true, algorithm_oid)?;
// 4. Let result be the result of DER-encoding data.
ExportKeyResult::Bytes(data)
@@ -13127,16 +13085,16 @@ impl AlgorithmMethods for MlDsa {
// Otherwise:
// throw a NotSupportedError.
let algorithm_oid = if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-DSA-44")) {
- ML_DSA_44_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa44)
} else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-DSA-65")) {
- ML_DSA_65_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa65)
} else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-DSA-87")) {
- ML_DSA_87_OID
+ KeyAlgorithm::MlDsa(MlDsaSize::MlDsa87)
} else {
return Err(dom_error("NotSupportedError", b"Invalid algorithm"));
};
- let data = mldsa_export_der(vm, key, false, &algorithm_oid)?;
+ let data = mldsa_export_der(vm, key, false, algorithm_oid)?;
// 4. Let result be the result of DER-encoding data.
ExportKeyResult::Bytes(data)
@@ -13165,7 +13123,7 @@ impl AlgorithmMethods for MlDsa {
// 2. Let data be a byte sequence containing the ξ seed variable of the key represented by the [[handle]] internal slot of key.
// Note: The ξ value is the seed from which the key was generated or imported, as used by
// ML-DSA.KeyGen_internal in Section 6.1 of [FIPS-204].
- let seed = libcrypto_rust::mldsa_seed_bytes(handle).map_err(|_| out_of_memory(vm))?;
+ let seed = libcrypto_rust::ml_seed_bytes(handle).map_err(|_| out_of_memory(vm))?;
let data = Bytes::new(seed);
// 3. Let result be data.
@@ -13191,7 +13149,7 @@ impl AlgorithmMethods for MlDsa {
// 6. -> If the [[type]] internal slot of key is "private":
// Set the priv attribute of jwk to the base64url encoded seed represented by the [[handle]] internal slot of key.
if key.key_type() == KeyType::Private {
- let seed = libcrypto_rust::mldsa_seed_bytes(handle).map_err(|_| out_of_memory(vm))?;
+ let seed = libcrypto_rust::ml_seed_bytes(handle).map_err(|_| out_of_memory(vm))?;
jwk.r#priv = Some(base64_url_bytes_encode(&seed));
}
@@ -13224,10 +13182,6 @@ impl AlgorithmMethods for MlDsa {
}
}
-const ML_KEM_512_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 4, 1];
-const ML_KEM_768_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 4, 2];
-const ML_KEM_1024_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 4, 3];
-
fn mlkem_read_public_key(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Ref<CryptoKey>> {
let Some(key) = libcrypto_rust::mlkem_read_public_key(bytes) else {
return Err(dom_error("DataError", b"Invalid key"));
@@ -13235,8 +13189,8 @@ fn mlkem_read_public_key(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Ref<CryptoKey>>
Ok(CryptoKey::create(vm, key))
}
-fn mlkem_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, oid: &[u32]) -> WebIdlResult<Bytes> {
- let result = libcrypto_rust::mlkem_export_der(key.handle(), is_public, oid).map(Bytes::new);
+fn mlkem_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, algorithm: KeyAlgorithm) -> WebIdlResult<Bytes> {
+ let result = libcrypto_rust::ml_export_der(key.handle(), is_public, algorithm).map(Bytes::new);
if result.is_err() {
return Err(out_of_memory(vm));
}
@@ -13287,7 +13241,7 @@ impl AlgorithmMethods for MlKem {
let key_pair = maybe_key_pair.map_err(|error| {
Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Key generation failed: {}", &[&error]),
+ libjs_rust::api::utf16_formatted("Key generation failed: {}", &[&error.message()]),
)
})?;
@@ -13378,22 +13332,22 @@ impl AlgorithmMethods for MlKem {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let spki = parse_key_info(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+ let spki = parse_a_subject_public_key_info(key_data.as_slice())?;
// 4. If the name member of normalizedAlgorithm is "ML-KEM-512":
let expected_oid = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
// Let expectedOid be id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1).
- ML_KEM_512_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem512)
}
// If the name member of normalizedAlgorithm is "ML-KEM-768":
else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
// Let expectedOid be id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2).
- ML_KEM_768_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem768)
}
// If the name member of normalizedAlgorithm is "ML-KEM-1024":
else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
// Let expectedOid be id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3).
- ML_KEM_1024_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem1024)
}
// Otherwise:
else {
@@ -13403,12 +13357,12 @@ impl AlgorithmMethods for MlKem {
// 5. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki is not equal
// to expectedOid, then throw a DataError.
- if spki.oid() != expected_oid {
+ if spki.algorithm() != Some(expected_oid) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 6. If the parameters field of the algorithm AlgorithmIdentifier field of spki is present, then throw a DataError.
- if spki.ec_parameters().is_some() {
+ if spki.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -13445,7 +13399,7 @@ impl AlgorithmMethods for MlKem {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("DER key data contains bytes")
};
- let private_key_info = parse_key_info(&key_data, Asn1Structure::PrivateKeyInfo)?;
+ let mut private_key_info = parse_a_private_key_info(key_data.as_slice())?;
// 4. If the name member of normalizedAlgorithm is "ML-KEM-512":
// Let expectedOid be id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1). Let asn1Structure be the ASN.1
@@ -13459,24 +13413,24 @@ impl AlgorithmMethods for MlKem {
// 4. Otherwise:
// throw a NotSupportedError.
let expected_oid = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
- ML_KEM_512_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem512)
} else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
- ML_KEM_768_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem768)
} else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
- ML_KEM_1024_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem1024)
} else {
return Err(dom_error("NotSupportedError", b"Invalid algorithm"));
};
// 5. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of
// privateKeyInfo is not equal to expectedOid, then throw a DataError.
- if private_key_info.oid() != expected_oid {
+ if private_key_info.algorithm() != Some(expected_oid) {
return Err(dom_error("DataError", b"Invalid algorithm"));
}
// 6. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of
// privateKeyInfo is present, then throw a DataError.
- if private_key_info.ec_parameters().is_some() {
+ if private_key_info.has_parameters() {
return Err(dom_error("DataError", b"Invalid algorithm parameters"));
}
@@ -13485,13 +13439,10 @@ impl AlgorithmMethods for MlKem {
// true.
// NOTE: We already did this in parse_a_private_key_info
// 8. If an error occurred while parsing, then throw a DataError.
- let ml_kem_private_key = private_key_info.mlkem_private_key();
-
// 9. If mlKemPrivateKey represents an ML-KEM key in the expandedKey format, or if mlKemPrivateKey
// represents an ML-KEM key in the both format and the both format is not supported, throw a
// NotSupportedError.
- // NB: A key in the expandedKey format has no seed.
- if !libcrypto_rust::ml_private_key_has_seed(&ml_kem_private_key) {
+ if private_key_info.is_ml_expanded_key_form() {
return Err(dom_error(
"NotSupportedError",
b"ML-KEM private keys in the expandedKey format are not supported",
@@ -13503,7 +13454,7 @@ impl AlgorithmMethods for MlKem {
// NB: LibCrypto checks the correspondence between the seed and expanded key while parsing.
// 11. Let key be a new CryptoKey that represents the ML-KEM private key identified by mlKemPrivateKey.
- key = CryptoKey::create(cx.vm(), ml_kem_private_key);
+ key = CryptoKey::create(cx.vm(), private_key_info.take_key());
// 12. Set the [[type]] internal slot of key to "private"
key.set_type(KeyType::Private);
@@ -13583,7 +13534,7 @@ impl AlgorithmMethods for MlKem {
let key_pair = maybe_key_pair.map_err(|error| {
Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Key generation failed: {}", &[&error]),
+ libjs_rust::api::utf16_formatted("Key generation failed: {}", &[&error.message()]),
)
})?;
@@ -13685,16 +13636,16 @@ impl AlgorithmMethods for MlKem {
// throw a NotSupportedError.
// * Set the subjectPublicKey field to keyData.
let algorithm_oid = if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
- ML_KEM_512_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem512)
} else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
- ML_KEM_768_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem768)
} else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
- ML_KEM_1024_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem1024)
} else {
return Err(dom_error("NotSupportedError", b"Invalid algorithm"));
};
- let data = mlkem_export_der(vm, key, true, &algorithm_oid)?;
+ let data = mlkem_export_der(vm, key, true, algorithm_oid)?;
// 4. Let result be the result of DER-encoding data.
ExportKeyResult::Bytes(data)
@@ -13740,16 +13691,16 @@ impl AlgorithmMethods for MlKem {
// Otherwise:
// throw a NotSupportedError.
let algorithm_oid = if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
- ML_KEM_512_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem512)
} else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
- ML_KEM_768_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem768)
} else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
- ML_KEM_1024_OID
+ KeyAlgorithm::MlKem(MlKemSize::MlKem1024)
} else {
return Err(dom_error("NotSupportedError", b"Invalid algorithm"));
};
- let data = mlkem_export_der(vm, key, false, &algorithm_oid)?;
+ let data = mlkem_export_der(vm, key, false, algorithm_oid)?;
// 4. Let result be the result of DER-encoding data.
ExportKeyResult::Bytes(data)
@@ -13778,7 +13729,7 @@ impl AlgorithmMethods for MlKem {
// key represented by the [[handle]] internal slot of key.
// Note: The d and z values are the seed from which the key was generated or imported, as used by
// ML-KEM.KeyGen_internal in Section 6.1 of [FIPS-203].
- let seed = libcrypto_rust::mlkem_seed_bytes(handle).map_err(|_| out_of_memory(vm))?;
+ let seed = libcrypto_rust::ml_seed_bytes(handle).map_err(|_| out_of_memory(vm))?;
let data = Bytes::new(seed);
// 3. Let result be data.
@@ -13850,7 +13801,7 @@ impl AlgorithmMethods for MlKem {
if let Err(error) = encapsulation {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Key encapsulation failed: {}", &[&error]),
+ libjs_rust::api::utf16_formatted("Key encapsulation failed: {}", &[&error.message()]),
));
}
@@ -13907,7 +13858,7 @@ impl AlgorithmMethods for MlKem {
if let Err(error) = shared_key {
return Err(Exception::Dom(
"OperationError",
- libjs_rust::api::utf16_formatted("Key decapsulation failed: {}", &[&error]),
+ libjs_rust::api::utf16_formatted("Key decapsulation failed: {}", &[&error.message()]),
));
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
index 45c4a44423e..a878197904f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
@@ -10,7 +10,7 @@ use core::cell::{Cell, RefCell};
use core::ffi::c_void;
use ak::{Span, Utf16String};
-use libcrypto_rust::{KeyDecodeError, KeyHandle};
+use libcrypto_rust::{HandleTag, KeyHandle};
use libjs_rust::api::{
Array, CellRoot, ErrorKind, ErrorType, Gc, GcRefCell, GcWeak, IntegrityLevel, MarkedVec, Must, Object,
PrimitiveString, PropertyKey, Trace, Value, Vm,
@@ -18,7 +18,7 @@ use libjs_rust::api::{
use crate::bindings::conversions::create_uint8_array;
use crate::bindings::interface::{
- Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, create_dictionary_object, realm_arguments, wrap,
+ Ref, Wrappable, allocate, cell_from_abi, create_dictionary_object, realm_arguments, wrap,
};
use crate::bindings::setlike::WorldEntries;
use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};
@@ -419,13 +419,6 @@ const ALGORITHM_AES: u8 = 4;
const ALGORITHM_HMAC: u8 = 5;
const ALGORITHM_KMAC: u8 = 6;
-/// The tags of a serialized handle, Crypto::HandleTag, which are part of the stable storage serialization format.
-const HANDLE_EC_PRIVATE_KEY: u8 = 4;
-
-/// The number of buffers of the handle of each tag, Crypto::HandleTag. An EC private key has one, then optionally its
-/// parameters and its public key, whose two buffers follow.
-const HANDLE_BUFFER_COUNTS: [usize; 11] = [1, 2, 8, 2, 1, 1, 3, 1, 3, 1, 1];
-
fn data_clone_error(message: &[u8]) -> Exception {
Exception::Dom("DataCloneError", Utf16String::from_ascii(message))
}
@@ -512,30 +505,30 @@ impl Serializable for CryptoKey {
}
// 5. Set serialized.[[Handle]] to the [[handle]] internal slot of value.
- self.handle().with_components(|fields| {
- serialized.write_u8(fields.tag);
- let buffers = fields.buffers();
- if fields.tag != HANDLE_EC_PRIVATE_KEY {
- for buffer in buffers {
- serialized.write_bytes(buffer);
- }
- return;
+ // NB: An EC private key's parameters and whether it has its public key follow its first buffer.
+ let stored = self.handle().to_stored();
+ serialized.write_u8(stored.tag as u8);
+ let buffers = stored.buffers();
+ if stored.tag != HandleTag::EcPrivate {
+ for buffer in buffers {
+ serialized.write_bytes(buffer);
}
+ return Ok(());
+ }
- serialized.write_bytes(buffers[0]);
- serialized.write_bool(fields.ec_parameters.is_some());
- if let Some(parameters) = fields.ec_parameters {
- serialized.write_u64(parameters.len() as u64);
- for &parameter in parameters {
- serialized.write_u32(parameter);
- }
- }
- serialized.write_bool(fields.has_ec_public_key);
- if fields.has_ec_public_key {
- serialized.write_bytes(buffers[1]);
- serialized.write_bytes(buffers[2]);
+ serialized.write_bytes(buffers[0]);
+ serialized.write_bool(stored.ec_parameters.is_some());
+ if let Some(parameters) = &stored.ec_parameters {
+ serialized.write_u64(parameters.len() as u64);
+ for &parameter in parameters {
+ serialized.write_u32(parameter);
}
- });
+ }
+ serialized.write_bool(stored.has_ec_public_key);
+ if stored.has_ec_public_key {
+ serialized.write_bytes(buffers[1]);
+ serialized.write_bytes(buffers[2]);
+ }
Ok(())
}
@@ -597,13 +590,12 @@ impl Serializable for CryptoKey {
}
// 5. Initialize the [[handle]] internal slot of value to serialized.[[Handle]].
- let handle_tag = serialized.read_u8()?;
- let Some(&buffer_count) = HANDLE_BUFFER_COUNTS.get(usize::from(handle_tag)) else {
+ let Ok(handle_tag) = HandleTag::try_from(serialized.read_u8()?) else {
return Err(data_clone_error(b"Invalid CryptoKey handle tag"));
};
let mut buffers: Vec<&[u8]> = Vec::new();
let (mut has_ec_parameters, mut ec_parameters, mut has_ec_public_key) = (false, Vec::new(), false);
- if handle_tag == HANDLE_EC_PRIVATE_KEY {
+ if handle_tag == HandleTag::EcPrivate {
buffers.push(serialized.read_borrowed_bytes()?);
has_ec_parameters = serialized.read_bool()?;
if has_ec_parameters {
@@ -618,28 +610,18 @@ impl Serializable for CryptoKey {
buffers.push(serialized.read_borrowed_bytes()?);
}
} else {
- for _ in 0..buffer_count {
+ for _ in 0..handle_tag.buffer_count() {
buffers.push(serialized.read_borrowed_bytes()?);
}
}
- let handle = KeyHandle::from_components(
+ let Ok(handle) = KeyHandle::from_stored(
handle_tag,
&buffers,
has_ec_parameters.then_some(ec_parameters.as_slice()),
has_ec_public_key,
- );
- let handle = match handle {
- Ok(handle) => handle,
- Err(KeyDecodeError::OutOfMemory) => {
- return cx
- .vm()
- .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])
- .map_err(Into::into);
- }
- Err(KeyDecodeError::InvalidComponents) => {
- return Err(data_clone_error(b"Invalid CryptoKey handle components"));
- }
+ ) else {
+ return Err(data_clone_error(b"Invalid CryptoKey handle components"));
};
let key = Self::create(cx.vm(), handle);
@@ -757,16 +739,6 @@ impl InternalAlgorithmData {
}
}
-/// # Safety
-///
-/// The VM is live and the caller transfers ownership of the handle.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_crypto_key_create(vm: *const c_void, handle: KeyHandle) -> *mut c_void {
- // SAFETY: The VM is live and the handle is owned.
- let vm = unsafe { &*vm.cast::<Vm>() };
- cell_into_abi(CryptoKey::create(vm, handle))
-}
-
/// # Safety
///
/// The VM, realm, and CryptoKey cell must be live.
@@ -781,15 +753,6 @@ pub unsafe extern "C" fn web_rust_crypto_key_wrap(
wrap(&CallContext::new(vm, realm), key).as_ptr().cast()
}
-/// # Safety
-///
-/// The key must be a live CryptoKey cell.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn web_rust_crypto_key_handle(key: *mut c_void) -> *mut c_void {
- // SAFETY: LibWeb supplies a live CryptoKey cell.
- unsafe { cell_from_abi::<CryptoKey>(key) }.handle().as_raw()
-}
-
/// # Safety
///
/// The key must be a live CryptoKey cell.
diff --git a/Libraries/LibWeb/Crypto/CryptoKey.cpp b/Libraries/LibWeb/Crypto/CryptoKey.cpp
index c75508e2beb..a22af17b34b 100644
--- a/Libraries/LibWeb/Crypto/CryptoKey.cpp
+++ b/Libraries/LibWeb/Crypto/CryptoKey.cpp
@@ -38,8 +38,6 @@ struct CryptoKeyAlgorithmFields {
extern "C" {
-CryptoKey* web_rust_crypto_key_create(JSVM*, CryptoKey::InternalKeyData*);
-CryptoKey::InternalKeyData const* web_rust_crypto_key_handle(CryptoKey const*);
bool web_rust_crypto_key_extractable(CryptoKey const*);
u8 web_rust_crypto_key_type(CryptoKey const*);
void web_rust_crypto_key_set_extractable(CryptoKey*, bool);
@@ -51,16 +49,6 @@ void web_rust_crypto_key_with_usages(CryptoKey const*, void*, void (*)(void*, Re
void web_rust_crypto_key_set_usages(CryptoKey*, ReadonlySpan<KeyUsage>);
}
-GC::Ref<CryptoKey> CryptoKey::create(InternalKeyData key_data)
-{
- return *web_rust_crypto_key_create(JS::HostABI::vm_to_abi(JS::VM::the()), new InternalKeyData(move(key_data)));
-}
-
-CryptoKey::InternalKeyData const& CryptoKey::handle() const
-{
- return *web_rust_crypto_key_handle(this);
-}
-
void CryptoKey::set_algorithm(InternalAlgorithmData algorithm)
{
CryptoKeyAlgorithmFields fields;
diff --git a/Libraries/LibWeb/Crypto/CryptoKey.h b/Libraries/LibWeb/Crypto/CryptoKey.h
index c83d89e5aca..6ba78824cba 100644
--- a/Libraries/LibWeb/Crypto/CryptoKey.h
+++ b/Libraries/LibWeb/Crypto/CryptoKey.h
@@ -6,7 +6,6 @@
#pragma once
-#include <LibCrypto/KeyHandle.h>
#include <LibGC/Ptr.h>
#include <LibJS/Forward.h>
#include <LibWeb/Bindings/CryptoKey.h>
@@ -21,9 +20,6 @@ enum class KeyType : u8;
namespace Web::Crypto {
-using ::Crypto::OKPPrivateKey;
-using ::Crypto::OKPPublicKey;
-
using KeyUsage = Bindings::KeyUsage;
enum class KeyType {
@@ -36,8 +32,6 @@ class WEB_API CryptoKey final : public Bindings::RustInterfaceCell {
WEB_RUST_INTERFACE(CryptoKey, crypto_key)
public:
- using InternalKeyData = ::Crypto::KeyHandle;
-
struct KeyAlgorithmData {
Utf16String const& name() const { return m_name; }
@@ -102,8 +96,6 @@ public:
using InternalAlgorithmData = Variant<KeyAlgorithmData, RsaKeyAlgorithmData, RsaHashedKeyAlgorithmData, EcKeyAlgorithmData, AesKeyAlgorithmData, HmacKeyAlgorithmData, KmacKeyAlgorithmData>;
- [[nodiscard]] static GC::Ref<CryptoKey> create(InternalKeyData);
-
bool extractable() const;
KeyType type() const;
@@ -115,7 +107,6 @@ public:
void set_algorithm(InternalAlgorithmData);
void set_usages(Vector<KeyUsage>);
- InternalKeyData const& handle() const;
Utf16String algorithm_name() const;
};
diff --git a/Libraries/LibWeb/Crypto/CryptoKeySerializationTags.h b/Libraries/LibWeb/Crypto/CryptoKeySerializationTags.h
index 6cd17f33dd6..3361eaa1bfa 100644
--- a/Libraries/LibWeb/Crypto/CryptoKeySerializationTags.h
+++ b/Libraries/LibWeb/Crypto/CryptoKeySerializationTags.h
@@ -8,14 +8,26 @@
#include <AK/Array.h>
#include <AK/Types.h>
-#include <LibCrypto/KeyHandle.h>
#include <LibWeb/HTML/StructuredSerializeTypes.h>
namespace Web::Crypto {
// HandleTag and KeyAlgorithmTag values are part of the stable storage serialization format.
// Do not reorder or reuse values; leave removed tags reserved.
-using ::Crypto::HandleTag;
+// These tags identify the key components in stored CryptoKey records.
+enum class HandleTag : u8 {
+ ByteBuffer = 0,
+ RSAPublicKey = 1,
+ RSAPrivateKey = 2,
+ ECPublicKey = 3,
+ ECPrivateKey = 4,
+ MLDSAPublicKey = 5,
+ MLDSAPrivateKey = 6,
+ MLKEMPublicKey = 7,
+ MLKEMPrivateKey = 8,
+ OKPPublicKey = 9,
+ OKPPrivateKey = 10,
+};
enum class KeyAlgorithmTag : u8 {
KeyAlgorithm = 0,
diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.h
index 3ee32a7563c..fec66cd2d21 100644
--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h
+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h
@@ -17,8 +17,6 @@
#include <AK/String.h>
#include <AK/Utf16String.h>
#include <AK/Vector.h>
-#include <LibCrypto/PK/MLDSA.h>
-#include <LibCrypto/PK/MLKEM.h>
#include <LibGC/Root.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/Color.h>
@@ -47,6 +45,9 @@
#include <LibWeb/HTML/Window.h>
#include <LibWeb/Platform/FontPlugin.h>
+#include <openssl/core_names.h>
+#include <openssl/evp.h>
+
using Web::HTML::ValueTag;
template<typename Record>
@@ -673,28 +674,58 @@ inline Vector<CryptoAlgorithmGolden> crypto_algorithm_goldens()
return goldens;
}
-// ML-DSA and ML-KEM key handles must hold real keys, so these come from fixed seeds.
-inline ::Crypto::PK::MLDSA::KeyPairType mldsa_44_key_pair()
+// ML-DSA and ML-KEM key handles must hold real keys, so these come from fixed seeds, made by OpenSSL as Web Crypto
+// makes them.
+struct ModuleLatticeKey {
+ ByteBuffer seed;
+ ByteBuffer public_key;
+ ByteBuffer expanded_key;
+};
+
+inline ByteBuffer octet_string_param_of(EVP_PKEY* key, char const* name)
+{
+ size_t size = 0;
+ VERIFY(EVP_PKEY_get_octet_string_param(key, name, nullptr, 0, &size) == 1);
+ auto bytes = MUST(ByteBuffer::create_uninitialized(size));
+ VERIFY(EVP_PKEY_get_octet_string_param(key, name, bytes.data(), bytes.size(), &size) == 1);
+ return bytes;
+}
+
+inline ModuleLatticeKey module_lattice_key_from_seed(char const* algorithm, ReadonlyBytes seed)
+{
+ auto* context = EVP_PKEY_CTX_new_from_name(nullptr, algorithm, nullptr);
+ VERIFY(context);
+ VERIFY(EVP_PKEY_fromdata_init(context) == 1);
+ OSSL_PARAM params[] {
+ OSSL_PARAM_octet_string("seed", const_cast<u8*>(seed.data()), seed.size()),
+ OSSL_PARAM_END,
+ };
+ EVP_PKEY* key = nullptr;
+ VERIFY(EVP_PKEY_fromdata(context, &key, EVP_PKEY_KEYPAIR, params) == 1);
+ EVP_PKEY_CTX_free(context);
+ ModuleLatticeKey result {
+ MUST(ByteBuffer::copy(seed)),
+ octet_string_param_of(key, OSSL_PKEY_PARAM_PUB_KEY),
+ octet_string_param_of(key, OSSL_PKEY_PARAM_PRIV_KEY),
+ };
+ EVP_PKEY_free(key);
+ return result;
+}
+
+inline ModuleLatticeKey mldsa_44_key(u8 first_seed_byte = 0)
{
Array<u8, 32> seed;
for (size_t i = 0; i < seed.size(); ++i)
- seed[i] = i;
- return MUST(::Crypto::PK::MLDSA::generate_key_pair(::Crypto::PK::MLDSA44, seed));
+ seed[i] = first_seed_byte + i;
+ return module_lattice_key_from_seed("ML-DSA-44", seed);
}
-inline ::Crypto::PK::MLKEM::KeyPairType mlkem_512_key_pair()
+inline ModuleLatticeKey mlkem_512_key()
{
Array<u8, 64> seed;
for (size_t i = 0; i < seed.size(); ++i)
seed[i] = i;
- return MUST(::Crypto::PK::MLKEM::generate_key_pair(::Crypto::PK::MLKEMSize::MLKEM512, seed));
-}
-
-template<typename PrivateKey>
-inline ByteBuffer seed_of(PrivateKey const& key)
-{
- Array<u8, PrivateKey::seed_size> buffer;
- return MUST(ByteBuffer::copy(MUST(key.seed(buffer))));
+ return module_lattice_key_from_seed("ML-KEM-512", seed);
}
inline Vector<CryptoHandleGolden> crypto_handle_goldens()
@@ -706,12 +737,8 @@ inline Vector<CryptoHandleGolden> crypto_handle_goldens()
auto x = p256_base_point_x();
auto y = p256_base_point_y();
auto d = ec_coordinate(0x33);
- auto mldsa = mldsa_44_key_pair();
- auto mldsa_expanded_key = MUST(mldsa.private_key.expanded_key());
- auto mlkem = mlkem_512_key_pair();
- auto mlkem_expanded_key = MUST(mlkem.private_key.expanded_key());
- auto mldsa_seed = seed_of(mldsa.private_key);
- auto mlkem_seed = seed_of(mlkem.private_key);
+ auto mldsa = mldsa_44_key();
+ auto mlkem = mlkem_512_key();
auto okp = "okpokpokpokpokpo"sv.bytes();
Array<ReadonlyBytes, 8> rsa_components { modulus, exponent, exponent, modulus, modulus, exponent, exponent, modulus };
@@ -723,10 +750,10 @@ inline Vector<CryptoHandleGolden> crypto_handle_goldens()
alg_rsa_hashed_key_algorithm("RSASSA-PKCS1-v1_5"sv, 2048, exponent, "SHA-256"sv), handle_rsa_private_key(rsa_components) });
goldens.append({ HandleTag::ECPublicKey, "public"sv, "verify"sv, alg_ec_key_algorithm("ECDSA"sv, "P-256"sv), handle_ec_public_key(x, y) });
goldens.append({ HandleTag::ECPrivateKey, "private"sv, "sign"sv, alg_ec_key_algorithm("ECDSA"sv, "P-256"sv), handle_ec_private_key(d, {}, {}) });
- goldens.append({ HandleTag::MLDSAPublicKey, "public"sv, "verify"sv, alg_key_algorithm("ML-DSA-44"sv), handle_single_buffer(5, mldsa.public_key.public_key()) });
- goldens.append({ HandleTag::MLDSAPrivateKey, "private"sv, "sign"sv, alg_key_algorithm("ML-DSA-44"sv), handle_triple_buffer(6, mldsa_seed, mldsa.private_key.public_key(), mldsa_expanded_key) });
- goldens.append({ HandleTag::MLKEMPublicKey, "public"sv, "encapsulateKey"sv, alg_key_algorithm("ML-KEM-512"sv), handle_single_buffer(7, mlkem.public_key.public_key()) });
- goldens.append({ HandleTag::MLKEMPrivateKey, "private"sv, "decapsulateKey"sv, alg_key_algorithm("ML-KEM-512"sv), handle_triple_buffer(8, mlkem_seed, mlkem.private_key.public_key(), mlkem_expanded_key) });
+ goldens.append({ HandleTag::MLDSAPublicKey, "public"sv, "verify"sv, alg_key_algorithm("ML-DSA-44"sv), handle_single_buffer(5, mldsa.public_key) });
+ goldens.append({ HandleTag::MLDSAPrivateKey, "private"sv, "sign"sv, alg_key_algorithm("ML-DSA-44"sv), handle_triple_buffer(6, mldsa.seed, mldsa.public_key, mldsa.expanded_key) });
+ goldens.append({ HandleTag::MLKEMPublicKey, "public"sv, "encapsulateKey"sv, alg_key_algorithm("ML-KEM-512"sv), handle_single_buffer(7, mlkem.public_key) });
+ goldens.append({ HandleTag::MLKEMPrivateKey, "private"sv, "decapsulateKey"sv, alg_key_algorithm("ML-KEM-512"sv), handle_triple_buffer(8, mlkem.seed, mlkem.public_key, mlkem.expanded_key) });
goldens.append({ HandleTag::OKPPublicKey, "public"sv, "verify"sv, alg_key_algorithm("Ed25519"sv), handle_single_buffer(9, okp) });
goldens.append({ HandleTag::OKPPrivateKey, "private"sv, "sign"sv, alg_key_algorithm("Ed25519"sv), handle_single_buffer(10, okp) });
return goldens;
@@ -742,10 +769,9 @@ inline GC::Ref<Web::Crypto::CryptoKey> build_live_crypto_key(StringView type, St
// Fabricate RsaKeyAlgorithm directly to pin the encode-only tag-1 branch.
inline GC::Ref<Web::Crypto::CryptoKey> build_live_crypto_key_with_rsa_key_algorithm(StringView type, StringView usage, StringView name, u32 modulus_length, ReadonlyBytes public_exponent, ReadonlyBytes modulus)
{
- auto key = Web::Crypto::CryptoKey::create(MUST(::Crypto::PK::RSAPublicKey::from_components(modulus, public_exponent)));
- key->set_type(type == "public"sv ? Web::Crypto::KeyType::Public : (type == "private"sv ? Web::Crypto::KeyType::Private : Web::Crypto::KeyType::Secret));
- key->set_extractable(false);
- key->set_usages({ usage == "verify"sv ? Web::Bindings::KeyUsage::Verify : Web::Bindings::KeyUsage::Sign });
+ // NB: A stored record cannot hold an RsaKeyAlgorithm, so the key is decoded with an RsaHashedKeyAlgorithm and given
+ // the RsaKeyAlgorithm afterwards.
+ auto key = build_live_crypto_key(type, usage, alg_rsa_hashed_key_algorithm(name, modulus_length, public_exponent, "SHA-256"sv), handle_rsa_public_key(modulus, public_exponent));
key->set_algorithm(Web::Crypto::CryptoKey::RsaKeyAlgorithmData {
Utf16String::from_utf8(name),
modulus_length,
diff --git a/Tests/LibWeb/TestStructuredSerializeDurability.cpp b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
index 5db8c8779f1..56479a3e5be 100644
--- a/Tests/LibWeb/TestStructuredSerializeDurability.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
@@ -93,8 +93,7 @@ TEST_CASE(crypto_key_storage_record_round_trips)
EXPECT_EQ(key.algorithm_name(), "HKDF"_string);
EXPECT_EQ(key.internal_usages().size(), 1u);
EXPECT_EQ(key.internal_usages()[0], Web::Bindings::KeyUsage::DeriveKey);
- EXPECT(key.handle().has<ByteBuffer>());
- EXPECT_EQ(key.handle().get<ByteBuffer>().span(), handle);
+ EXPECT_EQ(storage_serialize(GC::Ref { value.as_object() }).data.span(), crypto_key_secret_record(handle, handle.size()).data.span());
}
TEST_CASE(value_tag_primitives_round_trip)
@@ -616,13 +615,9 @@ TEST_CASE(crypto_key_with_an_invalid_ec_point_is_a_data_clone_error)
TEST_CASE(crypto_key_with_an_ml_dsa_seed_that_does_not_match_its_public_key_is_a_data_clone_error)
{
- auto key_pair = mldsa_44_key_pair();
- Array<u8, 32> other_seed;
- other_seed.fill(0xff);
- auto other_key_pair = MUST(::Crypto::PK::MLDSA::generate_key_pair(::Crypto::PK::MLDSA44, other_seed));
- auto expanded_key = MUST(key_pair.private_key.expanded_key());
- auto seed = seed_of(key_pair.private_key);
- auto record = crypto_key_full_record("private"sv, "sign"sv, alg_key_algorithm("ML-DSA-44"sv), handle_triple_buffer(6, seed, other_key_pair.public_key.public_key(), expanded_key));
+ auto key = mldsa_44_key();
+ auto other_key = mldsa_44_key(0xff);
+ auto record = crypto_key_full_record("private"sv, "sign"sv, alg_key_algorithm("ML-DSA-44"sv), handle_triple_buffer(6, key.seed, other_key.public_key, key.expanded_key));
auto& realm = principal_test_realm();
auto result = Web::WebIDL::throw_dom_exception_if_needed(realm.vm(), realm, [&] {
return principal_storage_deserialize(record);
@@ -638,9 +633,7 @@ TEST_CASE(crypto_key_with_an_ml_kem_public_key_that_fails_the_encapsulation_key_
public_key.fill(0xff);
auto record = crypto_key_full_record("public"sv, "encapsulateBits"sv, alg_key_algorithm("ML-KEM-512"sv), handle_single_buffer(7, public_key));
auto value = MUST(principal_storage_deserialize(record));
- auto& key = unwrap_wrappable<Web::Crypto::CryptoKey>(value);
- EXPECT(key.handle().has<::Crypto::PK::MLKEMPublicKey>());
- EXPECT(!key.handle().get<::Crypto::PK::MLKEMPublicKey>().size().has_value());
+ EXPECT_EQ(storage_serialize(GC::Ref { value.as_object() }).data.span(), record.data.span());
}
TEST_CASE(crypto_key_handle_variants_decode_from_frozen_bytes)
@@ -648,43 +641,7 @@ TEST_CASE(crypto_key_handle_variants_decode_from_frozen_bytes)
for (auto const& golden : crypto_handle_goldens()) {
auto record = crypto_key_full_record(golden.type, golden.usage, golden.algorithm, golden.handle);
auto value = MUST(principal_storage_deserialize(record));
- auto& key = unwrap_wrappable<Web::Crypto::CryptoKey>(value);
-
- switch (golden.tag) {
- case HandleTag::ByteBuffer:
- EXPECT(key.handle().has<ByteBuffer>());
- break;
- case HandleTag::RSAPublicKey:
- EXPECT(key.handle().has<::Crypto::PK::RSAPublicKey>());
- break;
- case HandleTag::RSAPrivateKey:
- EXPECT(key.handle().has<::Crypto::PK::RSAPrivateKey>());
- break;
- case HandleTag::ECPublicKey:
- EXPECT(key.handle().has<::Crypto::PK::ECPublicKey>());
- break;
- case HandleTag::ECPrivateKey:
- EXPECT(key.handle().has<::Crypto::PK::ECPrivateKey>());
- break;
- case HandleTag::MLDSAPublicKey:
- EXPECT(key.handle().has<::Crypto::PK::MLDSAPublicKey>());
- break;
- case HandleTag::MLDSAPrivateKey:
- EXPECT(key.handle().has<::Crypto::PK::MLDSAPrivateKey>());
- break;
- case HandleTag::MLKEMPublicKey:
- EXPECT(key.handle().has<::Crypto::PK::MLKEMPublicKey>());
- break;
- case HandleTag::MLKEMPrivateKey:
- EXPECT(key.handle().has<::Crypto::PK::MLKEMPrivateKey>());
- break;
- case HandleTag::OKPPublicKey:
- EXPECT(key.handle().has<Web::Crypto::OKPPublicKey>());
- break;
- case HandleTag::OKPPrivateKey:
- EXPECT(key.handle().has<Web::Crypto::OKPPrivateKey>());
- break;
- }
+ EXPECT_EQ(storage_serialize(GC::Ref { value.as_object() }).data.span(), record.data.span());
}
}
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-EC-jwk-private-key-range.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-EC-jwk-private-key-range.txt
new file mode 100644
index 00000000000..b535135f756
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-EC-jwk-private-key-range.txt
@@ -0,0 +1,4 @@
+d = 1: imported
+d = 0: DataError
+d = the order of the curve: DataError
+d = 31 bytes wide: DataError
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-HKDF-PBKDF2-vectors.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-HKDF-PBKDF2-vectors.txt
new file mode 100644
index 00000000000..6700a66ff95
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-HKDF-PBKDF2-vectors.txt
@@ -0,0 +1,6 @@
+HKDF RFC 5869 A.1: 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
+HKDF RFC 5869 A.3: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8
+HKDF longer than 255 SHA-1 blocks: OperationError
+PBKDF2 RFC 6070 test 1 with SHA-1: 0c60c80f961f0e71f3a9b524af6012062fe037a6
+PBKDF2 RFC 6070 test 1 with SHA-256: 120fb6cffcf8b32c43e7225256c4f837a86548c9
+PBKDF2 with 2^31 iterations: OperationError
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-pkcs8-private-key-forms.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-pkcs8-private-key-forms.txt
index 76af447105a..5f1c3c2f3c6 100644
--- a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-pkcs8-private-key-forms.txt
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-pkcs8-private-key-forms.txt
@@ -3,3 +3,9 @@ expandedKey: NotSupportedError
both: imported
seedWithoutItsTag: DataError
expandedKeyThatIsNotAValidKey: NotSupportedError
+bothWithTheExpandedKeyOfAnotherSeed: DataError
+expandedKeyInAConstructedOctetString: DataError
+seedWithATrailingByte: DataError
+seedWithALongFormLength: DataError
+seedWithAnotherTag: DataError
+bothWithAnExtraElement: DataError
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-OKP-pkcs8-private-key-length.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-OKP-pkcs8-private-key-length.txt
new file mode 100644
index 00000000000..9a770b03fe5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-OKP-pkcs8-private-key-length.txt
@@ -0,0 +1,2 @@
+Ed25519 PKCS#8 with an empty private key: DataError
+Ed25519 PKCS#8 with a 32-byte private key: imported
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-RSA-length-and-exponent-checks.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-RSA-length-and-exponent-checks.txt
new file mode 100644
index 00000000000..e3c2cf6d64d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-RSA-length-and-exponent-checks.txt
@@ -0,0 +1,4 @@
+RSA-OAEP ciphertext one byte short: OperationError
+RSA-PSS signature: true
+RSA-PSS signature one byte short: false
+public exponent 1: DataError
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-cSHAKE-vectors.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-cSHAKE-vectors.txt
new file mode 100644
index 00000000000..8b5ab6134ca
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-cSHAKE-vectors.txt
@@ -0,0 +1,4 @@
+cSHAKE128 without a function name or customization: 5881092dd818bf5cf8a3ddb793fbcba74097d5c526a6d35f97b83351940f2cc8
+cSHAKE128 with customization: c1c36925b6409a04f1b504fcbca9d82b4017277cb5ed2b2065fc1d3814d5aaf5
+cSHAKE256 with customization: d008828e2b80ac9d2218ffee1d070c48b8e4c87bff32c9699d5b6896eee0edd164020e2be0560858d9c00c037e34a96937c561a74c412bb4c746469527281c8c
+cSHAKE128 with a function name: d80243b842232be0bd24267d4181c25d69b286f43a85e1c6f324db0486ae1926
diff --git a/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.txt b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.txt
new file mode 100644
index 00000000000..0ed3847d03c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.txt
@@ -0,0 +1,66 @@
+Harness status: OK
+
+Found 61 tests
+
+61 Pass
+Pass setup
+Pass AES-CBC 128-bit key
+Pass AES-CBC 192-bit key
+Pass AES-CBC 256-bit key
+Pass AES-CBC 128-bit key with altered plaintext during call
+Pass AES-CBC 192-bit key with altered plaintext during call
+Pass AES-CBC 256-bit key with altered plaintext during call
+Pass AES-CBC 128-bit key with altered plaintext after call
+Pass AES-CBC 192-bit key with altered plaintext after call
+Pass AES-CBC 256-bit key with altered plaintext after call
+Pass AES-CBC 128-bit key with transferred plaintext during call
+Pass AES-CBC 192-bit key with transferred plaintext during call
+Pass AES-CBC 256-bit key with transferred plaintext during call
+Pass AES-CBC 128-bit key with transferred plaintext after call
+Pass AES-CBC 192-bit key with transferred plaintext after call
+Pass AES-CBC 256-bit key with transferred plaintext after call
+Pass AES-CBC 128-bit key decryption
+Pass AES-CBC 192-bit key decryption
+Pass AES-CBC 256-bit key decryption
+Pass AES-CBC 128-bit key decryption with altered ciphertext during call
+Pass AES-CBC 192-bit key decryption with altered ciphertext during call
+Pass AES-CBC 256-bit key decryption with altered ciphertext during call
+Pass AES-CBC 128-bit key decryption with altered ciphertext after call
+Pass AES-CBC 192-bit key decryption with altered ciphertext after call
+Pass AES-CBC 256-bit key decryption with altered ciphertext after call
+Pass AES-CBC 128-bit key decryption with transferred ciphertext during call
+Pass AES-CBC 192-bit key decryption with transferred ciphertext during call
+Pass AES-CBC 256-bit key decryption with transferred ciphertext during call
+Pass AES-CBC 128-bit key decryption with transferred ciphertext after call
+Pass AES-CBC 192-bit key decryption with transferred ciphertext after call
+Pass AES-CBC 256-bit key decryption with transferred ciphertext after call
+Pass AES-CBC 128-bit key without encrypt usage
+Pass AES-CBC 192-bit key without encrypt usage
+Pass AES-CBC 256-bit key without encrypt usage
+Pass AES-CBC 128-bit key with mismatched key and algorithm
+Pass AES-CBC 192-bit key with mismatched key and algorithm
+Pass AES-CBC 256-bit key with mismatched key and algorithm
+Pass AES-CBC 128-bit key without decrypt usage
+Pass AES-CBC 192-bit key without decrypt usage
+Pass AES-CBC 256-bit key without decrypt usage
+Pass AES-CBC 128-bit key, 64-bit IV
+Pass AES-CBC 128-bit key, 192-bit IV
+Pass AES-CBC 192-bit key, 64-bit IV
+Pass AES-CBC 192-bit key, 192-bit IV
+Pass AES-CBC 256-bit key, 64-bit IV
+Pass AES-CBC 256-bit key, 192-bit IV
+Pass AES-CBC 128-bit key, 64-bit IV decryption
+Pass AES-CBC 128-bit key, 192-bit IV decryption
+Pass AES-CBC 192-bit key, 64-bit IV decryption
+Pass AES-CBC 192-bit key, 192-bit IV decryption
+Pass AES-CBC 256-bit key, 64-bit IV decryption
+Pass AES-CBC 256-bit key, 192-bit IV decryption
+Pass AES-CBC 128-bit key, zeroPadChar
+Pass AES-CBC 128-bit key, bigPadChar
+Pass AES-CBC 128-bit key, inconsistentPadChars
+Pass AES-CBC 192-bit key, zeroPadChar
+Pass AES-CBC 192-bit key, bigPadChar
+Pass AES-CBC 192-bit key, inconsistentPadChars
+Pass AES-CBC 256-bit key, zeroPadChar
+Pass AES-CBC 256-bit key, bigPadChar
+Pass AES-CBC 256-bit key, inconsistentPadChars
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.txt b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.txt
new file mode 100644
index 00000000000..fc63144d631
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.txt
@@ -0,0 +1,57 @@
+Harness status: OK
+
+Found 52 tests
+
+52 Pass
+Pass setup
+Pass AES-CTR 128-bit key
+Pass AES-CTR 192-bit key
+Pass AES-CTR 256-bit key
+Pass AES-CTR 128-bit key with altered plaintext during call
+Pass AES-CTR 192-bit key with altered plaintext during call
+Pass AES-CTR 256-bit key with altered plaintext during call
+Pass AES-CTR 128-bit key with altered plaintext after call
+Pass AES-CTR 192-bit key with altered plaintext after call
+Pass AES-CTR 256-bit key with altered plaintext after call
+Pass AES-CTR 128-bit key with transferred plaintext during call
+Pass AES-CTR 192-bit key with transferred plaintext during call
+Pass AES-CTR 256-bit key with transferred plaintext during call
+Pass AES-CTR 128-bit key with transferred plaintext after call
+Pass AES-CTR 192-bit key with transferred plaintext after call
+Pass AES-CTR 256-bit key with transferred plaintext after call
+Pass AES-CTR 128-bit key decryption
+Pass AES-CTR 192-bit key decryption
+Pass AES-CTR 256-bit key decryption
+Pass AES-CTR 128-bit key decryption with altered ciphertext during call
+Pass AES-CTR 192-bit key decryption with altered ciphertext during call
+Pass AES-CTR 256-bit key decryption with altered ciphertext during call
+Pass AES-CTR 128-bit key decryption with altered ciphertext after call
+Pass AES-CTR 192-bit key decryption with altered ciphertext after call
+Pass AES-CTR 256-bit key decryption with altered ciphertext after call
+Pass AES-CTR 128-bit key decryption with transferred ciphertext during call
+Pass AES-CTR 192-bit key decryption with transferred ciphertext during call
+Pass AES-CTR 256-bit key decryption with transferred ciphertext during call
+Pass AES-CTR 128-bit key decryption with transferred ciphertext after call
+Pass AES-CTR 192-bit key decryption with transferred ciphertext after call
+Pass AES-CTR 256-bit key decryption with transferred ciphertext after call
+Pass AES-CTR 128-bit key without encrypt usage
+Pass AES-CTR 192-bit key without encrypt usage
+Pass AES-CTR 256-bit key without encrypt usage
+Pass AES-CTR 128-bit key with mismatched key and algorithm
+Pass AES-CTR 192-bit key with mismatched key and algorithm
+Pass AES-CTR 256-bit key with mismatched key and algorithm
+Pass AES-CTR 128-bit key without decrypt usage
+Pass AES-CTR 192-bit key without decrypt usage
+Pass AES-CTR 256-bit key without decrypt usage
+Pass AES-CTR 128-bit key, 0-bit counter
+Pass AES-CTR 128-bit key, 129-bit counter
+Pass AES-CTR 192-bit key, 0-bit counter
+Pass AES-CTR 192-bit key, 129-bit counter
+Pass AES-CTR 256-bit key, 0-bit counter
+Pass AES-CTR 256-bit key, 129-bit counter
+Pass AES-CTR 128-bit key, 0-bit counter decryption
+Pass AES-CTR 128-bit key, 129-bit counter decryption
+Pass AES-CTR 192-bit key, 0-bit counter decryption
+Pass AES-CTR 192-bit key, 129-bit counter decryption
+Pass AES-CTR 256-bit key, 0-bit counter decryption
+Pass AES-CTR 256-bit key, 129-bit counter decryption
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-EC-jwk-private-key-range.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-EC-jwk-private-key-range.html
new file mode 100644
index 00000000000..0b27186ffb8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-EC-jwk-private-key-range.html
@@ -0,0 +1,32 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ const base64url = hex =>
+ btoa(String.fromCharCode(...hex.match(/../g).map(byte => parseInt(byte, 16))))
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=+$/, "");
+
+ // The P-256 base point, whose private key is 1.
+ const x = base64url("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296");
+ const y = base64url("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5");
+ const order = "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551";
+
+ promiseTest(async () => {
+ const values = [
+ ["1", "00".repeat(31) + "01"],
+ ["0", "00".repeat(32)],
+ ["the order of the curve", order],
+ ["31 bytes wide", "00".repeat(30) + "01"],
+ ];
+ for (const [name, d] of values) {
+ const jwk = { kty: "EC", crv: "P-256", x, y, d: base64url(d) };
+ try {
+ await crypto.subtle.importKey("jwk", jwk, { name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]);
+ println(`d = ${name}: imported`);
+ } catch (error) {
+ println(`d = ${name}: ${error.name}`);
+ }
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-HKDF-PBKDF2-vectors.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-HKDF-PBKDF2-vectors.html
new file mode 100644
index 00000000000..c88ea459202
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-HKDF-PBKDF2-vectors.html
@@ -0,0 +1,66 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ const hex = bytes => Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, "0")).join("");
+ const bytes = string => Uint8Array.from(string.match(/../g) ?? [], byte => parseInt(byte, 16));
+ const text = string => new TextEncoder().encode(string);
+
+ async function deriveBits(name, keyData, parameters, length) {
+ const key = await crypto.subtle.importKey("raw", keyData, name, false, ["deriveBits"]);
+ try {
+ return hex(await crypto.subtle.deriveBits({ name, ...parameters }, key, length));
+ } catch (error) {
+ return error.name;
+ }
+ }
+
+ promiseTest(async () => {
+ const ikm = bytes("0b".repeat(22));
+ // https://www.rfc-editor.org/rfc/rfc5869#appendix-A.1
+ println(
+ `HKDF RFC 5869 A.1: ${await deriveBits(
+ "HKDF",
+ ikm,
+ { hash: "SHA-256", salt: bytes("000102030405060708090a0b0c"), info: bytes("f0f1f2f3f4f5f6f7f8f9") },
+ 42 * 8
+ )}`
+ );
+ // https://www.rfc-editor.org/rfc/rfc5869#appendix-A.3
+ println(
+ `HKDF RFC 5869 A.3: ${await deriveBits(
+ "HKDF",
+ ikm,
+ { hash: "SHA-256", salt: new Uint8Array(), info: new Uint8Array() },
+ 42 * 8
+ )}`
+ );
+ println(
+ `HKDF longer than 255 SHA-1 blocks: ${await deriveBits(
+ "HKDF",
+ ikm,
+ { hash: "SHA-1", salt: new Uint8Array(), info: new Uint8Array() },
+ 256 * 20 * 8
+ )}`
+ );
+
+ // https://www.rfc-editor.org/rfc/rfc6070#section-2
+ for (const hash of ["SHA-1", "SHA-256"]) {
+ println(
+ `PBKDF2 RFC 6070 test 1 with ${hash}: ${await deriveBits(
+ "PBKDF2",
+ text("password"),
+ { hash, salt: text("salt"), iterations: 1 },
+ 20 * 8
+ )}`
+ );
+ }
+ println(
+ `PBKDF2 with 2^31 iterations: ${await deriveBits(
+ "PBKDF2",
+ text("password"),
+ { hash: "SHA-256", salt: text("salt"), iterations: 0x80000000 },
+ 8
+ )}`
+ );
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-pkcs8-private-key-forms.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-pkcs8-private-key-forms.html
index bd0fb86df02..93a922e4ef8 100644
--- a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-pkcs8-private-key-forms.html
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-pkcs8-private-key-forms.html
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<script src="../include.js"></script>
<script>
function der(tag, bytes) {
@@ -13,7 +13,12 @@
// The ML-KEM-512 key generated from the seed 0, 1, ..., 63.
const seed = Array.from({ length: 64 }, (_, i) => i);
- const expandedKey = Array.from(atob("cFVP1DY0TyeFsbOxusGEtmeQAzNsJvFafeh4xIJca+A/PEpID3W3SGqtMdOgBRhiP9IHq1KN1ichSVg1rgBiw2e3SnG68QqtDoopAgdr4xNIvrFczAlXzeu0r/ImdWu8YBtlaKt4Ssuus0cC8PhqJiAhGLIrI/g1WHdsecFNupgzecgD4NzDFgoRdXAw5pxpGXmNgetpippEg6meWlyywxyaZheZ88yJx5BwbqBBYpBF1CqDrtiIYOOUxpGH4hBdKMwU7Dk1ktZ90AqkP+i06uRBQAKGa1xxPGqNfRbPeLgZ1vEunlp0IzkI8LFePEuoMpxc3aVchJKOOqgGPlqpZ2QD+Rc1sRAQx/WTCRNk3IZEW8gEhAqaIXJCEkafinsM4KxpjrhsrTmn9IJNmlFjqsIe5oCLBTyKP6ywtnRLUmK7yyakP2ZMhzK2TPx6zwmWBfQceWBgl2rEM4M/4AND+xgoMApCR0ERbktFuyduqBEpoNtMbmC85hEQHoxiVHSSXgIiZ5MIo+dwjRlyp7Qj6yMoUcNtLtU9PtO7dQBjcGGl3CKS+hxGbAc1RoMyi+wsHtLLXJm3jsoJaQOM98NN0RhyTjHK4IYgazQwK1IPXRd63tWzzOAqzOgI6ia8wHJiX9uT8XRYpfwdTaOUOAofV+nMZhCUOKB18NKBP8xKGZzHbbOCPycLAGFZQZKUBBGjf/uvriwVAWXOxca/c8WV+5LNFTEmB9oHB3hlK9mUS8SLx9GlNDOLrQutZlbF1QLOeFCrFYckTutY9DmrXghXSnGMiqw9d8eYu6FUJzO+c0SPI/twwOU1OifIgyLFIYSTr7s4CGQ01tYKVrqIfdSYw6smoIcJk4FapqQJdfIYrcoVgtZP/IZS+7OppvvDBPkZRfpKrvKHj9cV33ARPSN59EiG+BLIP/K3GaaeHsdK5LFazNOu1aU852p7CYJHFjO5c8tAoaABXQpCT6EaR5wCMBdDbSopAOmT61oKBnQAx/Sq3yAfxPoxJkpjuulcyNZcOZWBXll9EENVzymqUzPJMlGGnVvNvkhxJPYCuLambBbEdhZIrXZc9dgAa1FekFp/CsB2sMYu+jKBU+fKVwFpnxMF8ea8b5Cw5JtpNRK2zpkqi4AW3fwaZix+P5YZy9hp3Xca8wiWzNWRisbLd0ZsXneZltZ/+aq8l1A/LHt+LQANhkUPsYB8pMq9pGWCWjHHiaG3pJGrOHJ2XTINC3GSD6ITyUCTQWuDuBJOafZeYstQANzDeqmg//c5cMR3LzV9JBicpvUwVWjA4jdqN2KmjGBeVjxdIJVy4Px1MsopRylTVWe1/EE8XoeS0kZFNsyAj5it10Zk8UFWb5AWqQpUGCmpigRkzkGou0TC1Po8LCCUYHKO8UoafEybmNEiA7TMNSkWCpqy14OPf/a1OuBaoxp9ZGt6+mxFkyUmo8N1Vhm+mUwhHCoxwFs0R4NsshUL4YKdrmsExVNc/1RuOSunl0EXIPkk9JClrFSV8hNW1VC3gqZMFoi2tlW8x4Qhl6Q0wvZWO1t/CaeLzEiCMng1YdFvTLq2dVQABQeBVwxmYEuBetElIpRzbosBhhpLWnRRm4tv5RSJpQcjkuWHYmxxN3ZXXTOAahyOJzKvl8JoD1FmYzHE64u8BDHE+Wgy2vGzxFUo+6FT9seLHBmHApR8zTN3J6RvtTuhHeXLQZE0aFlRbLatckAPPPIJsjau81pYCsh+s+MPr9Zpc8qKfdJnWvQfehe2FDPNGvgPdwiGn2ZUiEl5gLGsEKDNy2NqAO2GgbNeQpEkyoA1ByW4X4Ol6sOko8wWAJA+ZSk1YLmzNuWvDVKdrBoEgRkwLLepvMEQuUhRvwIRfxmdxIWoUrdHPwm4MaaDHVtUwLeQ0iXPa7ktlGKibNsz3aUSPHqvDiaguDZV7qKL86gHRyUBj9a65LYBz2G6q3Gno9NRl6ND50tKJywSXVQIlkJthbeVjTs4prqYfsNyJce0TNsS3eRTm0qwgjY2g/BL96CcxcQd/oMKGxYuCzJDNDYvCEoURncjNEut0AD42MU3xI+ZjwUwfOvR7eC4HDvFmgZaG21jsmyC8QH/ZIBjs3biu2xbdFX2VaUML+ra3hUO+g4ObzZa6iAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/"), c => c.charCodeAt(0));
+ const expandedKey = Array.from(
+ atob(
+ "cFVP1DY0TyeFsbOxusGEtmeQAzNsJvFafeh4xIJca+A/PEpID3W3SGqtMdOgBRhiP9IHq1KN1ichSVg1rgBiw2e3SnG68QqtDoopAgdr4xNIvrFczAlXzeu0r/ImdWu8YBtlaKt4Ssuus0cC8PhqJiAhGLIrI/g1WHdsecFNupgzecgD4NzDFgoRdXAw5pxpGXmNgetpippEg6meWlyywxyaZheZ88yJx5BwbqBBYpBF1CqDrtiIYOOUxpGH4hBdKMwU7Dk1ktZ90AqkP+i06uRBQAKGa1xxPGqNfRbPeLgZ1vEunlp0IzkI8LFePEuoMpxc3aVchJKOOqgGPlqpZ2QD+Rc1sRAQx/WTCRNk3IZEW8gEhAqaIXJCEkafinsM4KxpjrhsrTmn9IJNmlFjqsIe5oCLBTyKP6ywtnRLUmK7yyakP2ZMhzK2TPx6zwmWBfQceWBgl2rEM4M/4AND+xgoMApCR0ERbktFuyduqBEpoNtMbmC85hEQHoxiVHSSXgIiZ5MIo+dwjRlyp7Qj6yMoUcNtLtU9PtO7dQBjcGGl3CKS+hxGbAc1RoMyi+wsHtLLXJm3jsoJaQOM98NN0RhyTjHK4IYgazQwK1IPXRd63tWzzOAqzOgI6ia8wHJiX9uT8XRYpfwdTaOUOAofV+nMZhCUOKB18NKBP8xKGZzHbbOCPycLAGFZQZKUBBGjf/uvriwVAWXOxca/c8WV+5LNFTEmB9oHB3hlK9mUS8SLx9GlNDOLrQutZlbF1QLOeFCrFYckTutY9DmrXghXSnGMiqw9d8eYu6FUJzO+c0SPI/twwOU1OifIgyLFIYSTr7s4CGQ01tYKVrqIfdSYw6smoIcJk4FapqQJdfIYrcoVgtZP/IZS+7OppvvDBPkZRfpKrvKHj9cV33ARPSN59EiG+BLIP/K3GaaeHsdK5LFazNOu1aU852p7CYJHFjO5c8tAoaABXQpCT6EaR5wCMBdDbSopAOmT61oKBnQAx/Sq3yAfxPoxJkpjuulcyNZcOZWBXll9EENVzymqUzPJMlGGnVvNvkhxJPYCuLambBbEdhZIrXZc9dgAa1FekFp/CsB2sMYu+jKBU+fKVwFpnxMF8ea8b5Cw5JtpNRK2zpkqi4AW3fwaZix+P5YZy9hp3Xca8wiWzNWRisbLd0ZsXneZltZ/+aq8l1A/LHt+LQANhkUPsYB8pMq9pGWCWjHHiaG3pJGrOHJ2XTINC3GSD6ITyUCTQWuDuBJOafZeYstQANzDeqmg//c5cMR3LzV9JBicpvUwVWjA4jdqN2KmjGBeVjxdIJVy4Px1MsopRylTVWe1/EE8XoeS0kZFNsyAj5it10Zk8UFWb5AWqQpUGCmpigRkzkGou0TC1Po8LCCUYHKO8UoafEybmNEiA7TMNSkWCpqy14OPf/a1OuBaoxp9ZGt6+mxFkyUmo8N1Vhm+mUwhHCoxwFs0R4NsshUL4YKdrmsExVNc/1RuOSunl0EXIPkk9JClrFSV8hNW1VC3gqZMFoi2tlW8x4Qhl6Q0wvZWO1t/CaeLzEiCMng1YdFvTLq2dVQABQeBVwxmYEuBetElIpRzbosBhhpLWnRRm4tv5RSJpQcjkuWHYmxxN3ZXXTOAahyOJzKvl8JoD1FmYzHE64u8BDHE+Wgy2vGzxFUo+6FT9seLHBmHApR8zTN3J6RvtTuhHeXLQZE0aFlRbLatckAPPPIJsjau81pYCsh+s+MPr9Zpc8qKfdJnWvQfehe2FDPNGvgPdwiGn2ZUiEl5gLGsEKDNy2NqAO2GgbNeQpEkyoA1ByW4X4Ol6sOko8wWAJA+ZSk1YLmzNuWvDVKdrBoEgRkwLLepvMEQuUhRvwIRfxmdxIWoUrdHPwm4MaaDHVtUwLeQ0iXPa7ktlGKibNsz3aUSPHqvDiaguDZV7qKL86gHRyUBj9a65LYBz2G6q3Gno9NRl6ND50tKJywSXVQIlkJthbeVjTs4prqYfsNyJce0TNsS3eRTm0qwgjY2g/BL96CcxcQd/oMKGxYuCzJDNDYvCEoURncjNEut0AD42MU3xI+ZjwUwfOvR7eC4HDvFmgZaG21jsmyC8QH/ZIBjs3biu2xbdFX2VaUML+ra3hUO+g4ObzZa6iAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/"
+ ),
+ c => c.charCodeAt(0)
+ );
const forms = {
seed: der(0x80, seed),
@@ -21,12 +26,20 @@
both: der(0x30, [...der(0x04, seed), ...der(0x04, expandedKey)]),
seedWithoutItsTag: seed,
expandedKeyThatIsNotAValidKey: der(0x04, new Array(1632).fill(0)),
+ bothWithTheExpandedKeyOfAnotherSeed: der(0x30, [...der(0x04, seed.toReversed()), ...der(0x04, expandedKey)]),
+ expandedKeyInAConstructedOctetString: der(0x24, der(0x04, expandedKey)),
+ seedWithATrailingByte: [...der(0x80, seed), 0x00],
+ seedWithALongFormLength: [0x80, 0x81, 0x40, ...seed],
+ seedWithAnotherTag: der(0x81, seed),
+ bothWithAnExtraElement: der(0x30, [...der(0x04, seed), ...der(0x04, expandedKey), 0x05, 0x00]),
};
asyncTest(async done => {
for (const [name, privateKey] of Object.entries(forms)) {
try {
- await crypto.subtle.importKey("pkcs8", privateKeyInfo(privateKey), "ML-KEM-512", true, ["decapsulateBits"]);
+ await crypto.subtle.importKey("pkcs8", privateKeyInfo(privateKey), "ML-KEM-512", true, [
+ "decapsulateBits",
+ ]);
println(`${name}: imported`);
} catch (e) {
println(`${name}: ${e.name}`);
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-OKP-pkcs8-private-key-length.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-OKP-pkcs8-private-key-length.html
new file mode 100644
index 00000000000..b98bd49d127
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-OKP-pkcs8-private-key-length.html
@@ -0,0 +1,20 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ const hex = string => Uint8Array.from(string.match(/../g), byte => parseInt(byte, 16));
+
+ promiseTest(async () => {
+ const keys = [
+ ["an empty private key", "300e020100300506032b65700402" + "0400"],
+ ["a 32-byte private key", "302e020100300506032b657004220420" + "00".repeat(32)],
+ ];
+ for (const [name, der] of keys) {
+ try {
+ await crypto.subtle.importKey("pkcs8", hex(der), { name: "Ed25519" }, true, ["sign"]);
+ println(`Ed25519 PKCS#8 with ${name}: imported`);
+ } catch (error) {
+ println(`Ed25519 PKCS#8 with ${name}: ${error.name}`);
+ }
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-RSA-length-and-exponent-checks.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-RSA-length-and-exponent-checks.html
new file mode 100644
index 00000000000..a4585254fe2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-RSA-length-and-exponent-checks.html
@@ -0,0 +1,41 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ const generate = async (name, usages) =>
+ crypto.subtle.generateKey(
+ { name, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
+ true,
+ usages
+ );
+
+ promiseTest(async () => {
+ const message = new Uint8Array([1, 2, 3]);
+
+ const oaep = await generate("RSA-OAEP", ["encrypt", "decrypt"]);
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, oaep.publicKey, message));
+ try {
+ await crypto.subtle.decrypt({ name: "RSA-OAEP" }, oaep.privateKey, ciphertext.slice(1));
+ println("RSA-OAEP ciphertext one byte short: decrypted");
+ } catch (error) {
+ println(`RSA-OAEP ciphertext one byte short: ${error.name}`);
+ }
+
+ const pss = await generate("RSA-PSS", ["sign", "verify"]);
+ const algorithm = { name: "RSA-PSS", saltLength: 32 };
+ const signature = new Uint8Array(await crypto.subtle.sign(algorithm, pss.privateKey, message));
+ println(`RSA-PSS signature: ${await crypto.subtle.verify(algorithm, pss.publicKey, signature, message)}`);
+ println(
+ `RSA-PSS signature one byte short: ${await crypto.subtle.verify(algorithm, pss.publicKey, signature.slice(1), message)}`
+ );
+
+ const jwk = await crypto.subtle.exportKey("jwk", pss.publicKey);
+ try {
+ await crypto.subtle.importKey("jwk", { ...jwk, e: "AQ" }, { name: "RSA-PSS", hash: "SHA-256" }, true, [
+ "verify",
+ ]);
+ println("public exponent 1: imported");
+ } catch (error) {
+ println(`public exponent 1: ${error.name}`);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-cSHAKE-vectors.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-cSHAKE-vectors.html
new file mode 100644
index 00000000000..dabcda64cfb
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-cSHAKE-vectors.html
@@ -0,0 +1,33 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ const hex = bytes => Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, "0")).join("");
+ const text = string => new TextEncoder().encode(string);
+
+ promiseTest(async () => {
+ const vectors = [
+ ["cSHAKE128 without a function name or customization", "cSHAKE128", 256, text("abc"), {}],
+ // NIST SP 800-185 cSHAKE sample #1
+ [
+ "cSHAKE128 with customization",
+ "cSHAKE128",
+ 256,
+ new Uint8Array([0, 1, 2, 3]),
+ { customization: text("Email Signature") },
+ ],
+ // NIST SP 800-185 cSHAKE sample #3
+ [
+ "cSHAKE256 with customization",
+ "cSHAKE256",
+ 512,
+ new Uint8Array([0, 1, 2, 3]),
+ { customization: text("Email Signature") },
+ ],
+ ["cSHAKE128 with a function name", "cSHAKE128", 256, text("hello"), { functionName: text("KMAC") }],
+ ];
+ for (const [description, name, length, data, parameters] of vectors) {
+ const digest = await crypto.subtle.digest({ name, outputLength: length, ...parameters }, data);
+ println(`${description}: ${hex(digest)}`);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.html b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.html
new file mode 100644
index 00000000000..163c225743f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>WebCryptoAPI: encrypt() Using AES-CBC</title>
+<meta name="timeout" content="long">
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="../util/helpers.js"></script>
+<script src="aes_common_fixtures.js"></script>
+<script src="aes_cbc_vectors.js"></script>
+<script src="aes.js"></script>
+<div id=log></div>
+<script src="../../WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.js b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.js
new file mode 100644
index 00000000000..9dcbfbdeccb
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc.https.any.js
@@ -0,0 +1,8 @@
+// META: title=WebCryptoAPI: encrypt() Using AES-CBC
+// META: script=../util/helpers.js
+// META: script=aes_common_fixtures.js
+// META: script=aes_cbc_vectors.js
+// META: script=aes.js
+// META: timeout=long
+
+run_test();
diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc_vectors.js b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc_vectors.js
new file mode 100644
index 00000000000..6bc7b3bf4b7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_cbc_vectors.js
@@ -0,0 +1,211 @@
+
+// aes_cbc_vectors.js
+
+// The following function returns an array of test vectors
+// for the subtleCrypto encrypt method.
+//
+// Each test vector has the following fields:
+// name - a unique name for this vector
+// keyBuffer - an arrayBuffer with the key data in raw form
+// key - a CryptoKey object for the keyBuffer. INITIALLY null! You must fill this in first to use it!
+// algorithm - the value of the AlgorithmIdentifier parameter to provide to encrypt
+// plaintext - the text to encrypt
+// result - the expected result (usually just ciphertext, sometimes with added authentication)
+function getTestVectors() {
+ var commonFixtures = getAesCommonFixtures();
+ var plaintext = commonFixtures.plaintext;
+ var keyBytes = commonFixtures.keyBytes;
+
+ // AES-CBC needs a 16 byte (128 bit) IV.
+ var iv = new Uint8Array([85, 170, 248, 155, 168, 148, 19, 213, 78, 167, 39,
+ 167, 108, 39, 162, 132]);
+
+
+ // Results. These were created using the Python cryptography module.
+
+ // AES-CBC produces ciphertext
+ var ciphertext = {
+ 128: new Uint8Array([35, 127, 3, 254, 231, 8, 114, 231, 143, 174, 193,
+ 72, 221, 189, 1, 189, 119, 203, 150, 227, 56, 30, 244, 236, 226, 175,
+ 234, 23, 167, 175, 211, 124, 203, 228, 97, 223, 156, 77, 88, 174,
+ 166, 187, 186, 225, 176, 92, 250, 177, 225, 41, 135, 124, 215, 86,
+ 198, 134, 124, 49, 154, 60, 224, 93, 165, 12, 190, 245, 241, 164,
+ 247, 220, 227, 69, 242, 105, 208, 108, 222, 193, 223, 0, 226, 217,
+ 39, 160, 78, 147, 191, 38, 153, 232, 206, 221, 254, 25, 185, 249, 7,
+ 181, 215, 104, 98, 163, 194, 161, 103, 161, 237, 167, 10, 242, 37,
+ 80, 2, 255, 173, 96, 20, 106, 170, 110, 80, 38, 136, 127, 16, 85,
+ 244, 78, 172, 56, 106, 3, 115, 130, 58, 186, 129, 236, 255, 251,
+ 178, 112, 24, 159, 82, 252, 1, 178, 132, 92, 40, 125, 18, 135, 116,
+ 64, 178, 31, 174, 87, 114, 114, 218, 78, 111, 0, 239, 252, 79, 63,
+ 119, 58, 118, 78, 55, 249, 36, 130, 225, 205, 13, 76, 97, 214, 250,
+ 174, 232, 67, 103, 211, 178, 206, 32, 129, 188, 243, 100, 71, 63,
+ 154, 159, 200, 125, 34, 138, 39, 73, 130, 75, 97, 203, 204, 111,
+ 244, 75, 186, 181, 43, 207, 175, 146, 98, 207, 27, 23, 90, 144, 161,
+ 19, 235, 199, 93, 98, 238, 72, 134, 157, 220, 207, 66, 167, 236, 94,
+ 57, 0, 3, 202, 250, 55, 26, 163, 20, 133, 191, 67, 20, 63, 150, 203,
+ 87, 216, 44, 57, 188, 236, 64, 80, 111, 68, 26, 12, 10, 163, 82, 3,
+ 191, 19, 71, 186, 196, 177, 84, 244, 7, 78, 41, 172, 203, 27, 225,
+ 231, 108, 206, 141, 221, 253, 204, 220, 134, 20, 130, 54, 113, 81,
+ 127, 197, 27, 101, 121, 159, 223, 193, 115, 190, 12, 153, 174, 231,
+ 196, 92, 142, 156, 61, 189, 3, 18, 153, 206, 190, 58, 255, 154, 115,
+ 66, 23, 107, 94, 220, 156, 220, 228, 241, 66, 6, 184, 44, 238, 249,
+ 51, 240, 109, 142, 208, 189, 11, 117, 70, 170, 217, 170, 216, 66,
+ 231, 18, 175, 121, 221, 16, 29, 139, 55, 103, 91, 239, 111, 29, 108,
+ 94, 179, 138, 134, 73, 130, 29, 69, 182, 192, 249, 150, 165, 79, 47,
+ 91, 203, 226, 63, 87, 52, 60, 172, 191, 190, 179, 171, 155, 205, 88,
+ 172, 111, 59, 40, 198, 250, 209, 148, 177, 115, 200, 40, 43, 165,
+ 167, 67, 116, 64, 159, 240, 81, 253, 235, 137, 132, 49, 223, 214,
+ 172, 53, 7, 47, 184, 223, 120, 59, 51, 33, 124, 147, 221, 27, 60,
+ 16, 254, 24, 115, 115, 214, 75, 73, 97, 136, 214, 209, 177, 106, 71,
+ 254, 211, 94, 57, 104, 170, 168, 35, 37, 93, 203, 199, 38, 28, 84]),
+
+ 192: new Uint8Array([131, 160, 2, 14, 214, 229, 41, 230, 47, 99, 83,
+ 193, 62, 133, 172, 195, 127, 61, 247, 80, 71, 167, 37, 184, 230,
+ 207, 168, 163, 139, 145, 18, 225, 205, 134, 87, 138, 80, 247, 166,
+ 176, 177, 18, 71, 88, 193, 56, 45, 96, 36, 78, 134, 212, 9, 250, 217,
+ 24, 207, 215, 111, 72, 114, 203, 27, 188, 122, 34, 212, 191, 88, 72,
+ 22, 194, 224, 217, 236, 201, 191, 236, 214, 231, 90, 244, 100, 153,
+ 211, 35, 182, 205, 128, 84, 79, 161, 53, 166, 236, 196, 181, 163,
+ 140, 255, 80, 59, 49, 71, 170, 118, 14, 100, 40, 105, 184, 187, 41,
+ 198, 180, 135, 69, 211, 69, 74, 132, 243, 76, 144, 102, 90, 155,
+ 243, 125, 140, 190, 20, 9, 232, 188, 198, 221, 148, 13, 53, 155, 91,
+ 34, 235, 24, 121, 109, 48, 242, 142, 8, 160, 223, 242, 163, 98, 198,
+ 131, 164, 160, 79, 27, 210, 216, 192, 228, 27, 4, 254, 222, 195, 14,
+ 77, 72, 225, 151, 114, 38, 130, 143, 6, 17, 138, 229, 193, 114, 169,
+ 2, 108, 225, 35, 37, 232, 200, 167, 147, 251, 210, 138, 243, 44, 48,
+ 12, 84, 192, 169, 108, 0, 113, 77, 160, 218, 96, 4, 138, 171, 207,
+ 20, 189, 146, 255, 206, 68, 160, 87, 127, 3, 83, 182, 203, 116, 59,
+ 24, 186, 79, 68, 220, 161, 85, 227, 29, 118, 134, 128, 187, 29, 128,
+ 121, 120, 64, 211, 30, 255, 52, 187, 185, 216, 151, 30, 10, 165,
+ 203, 148, 39, 224, 14, 173, 199, 57, 0, 194, 79, 115, 206, 159, 43,
+ 13, 36, 169, 97, 144, 32, 0, 207, 230, 16, 162, 156, 166, 34, 150,
+ 12, 93, 141, 164, 181, 194, 10, 47, 139, 82, 75, 42, 23, 224, 3, 92,
+ 151, 154, 249, 170, 57, 141, 113, 32, 52, 158, 218, 49, 242, 134,
+ 65, 69, 203, 71, 19, 133, 125, 117, 1, 207, 210, 224, 130, 45, 37,
+ 42, 181, 139, 34, 85, 8, 67, 165, 249, 180, 89, 3, 60, 152, 1, 231,
+ 49, 1, 124, 243, 81, 44, 72, 232, 239, 129, 75, 108, 4, 169, 132,
+ 73, 183, 21, 29, 46, 94, 138, 83, 190, 131, 146, 65, 104, 107, 251,
+ 218, 95, 227, 94, 145, 70, 0, 2, 252, 59, 188, 58, 150, 203, 148,
+ 100, 219, 36, 182, 81, 237, 138, 160, 83, 151, 119, 11, 216, 122,
+ 134, 189, 246, 251, 192, 41, 158, 125, 247, 190, 32, 173, 104, 9,
+ 58, 223, 97, 212, 48, 62, 3, 112, 21, 74, 206, 87, 182, 110, 197,
+ 67, 68, 155, 189, 223, 136, 2, 239, 137, 151, 138, 252, 162, 141,
+ 255, 209, 25, 4, 146, 24, 221, 43, 148, 120, 26, 228, 208, 200, 198,
+ 192, 4, 96, 70, 227, 237, 104, 17, 67, 9, 211]),
+
+ 256: new Uint8Array([41, 213, 121, 140, 181, 227, 200, 97, 100, 133, 58,
+ 227, 106, 115, 25, 63, 77, 51, 26, 57, 238, 140, 99, 63, 71, 211,
+ 128, 84, 115, 26, 236, 52, 103, 81, 145, 14, 101, 161, 181, 58, 135,
+ 193, 56, 167, 214, 220, 5, 52, 85, 222, 183, 27, 101, 134, 86, 155,
+ 64, 148, 124, 212, 219, 251, 65, 42, 32, 44, 128, 2, 50, 128, 221,
+ 22, 238, 56, 189, 83, 28, 122, 121, 157, 215, 135, 151, 128, 233,
+ 193, 65, 190, 86, 148, 191, 140, 196, 120, 8, 172, 100, 166, 254,
+ 41, 245, 75, 56, 6, 166, 244, 178, 111, 234, 23, 4, 107, 6, 22, 132,
+ 187, 230, 17, 71, 172, 113, 238, 73, 4, 180, 90, 103, 77, 37, 51,
+ 118, 112, 129, 238, 199, 7, 222, 122, 173, 30, 232, 178, 233, 234,
+ 144, 98, 14, 234, 112, 77, 68, 62, 62, 159, 230, 101, 98, 43, 2,
+ 204, 69, 156, 86, 104, 128, 34, 128, 7, 173, 90, 120, 33, 104, 59,
+ 45, 251, 93, 51, 240, 232, 60, 94, 189, 134, 90, 20, 184, 122, 29,
+ 225, 85, 213, 38, 116, 159, 80, 69, 106, 168, 236, 201, 69, 140, 98,
+ 240, 45, 160, 133, 225, 106, 45, 245, 212, 160, 176, 128, 27, 114,
+ 153, 182, 144, 145, 214, 72, 196, 138, 183, 87, 61, 245, 150, 56,
+ 82, 158, 224, 50, 114, 125, 122, 172, 161, 129, 234, 70, 63, 245,
+ 136, 30, 136, 9, 128, 220, 229, 157, 222, 195, 149, 189, 70, 8, 71,
+ 40, 195, 93, 27, 7, 234, 164, 175, 102, 201, 149, 115, 248, 179,
+ 125, 66, 122, 194, 26, 61, 218, 198, 181, 152, 140, 199, 48, 148,
+ 31, 14, 241, 197, 3, 70, 128, 239, 32, 86, 15, 215, 86, 245, 190,
+ 95, 141, 41, 111, 0, 232, 28, 152, 67, 87, 197, 255, 118, 13, 251,
+ 71, 84, 22, 231, 134, 188, 175, 115, 138, 37, 199, 5, 238, 199, 2,
+ 99, 203, 75, 62, 231, 21, 150, 239, 94, 201, 185, 219, 58, 210, 228,
+ 151, 131, 76, 148, 104, 60, 74, 82, 6, 168, 49, 251, 182, 3, 232,
+ 173, 210, 201, 19, 101, 166, 7, 94, 11, 194, 211, 146, 229, 75, 241,
+ 15, 50, 187, 36, 175, 78, 227, 98, 224, 3, 95, 209, 93, 126, 112,
+ 178, 29, 18, 108, 241, 232, 79, 210, 41, 2, 238, 208, 190, 171, 134,
+ 147, 188, 191, 229, 122, 32, 209, 166, 118, 129, 223, 130, 214, 195,
+ 89, 67, 94, 218, 155, 185, 0, 144, 255, 132, 213, 25, 59, 83, 242,
+ 57, 69, 148, 109, 133, 61, 163, 30, 214, 254, 54, 169, 3, 217, 77,
+ 66, 123, 193, 204, 199, 109, 123, 49, 186, 223, 229, 8, 230, 164,
+ 171, 196, 145, 225, 10, 111, 248, 111, 164, 216, 54, 225, 253])
+ };
+
+ // Replace the last block of each ciphertext with bad padding below for decryption errors
+ var badPadding = {
+ 128: {
+ "zeroPadChar": new Uint8Array([238, 27, 248, 169, 218, 138, 164, 86, 207, 102, 36, 223, 6, 166, 77, 14]),
+ "bigPadChar": new Uint8Array([91, 67, 119, 104, 252, 238, 175, 144, 17, 75, 12, 163, 212, 52, 46, 51]),
+ "inconsistentPadChars": new Uint8Array([135, 101, 112, 208, 3, 106, 226, 20, 25, 219, 79, 94, 58, 212, 242, 192])
+ },
+ 192: {
+ "zeroPadChar": new Uint8Array([22, 158, 50, 15, 168, 47, 19, 194, 182, 133, 184, 65, 36, 43, 177, 254]),
+ "bigPadChar": new Uint8Array([207, 110, 28, 160, 165, 213, 48, 213, 163, 242, 15, 78, 96, 117, 106, 87]),
+ "inconsistentPadChars": new Uint8Array([143, 227, 12, 112, 216, 207, 136, 167, 78, 137, 93, 30, 50, 75, 102, 101])
+ },
+ 256: {
+ "zeroPadChar": new Uint8Array([1, 253, 141, 214, 30, 193, 254, 68, 140, 200, 157, 110, 200, 89, 177, 129]),
+ "bigPadChar": new Uint8Array([88, 7, 110, 221, 74, 34, 97, 109, 99, 25, 189, 222, 94, 90, 27, 60]),
+ "inconsistentPadChars": new Uint8Array([152, 54, 60, 148, 59, 136, 193, 21, 77, 140, 170, 67, 120, 74, 106, 62])
+ }
+ };
+
+ var keyLengths = [128, 192, 256];
+
+ // All the scenarios that should succeed, if the key has "encrypt" usage
+ var passing = [];
+ keyLengths.forEach(function(keyLength) {
+ passing.push({
+ name: "AES-CBC " + keyLength.toString() + "-bit key",
+ keyBuffer: keyBytes[keyLength],
+ key: null,
+ algorithm: {name: "AES-CBC", iv: iv},
+ plaintext: plaintext,
+ result: ciphertext[keyLength]
+ });
+ });
+
+ // Scenarios that should fail because of a bad iv length, causing an OperationError
+ var failing = [];
+ keyLengths.forEach(function(keyLength) {
+ var shortIv = iv.slice(0, 8);
+ failing.push({
+ name: "AES-CBC " + keyLength.toString() + "-bit key, 64-bit IV",
+ keyBuffer: keyBytes[keyLength],
+ key: null,
+ algorithm: {name: "AES-CBC", iv: shortIv},
+ plaintext: plaintext,
+ result: ciphertext[keyLength]
+ });
+
+ var longIv = new Uint8Array(24);
+ longIv.set(iv, 0);
+ longIv.set(iv.slice(0, 8), 16);
+ failing.push({
+ name: "AES-CBC " + keyLength.toString() + "-bit key, 192-bit IV",
+ keyBuffer: keyBytes[keyLength],
+ key: null,
+ algorithm: {name: "AES-CBC", iv: longIv},
+ plaintext: plaintext,
+ result: ciphertext[keyLength]
+ });
+ });
+
+ // Scenarios that should fail decryption because of bad padding
+ var decryptionFailing = [];
+ keyLengths.forEach(function(keyLength) {
+ ["zeroPadChar", "bigPadChar", "inconsistentPadChars"].forEach(function(paddingProblem) {
+ var badCiphertext = new Uint8Array(ciphertext[keyLength].byteLength);
+ badCiphertext.set(ciphertext[keyLength].slice(0, ciphertext[keyLength].byteLength - 16));
+ badCiphertext.set(badPadding[keyLength][paddingProblem], ciphertext[keyLength].byteLength - 16);
+
+ decryptionFailing.push({
+ name: "AES-CBC " + keyLength.toString() + "-bit key, " + paddingProblem,
+ keyBuffer: keyBytes[keyLength],
+ key: null,
+ algorithm: {name: "AES-CBC", iv: iv},
+ plaintext: plaintext,
+ result: badCiphertext
+ });
+ });
+ });
+
+ return {passing: passing, failing: failing, decryptionFailing: decryptionFailing};
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.html b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.html
new file mode 100644
index 00000000000..61fb9d5febe
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>WebCryptoAPI: encrypt() Using AES-CTR</title>
+<meta name="timeout" content="long">
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="../util/helpers.js"></script>
+<script src="aes_common_fixtures.js"></script>
+<script src="aes_ctr_vectors.js"></script>
+<script src="aes.js"></script>
+<div id=log></div>
+<script src="../../WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.js b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.js
new file mode 100644
index 00000000000..cbda32f3543
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr.https.any.js
@@ -0,0 +1,8 @@
+// META: title=WebCryptoAPI: encrypt() Using AES-CTR
+// META: script=../util/helpers.js
+// META: script=aes_common_fixtures.js
+// META: script=aes_ctr_vectors.js
+// META: script=aes.js
+// META: timeout=long
+
+run_test();
diff --git a/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr_vectors.js b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr_vectors.js
new file mode 100644
index 00000000000..89a19fa5fcb
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/WebCryptoAPI/encrypt_decrypt/aes_ctr_vectors.js
@@ -0,0 +1,73 @@
+
+// aes_ctr_vectors.js
+
+// The following function returns an array of test vectors
+// for the subtleCrypto encrypt method.
+//
+// Each test vector has the following fields:
+// name - a unique name for this vector
+// keyBuffer - an arrayBuffer with the key data in raw form
+// key - a CryptoKey object for the keyBuffer. INITIALLY null! You must fill this in first to use it!
+// algorithm - the value of the AlgorithmIdentifier parameter to provide to encrypt
+// plaintext - the text to encrypt
+// result - the expected result (usually just ciphertext, sometimes with added authentication)
+function getTestVectors() {
+ var commonFixtures = getAesCommonFixtures();
+ var plaintext = commonFixtures.plaintext;
+ var keyBytes = commonFixtures.keyBytes;
+
+ // AES-CTR needs a 16 byte (128 bit) counter.
+ var counter = new Uint8Array([85, 170, 248, 155, 168, 148, 19, 213, 78, 167, 39,
+ 167, 108, 39, 162, 132]);
+
+
+ // Results. These were created using the Python cryptography module.
+
+ // AES-CTR produces ciphertext
+ var ciphertext = {
+ 128: new Uint8Array([233, 17, 117, 253, 164, 245, 234, 87, 197, 43, 13, 0, 11, 190, 152, 175, 104, 192, 165, 144, 88, 174, 237, 138, 181, 183, 6, 53, 3, 161, 206, 71, 13, 121, 218, 209, 116, 249, 10, 170, 250, 165, 68, 157, 132, 141, 200, 178, 197, 87, 209, 231, 250, 75, 154, 65, 162, 251, 30, 159, 234, 20, 20, 181, 147, 218, 180, 12, 4, 241, 75, 79, 129, 64, 15, 228, 60, 147, 153, 1, 129, 176, 150, 161, 85, 97, 22, 154, 234, 23, 127, 16, 4, 22, 226, 11, 104, 16, 176, 14, 225, 176, 79, 239, 103, 243, 190, 222, 40, 186, 244, 212, 29, 57, 125, 175, 21, 17, 233, 2, 13, 119, 102, 233, 230, 4, 16, 222, 56, 225, 67, 45, 191, 250, 15, 153, 45, 193, 240, 212, 117, 101, 68, 232, 199, 101, 175, 125, 247, 6, 249, 14, 0, 157, 185, 56, 76, 51, 228, 77, 234, 84, 60, 42, 119, 187, 213, 32, 34, 222, 65, 231, 215, 26, 73, 141, 231, 254, 185, 118, 14, 180, 126, 80, 51, 102, 200, 141, 204, 45, 26, 56, 119, 136, 222, 45, 143, 120, 231, 44, 43, 221, 136, 21, 188, 138, 84, 232, 208, 238, 226, 117, 104, 60, 165, 4, 18, 144, 240, 49, 173, 90, 68, 84, 239, 161, 124, 196, 144, 119, 24, 243, 239, 75, 117, 254, 219, 209, 53, 131, 37, 79, 68, 26, 21, 168, 163, 50, 59, 18, 244, 11, 143, 190, 188, 129, 108, 249, 180, 104, 216, 215, 165, 160, 251, 84, 132, 152, 195, 154, 110, 216, 70, 21, 248, 148, 146, 152, 56, 174, 248, 227, 1, 102, 15, 118, 182, 50, 73, 63, 35, 112, 159, 237, 253, 94, 16, 127, 120, 38, 127, 51, 27, 96, 163, 140, 20, 111, 151, 16, 72, 74, 74, 205, 239, 241, 16, 179, 183, 116, 95, 248, 58, 168, 203, 93, 233, 225, 91, 17, 226, 10, 120, 85, 114, 4, 31, 40, 82, 161, 152, 17, 86, 237, 207, 7, 228, 110, 182, 65, 68, 68, 156, 206, 116, 185, 204, 148, 22, 58, 111, 218, 138, 225, 146, 25, 114, 29, 96, 183, 87, 181, 181, 236, 113, 141, 171, 213, 9, 84, 182, 230, 163, 147, 246, 86, 246, 52, 111, 64, 34, 157, 12, 80, 224, 28, 21, 112, 31, 42, 79, 229, 210, 90, 23, 78, 223, 155, 144, 238, 12, 14, 191, 158, 6, 181, 254, 0, 85, 134, 56, 161, 234, 55, 129, 64, 59, 12, 146, 6, 217, 232, 20, 214, 167, 159, 183, 165, 96, 96, 225, 199, 23, 106, 243, 108, 106, 26, 214, 53, 152, 26, 155, 253, 128, 7, 216, 207, 109, 159, 147, 240, 232, 226, 43, 147, 169, 162, 204, 215, 9, 10, 177, 223, 99, 206, 163, 240, 64]),
+
+ 192: new Uint8Array([98, 123, 235, 65, 14, 86, 80, 133, 88, 104, 244, 125, 165, 185, 163, 4, 3, 230, 62, 58, 113, 222, 46, 210, 17, 155, 95, 19, 125, 125, 70, 234, 105, 54, 23, 246, 114, 9, 237, 191, 9, 194, 34, 254, 156, 11, 50, 216, 80, 178, 185, 221, 132, 154, 27, 85, 82, 49, 241, 123, 23, 106, 119, 134, 203, 0, 151, 66, 149, 218, 124, 247, 227, 233, 236, 184, 88, 234, 174, 250, 83, 168, 33, 15, 122, 26, 96, 213, 210, 4, 52, 92, 20, 12, 64, 12, 209, 197, 69, 100, 15, 56, 60, 63, 241, 52, 18, 189, 93, 146, 47, 60, 33, 200, 218, 243, 43, 169, 17, 108, 19, 199, 174, 33, 107, 186, 57, 95, 167, 138, 180, 187, 53, 113, 208, 148, 190, 48, 167, 53, 209, 52, 153, 184, 231, 63, 168, 54, 179, 238, 93, 130, 125, 3, 149, 119, 60, 25, 142, 150, 183, 193, 29, 18, 3, 219, 235, 219, 26, 116, 217, 196, 108, 6, 96, 103, 212, 48, 227, 91, 124, 77, 181, 169, 18, 111, 123, 83, 26, 169, 230, 88, 103, 185, 153, 93, 143, 152, 142, 231, 41, 226, 226, 156, 179, 206, 212, 67, 18, 193, 187, 53, 252, 214, 15, 228, 246, 131, 170, 101, 134, 212, 100, 170, 146, 47, 57, 125, 50, 230, 51, 246, 74, 175, 129, 196, 178, 206, 176, 52, 153, 39, 77, 24, 186, 99, 137, 83, 105, 111, 168, 35, 176, 24, 29, 170, 223, 74, 160, 138, 247, 12, 102, 233, 136, 59, 172, 228, 242, 84, 13, 34, 155, 80, 80, 87, 180, 143, 129, 61, 213, 54, 41, 8, 183, 102, 126, 179, 127, 77, 55, 176, 152, 41, 131, 85, 86, 225, 87, 216, 139, 226, 196, 195, 210, 34, 33, 161, 249, 153, 205, 197, 128, 41, 28, 121, 6, 159, 25, 211, 168, 137, 26, 217, 249, 113, 81, 141, 18, 1, 250, 228, 68, 238, 74, 54, 99, 167, 236, 176, 199, 148, 161, 143, 156, 51, 189, 204, 59, 240, 151, 170, 85, 63, 23, 38, 152, 199, 12, 81, 217, 244, 178, 231, 249, 159, 224, 107, 214, 58, 127, 116, 143, 219, 155, 80, 55, 213, 171, 80, 127, 235, 20, 247, 12, 104, 228, 147, 202, 124, 143, 110, 223, 76, 221, 154, 175, 143, 185, 237, 222, 189, 104, 218, 72, 244, 55, 253, 138, 183, 92, 231, 68, 176, 239, 171, 100, 10, 63, 61, 194, 228, 15, 133, 216, 45, 60, 135, 203, 142, 127, 153, 172, 223, 213, 230, 220, 189, 223, 234, 156, 134, 238, 220, 251, 104, 209, 117, 175, 47, 46, 148, 6, 61, 216, 215, 39, 30, 116, 212, 45, 112, 202, 227, 198, 98, 253, 97, 177, 120, 74, 238, 68, 99, 240, 96, 43, 88, 166]),
+
+ 256: new Uint8Array([55, 82, 154, 67, 47, 80, 186, 78, 83, 56, 95, 130, 102, 236, 61, 236, 204, 236, 234, 222, 122, 226, 147, 149, 233, 41, 16, 118, 201, 91, 185, 162, 79, 71, 146, 252, 221, 110, 165, 137, 75, 129, 94, 219, 93, 94, 64, 34, 250, 190, 5, 90, 6, 177, 167, 224, 25, 121, 85, 91, 87, 152, 56, 100, 191, 35, 1, 156, 177, 179, 127, 253, 173, 176, 87, 247, 40, 207, 178, 175, 10, 51, 209, 70, 52, 76, 251, 160, 172, 203, 77, 191, 97, 58, 123, 238, 82, 60, 166, 214, 134, 14, 71, 74, 156, 15, 77, 6, 141, 76, 10, 205, 148, 204, 85, 203, 242, 30, 66, 133, 202, 21, 17, 108, 151, 2, 15, 44, 51, 180, 88, 80, 8, 248, 254, 151, 201, 226, 156, 6, 39, 197, 212, 124, 72, 217, 75, 232, 139, 155, 22, 199, 242, 223, 116, 10, 141, 42, 7, 85, 99, 5, 184, 43, 145, 159, 122, 135, 202, 46, 209, 157, 178, 114, 98, 194, 119, 194, 19, 242, 167, 236, 162, 94, 90, 106, 219, 234, 67, 11, 162, 225, 6, 17, 152, 23, 16, 84, 40, 90, 255, 158, 8, 105, 198, 56, 220, 213, 36, 203, 241, 242, 85, 218, 103, 90, 202, 214, 215, 134, 121, 169, 149, 139, 122, 143, 155, 178, 29, 217, 197, 128, 173, 25, 111, 154, 14, 76, 106, 101, 0, 215, 187, 33, 223, 116, 205, 89, 52, 206, 60, 77, 141, 31, 57, 211, 74, 42, 219, 88, 210, 36, 196, 128, 151, 136, 124, 222, 157, 59, 225, 70, 163, 234, 59, 173, 228, 198, 134, 76, 249, 228, 69, 181, 196, 194, 179, 239, 78, 43, 143, 94, 234, 10, 177, 192, 185, 171, 231, 164, 254, 91, 44, 11, 29, 148, 223, 107, 18, 149, 61, 50, 115, 38, 14, 128, 189, 9, 77, 236, 151, 163, 23, 122, 156, 236, 11, 80, 66, 190, 24, 4, 4, 12, 148, 57, 64, 59, 143, 114, 247, 66, 111, 167, 86, 173, 98, 102, 207, 44, 134, 89, 231, 64, 50, 157, 208, 210, 79, 159, 133, 73, 118, 98, 202, 215, 57, 247, 29, 97, 116, 1, 28, 119, 248, 243, 31, 180, 66, 38, 40, 141, 251, 134, 129, 126, 241, 113, 22, 50, 28, 113, 187, 158, 217, 125, 182, 233, 144, 246, 32, 88, 88, 15, 0, 102, 131, 67, 31, 34, 150, 98, 241, 213, 227, 205, 175, 254, 3, 53, 70, 124, 167, 38, 53, 104, 140, 147, 158, 200, 179, 45, 100, 101, 246, 81, 166, 53, 247, 60, 10, 78, 127, 10, 173, 176, 232, 31, 91, 203, 250, 236, 38, 113, 172, 151, 253, 194, 253, 50, 242, 76, 148, 23, 117, 195, 122, 104, 16, 212, 177, 113, 188, 138, 186, 144, 168, 102, 3])
+ };
+
+ var keyLengths = [128, 192, 256];
+
+ // All the scenarios that should succeed, if the key has "encrypt" usage
+ var passing = [];
+ keyLengths.forEach(function(keyLength) {
+ passing.push({
+ name: "AES-CTR " + keyLength.toString() + "-bit key",
+ keyBuffer: keyBytes[keyLength],
+ key: null,
+ algorithm: {name: "AES-CTR", counter: counter, length: 64},
+ plaintext: plaintext,
+ result: ciphertext[keyLength]
+ });
+ });
+
+ // Scenarios that should fail because of a bad length parameter, causing an OperationError
+ var failing = [];
+ keyLengths.forEach(function(keyLength) {
+ failing.push({
+ name: "AES-CTR " + keyLength.toString() + "-bit key, 0-bit counter",
+ keyBuffer: keyBytes[keyLength],
+ key: null,
+ algorithm: {name: "AES-CTR", counter: counter, length: 0},
+ plaintext: plaintext,
+ result: ciphertext[keyLength]
+ });
+
+ failing.push({
+ name: "AES-CTR " + keyLength.toString() + "-bit key, 129-bit counter",
+ keyBuffer: keyBytes[keyLength],
+ key: null,
+ algorithm: {name: "AES-CTR", counter: counter, length: 129},
+ plaintext: plaintext,
+ result: ciphertext[keyLength]
+ });
+ });
+
+ return {passing: passing, failing: failing, decryptionFailing: []};
+}