Skip to content

Truly independent web browser

LibCrypto+LibWeb: Hold OKP keys as OpenSSL keys

Shannon Boothdb95f02e8f05
diff --git a/Libraries/LibCrypto/Rust/src/key.rs b/Libraries/LibCrypto/Rust/src/key.rs
index f39fd5e250f..ad54099a753 100644
--- a/Libraries/LibCrypto/Rust/src/key.rs
+++ b/Libraries/LibCrypto/Rust/src/key.rs
@@ -9,13 +9,14 @@
use crate::ec::{self, EcPrivateKey, EcPublicKey};
use crate::ml::{self, MlDsaPublicKey, MlKemPublicKey, MlPrivateKey};
use crate::rsa::{self, RsaPrivateKey, RsaPublicKey};
+use crate::{OkpCurve, OkpKey, okp_key_from_raw};
pub struct KeyHandle(pub(crate) Key);
pub(crate) enum Key {
Secret(SecretBytes),
- OkpPublic(Vec<u8>),
- OkpPrivate(SecretBytes),
+ OkpPublic(OkpKey),
+ OkpPrivate(OkpKey),
MlDsaPublic(MlDsaPublicKey),
MlKemPublic(MlKemPublicKey),
MlPrivate(MlPrivateKey),
@@ -98,13 +99,13 @@ impl StoredKey {
Self { tag, buffers }
}
- pub fn buffers(&self) -> Vec<&[u8]> {
- self.buffers.iter().map(|buffer| &**buffer).collect()
+ pub fn buffers(&self) -> &[SecretBytes] {
+ &self.buffers
}
}
/// Bytes that are cleared when they are dropped.
-pub(crate) struct SecretBytes(Vec<u8>);
+pub struct SecretBytes(Vec<u8>);
impl SecretBytes {
pub(crate) fn new(bytes: Vec<u8>) -> Self {
@@ -174,14 +175,6 @@ impl KeyHandle {
Self(Key::Secret(SecretBytes::new(bytes.to_vec())))
}
- pub fn from_okp_bytes(is_private: bool, bytes: &[u8]) -> Self {
- Self(if is_private {
- Key::OkpPrivate(SecretBytes::new(bytes.to_vec()))
- } else {
- Key::OkpPublic(bytes.to_vec())
- })
- }
-
pub fn secret_bytes(&self) -> &[u8] {
match &self.0 {
Key::Secret(bytes) => bytes,
@@ -189,23 +182,11 @@ impl KeyHandle {
}
}
- pub fn okp_bytes(&self) -> &[u8] {
- 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::OkpPublic(key) => key.stored(HandleTag::OkpPublic),
+ Key::OkpPrivate(key) => key.stored(HandleTag::OkpPrivate),
Key::EcPublic(key) => key.stored(),
Key::EcPrivate(key) => key.stored(),
Key::RsaPublic(key) => key.stored(),
@@ -216,12 +197,13 @@ impl KeyHandle {
}
}
- /// The key that a stored form holds, as `to_stored()` gives it.
+ /// The key that a stored form holds, as `to_stored()` gives it. An OKP key's curve is not stored with it.
pub fn from_stored(
tag: HandleTag,
buffers: &[&[u8]],
ec_parameters: Option<&[u32]>,
has_ec_public_key: bool,
+ okp_curve: Option<OkpCurve>,
) -> Result<Self, KeyDecodeError> {
let is_ec_private_key = tag == HandleTag::EcPrivate;
let expected = tag.buffer_count() + if has_ec_public_key { 2 } else { 0 };
@@ -230,8 +212,11 @@ impl KeyHandle {
}
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::OkpPublic | HandleTag::OkpPrivate => {
+ let curve = okp_curve.ok_or(KeyDecodeError::InvalidComponents)?;
+ okp_key_from_raw(curve, tag == HandleTag::OkpPrivate, buffers[0])
+ .map_err(|_| KeyDecodeError::InvalidComponents)
+ }
HandleTag::RsaPublic | HandleTag::RsaPrivate => rsa::decode_stored(tag, buffers),
HandleTag::EcPublic | HandleTag::EcPrivate => {
ec::decode_stored(tag, buffers, ec_parameters, has_ec_public_key)
diff --git a/Libraries/LibCrypto/Rust/src/lib.rs b/Libraries/LibCrypto/Rust/src/lib.rs
index 6e57672f628..8f4de7965e7 100644
--- a/Libraries/LibCrypto/Rust/src/lib.rs
+++ b/Libraries/LibCrypto/Rust/src/lib.rs
@@ -11,10 +11,9 @@
use core::ffi::{CStr, c_int, c_uint};
-use ak::Utf16String;
use subtle::ConstantTimeEq;
-use key::SecretBytes;
+use key::Key;
use openssl::{Cipher, CipherContext, Pkey, end_parameter, octet_string_parameter, uint_parameter, utf8_parameter};
mod der;
@@ -31,7 +30,7 @@ pub use ec::{
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::{HandleTag, KeyDecodeError, KeyHandle, KeyPair, SecretBytes, 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,
@@ -606,28 +605,84 @@ impl OkpCurve {
}
}
-pub fn okp_generate_private_key(curve: OkpCurve) -> Result<Vec<u8>, CryptoError> {
- Ok(Pkey::generate(curve.name(), None)?.raw_private_key()?.into_vec())
+pub(crate) struct OkpKey {
+ curve: OkpCurve,
+ key: Pkey,
+}
+
+impl OkpKey {
+ /// The stored form of the key: its raw public or private key.
+ pub(crate) fn stored(&self, tag: HandleTag) -> StoredKey {
+ let bytes = if tag == HandleTag::OkpPrivate {
+ self.key.raw_private_key()
+ } else {
+ self.key.raw_public_key().map(SecretBytes::new)
+ };
+ StoredKey::new(tag, vec![bytes.expect("OpenSSL gives an OKP key's raw key")])
+ }
+
+ fn public_key(&self) -> Result<Self, CryptoError> {
+ Ok(Self {
+ curve: self.curve,
+ key: Pkey::from_raw_public_key(self.curve.name(), &self.key.raw_public_key()?)?,
+ })
+ }
+}
+
+fn okp_key(key: &KeyHandle) -> &OkpKey {
+ match &key.0 {
+ Key::OkpPublic(key) | Key::OkpPrivate(key) => key,
+ _ => panic!("The key is not an OKP key"),
+ }
+}
+
+pub fn okp_generate_key_pair(curve: OkpCurve) -> Result<KeyPair, CryptoError> {
+ let private_key = OkpKey {
+ curve,
+ key: Pkey::generate(curve.name(), None)?,
+ };
+ Ok(KeyPair {
+ public_key: KeyHandle(Key::OkpPublic(private_key.public_key()?)),
+ private_key: KeyHandle(Key::OkpPrivate(private_key)),
+ })
+}
+
+pub fn okp_key_from_raw(curve: OkpCurve, is_private: bool, bytes: &[u8]) -> Result<KeyHandle, CryptoError> {
+ Ok(KeyHandle(if is_private {
+ Key::OkpPrivate(OkpKey {
+ curve,
+ key: Pkey::from_raw_private_key(curve.name(), bytes)?,
+ })
+ } else {
+ Key::OkpPublic(OkpKey {
+ curve,
+ key: Pkey::from_raw_public_key(curve.name(), 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()
+/// The raw public key of an OKP public key, or of the public key of an OKP private key.
+pub fn okp_raw_public_key(key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
+ okp_key(key).key.raw_public_key()
}
-pub fn okp_compute_coordinate(curve: OkpCurve, private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, CryptoError> {
- if !matches!(curve, OkpCurve::X25519 | OkpCurve::X448) {
+pub fn okp_raw_private_key(key: &KeyHandle) -> Result<SecretBytes, CryptoError> {
+ okp_key(key).key.raw_private_key()
+}
+
+pub fn okp_compute_coordinate(private_key: &KeyHandle, public_key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
+ let private_key = okp_key(private_key);
+ if !matches!(private_key.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)
+ openssl::derive(&private_key.key, &okp_key(public_key).key, false)
}
-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)?;
+pub fn okp_sign(private_key: &KeyHandle, message: &[u8], context: &[u8]) -> Result<Vec<u8>, CryptoError> {
+ let OkpKey { curve, key } = okp_key(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::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),
}
}
@@ -682,22 +737,22 @@ fn is_small_order_ed25519_point(point: &[u8]) -> bool {
}
pub fn okp_verify(
- curve: OkpCurve,
- public_key: &[u8],
+ public_key: &KeyHandle,
signature: &[u8],
message: &[u8],
context: &[u8],
) -> 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))
+ let OkpKey { curve, key } = okp_key(public_key);
+ if *curve == OkpCurve::Ed25519
+ && (is_small_order_ed25519_point(&key.raw_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::Ed25519 => openssl::digest_verify(key, None, &[end_parameter()], message, signature),
OkpCurve::Ed448 => openssl::digest_verify(
- &key,
+ key,
None,
&openssl::context_string_parameters(context),
message,
@@ -707,33 +762,26 @@ pub fn okp_verify(
}
}
-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 okp_export_der(key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
+ match &key.0 {
+ Key::OkpPublic(public_key) => public_key.key.public_key_info(),
+ Key::OkpPrivate(OkpKey { curve, key }) => {
+ // https://www.rfc-editor.org/rfc/rfc8410#section-7
+ // CurvePrivateKey ::= OCTET STRING
+ let private_key = SecretBytes::new(der::element(der::OCTET_STRING, &[&key.raw_private_key()?]));
+ Ok(der::private_key_info(
+ KeyAlgorithm::Okp(*curve).oid(),
+ None,
+ &private_key,
+ ))
+ }
+ _ => panic!("The key is not an OKP key"),
}
}
-pub fn public_key_for_private_key(key: &KeyHandle, name: &Utf16String) -> Option<KeyHandle> {
- 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));
+pub fn public_key_for_private_key(key: &KeyHandle) -> Option<KeyHandle> {
+ if let Key::OkpPrivate(private_key) = &key.0 {
+ return Some(KeyHandle(Key::OkpPublic(private_key.public_key().ok()?)));
}
ml::public_key_for_private_key(key)
.or_else(|| ec::public_key_for_private_key(key))
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index 05dbafbbaaf..00f057da93d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -15,7 +15,7 @@ use std::rc::Rc;
use ak::{Utf16String, Utf16StringUnits};
use libcrypto_rust::{
Argon2Inputs, Argon2Type, CShakeKind, CryptoError, EcCurve, KeyAlgorithm, KeyHandle, KeyInfo, KeyPair, KmacKind,
- MlDsaSize, MlKemSize, OkpCurve, RsaJwkInteger, RsaSignaturePadding, ShaHashKind,
+ MlDsaSize, MlKemSize, OkpCurve, RsaJwkInteger, RsaSignaturePadding, SecretBytes, ShaHashKind,
};
use libjs_rust::api::{
ErrorKind, ErrorType, Gc, Object, PropertyKey, Realm, Trace, TypedArrayBase, TypedArrayKind, Value, Vm,
@@ -9875,26 +9875,28 @@ fn parse_octet_string(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Vec<u8>> {
copy_bytes(vm, octets)
}
-fn okp_generate_private_key(curve: OkpCurve) -> Result<Bytes, ()> {
- libcrypto_rust::okp_generate_private_key(curve)
- .map(Bytes::new)
- .map_err(|_| ())
+fn okp_key_handle(vm: &Vm, curve: OkpCurve, is_private: bool, bytes: &[u8]) -> WebIdlResult<KeyHandle> {
+ libcrypto_rust::okp_key_from_raw(curve, is_private, bytes).map_err(|_| out_of_memory(vm))
+}
+
+fn okp_key(vm: &Vm, curve: OkpCurve, is_private: bool, bytes: &[u8]) -> WebIdlResult<Ref<CryptoKey>> {
+ Ok(CryptoKey::create(vm, okp_key_handle(vm, curve, is_private, bytes)?))
}
-fn okp_generate_public_key(curve: OkpCurve, private_key: &[u8]) -> Result<Bytes, ()> {
- libcrypto_rust::okp_generate_public_key(curve, private_key)
+fn okp_raw_public_key(vm: &Vm, key: &CryptoKey) -> WebIdlResult<Bytes> {
+ libcrypto_rust::okp_raw_public_key(key.handle())
.map(Bytes::new)
- .map_err(|_| ())
+ .map_err(|_| out_of_memory(vm))
}
-fn okp_export_der(vm: &Vm, curve: OkpCurve, is_public: bool, key: &[u8]) -> WebIdlResult<Bytes> {
- let result = libcrypto_rust::okp_export_der(curve, is_public, key).map(Bytes::new);
- let Ok(result) = result else {
- return vm
- .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])
- .map_err(Into::into);
- };
- Ok(result)
+fn okp_raw_private_key(vm: &Vm, key: &CryptoKey) -> WebIdlResult<SecretBytes> {
+ libcrypto_rust::okp_raw_private_key(key.handle()).map_err(|_| out_of_memory(vm))
+}
+
+fn okp_export_der(vm: &Vm, key: &CryptoKey) -> WebIdlResult<Bytes> {
+ libcrypto_rust::okp_export_der(key.handle())
+ .map(Bytes::new)
+ .map_err(|_| out_of_memory(vm))
}
fn out_of_memory(vm: &Vm) -> Exception {
@@ -9927,18 +9929,12 @@ impl AlgorithmMethods for Ed25519 {
}
// 2. Generate an Ed25519 key pair, as defined in [RFC8032], section 5.1.5.
- let maybe_private_key = okp_generate_private_key(OkpCurve::Ed25519);
- let Ok(private_key_data) = maybe_private_key else {
- return Err(dom_error("OperationError", b"Failed to generate private key"));
- };
-
- let maybe_public_key = okp_generate_public_key(OkpCurve::Ed25519, private_key_data.as_slice());
- let Ok(public_key_data) = maybe_public_key else {
- return Err(dom_error("OperationError", b"Failed to generate public key"));
+ let Ok(key_pair) = libcrypto_rust::okp_generate_key_pair(OkpCurve::Ed25519) else {
+ return Err(dom_error("OperationError", b"Failed to generate key pair"));
};
// 5. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
- let public_key = CryptoKey::from_okp_handle(cx.vm(), false, public_key_data.as_slice());
+ let public_key = CryptoKey::create(cx.vm(), key_pair.public_key);
// 6. Set the [[type]] internal slot of publicKey to "public"
public_key.set_type(KeyType::Public);
@@ -9957,7 +9953,7 @@ impl AlgorithmMethods for Ed25519 {
public_key.set_usages(usage_intersection(key_usages, &[KeyUsage::Verify]));
// 10. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
- let private_key = CryptoKey::from_okp_handle(cx.vm(), true, private_key_data.as_slice());
+ let private_key = CryptoKey::create(cx.vm(), key_pair.private_key);
// 11. Set the [[type]] internal slot of privateKey to "private"
private_key.set_type(KeyType::Private);
@@ -10035,7 +10031,7 @@ impl AlgorithmMethods for Ed25519 {
let public_key = spki.raw_key();
// 7. Let key be a new CryptoKey that represents publicKey.
- key = CryptoKey::from_okp_handle(cx.vm(), false, public_key);
+ key = okp_key(cx.vm(), OkpCurve::Ed25519, false, public_key)?;
// 8. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -10085,7 +10081,7 @@ impl AlgorithmMethods for Ed25519 {
let curve_private_key_bytes = parse_octet_string(cx.vm(), private_key_info.raw_key())?;
// 8. Let key be a new CryptoKey that represents the Ed25519 private key identified by curvePrivateKey.
- key = CryptoKey::from_okp_handle(cx.vm(), true, curve_private_key_bytes.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::Ed25519, true, curve_private_key_bytes.as_slice())?;
// 9. Set the [[type]] internal slot of key to "private"
key.set_type(KeyType::Private);
@@ -10197,14 +10193,15 @@ impl AlgorithmMethods for Ed25519 {
return Err(dom_error("DataError", b"Invalid key length"));
}
- let derived_public_key = okp_generate_public_key(OkpCurve::Ed25519, private_key.as_slice())
- .map_err(|()| out_of_memory(cx.vm()))?;
+ let private_key = okp_key_handle(cx.vm(), OkpCurve::Ed25519, true, private_key.as_slice())?;
+ let derived_public_key =
+ libcrypto_rust::okp_raw_public_key(&private_key).map_err(|_| out_of_memory(cx.vm()))?;
if derived_public_key.as_slice() != public_key.as_slice() {
return Err(dom_error("DataError", b"Invalid key pair"));
}
// 2. Let key be a new CryptoKey object that represents the Ed25519 private key identified by interpreting jwk according to Section 2 of [RFC8037].
- key = CryptoKey::from_okp_handle(cx.vm(), true, private_key.as_slice());
+ key = CryptoKey::create(cx.vm(), private_key);
// 3. Set the [[type]] internal slot of Key to "private".
key.set_type(KeyType::Private);
@@ -10239,7 +10236,7 @@ impl AlgorithmMethods for Ed25519 {
}
// 2. Let key be a new CryptoKey object that represents the Ed25519 public key identified by interpreting jwk according to Section 2 of [RFC8037].
- key = CryptoKey::from_okp_handle(cx.vm(), false, public_key.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::Ed25519, false, public_key.as_slice())?;
// 3. Set the [[type]] internal slot of Key to "public".
key.set_type(KeyType::Public);
@@ -10275,7 +10272,7 @@ impl AlgorithmMethods for Ed25519 {
}
// 5. Let key be a new CryptoKey representing the key data provided in keyData.
- key = CryptoKey::from_okp_handle(cx.vm(), false, data.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::Ed25519, false, data.as_slice())?;
// 6. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -10320,7 +10317,7 @@ impl AlgorithmMethods for Ed25519 {
// * Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
// * Set the algorithm object identifier to the id-Ed25519 OID defined in [RFC8410].
// * Set the subjectPublicKey field to keyData.
- let data = okp_export_der(cx.vm(), OkpCurve::Ed25519, true, key.okp_handle_bytes())?;
+ let data = okp_export_der(cx.vm(), &key)?;
// 3. Let result be the result of DER-encoding data.
return Ok(ExportKeyResult::Bytes(data));
@@ -10343,7 +10340,7 @@ impl AlgorithmMethods for Ed25519 {
// Section 7 of [RFC8410], that represents the Ed25519 private key represented by the [[handle]]
// internal slot of key
- let data = okp_export_der(cx.vm(), OkpCurve::Ed25519, false, key.okp_handle_bytes())?;
+ let data = okp_export_der(cx.vm(), &key)?;
// 3. Let result be the result of DER-encoding data.
return Ok(ExportKeyResult::Bytes(data));
@@ -10364,22 +10361,12 @@ impl AlgorithmMethods for Ed25519 {
jwk.crv = Some(Utf16String::from_ascii(b"Ed25519"));
// 5. Set the x attribute of jwk according to the definition in Section 2 of [RFC8037].
- if key.key_type() == KeyType::Public {
- jwk.x = Some(base64_url_bytes_encode(key.okp_handle_bytes()));
- } else {
- // The "x" parameter of the "epk" field is set as follows:
- // Apply the appropriate ECDH function to the ephemeral private key (as scalar input)
- // and the standard base point (as u-coordinate input).
- // The base64url encoding of the output is the value for the "x" parameter of the "epk" field.
- let public_key = okp_generate_public_key(OkpCurve::Ed25519, key.okp_handle_bytes())
- .map_err(|()| out_of_memory(cx.vm()))?;
- jwk.x = Some(base64_url_bytes_encode(public_key.as_slice()));
- }
+ jwk.x = Some(base64_url_bytes_encode(okp_raw_public_key(cx.vm(), &key)?.as_slice()));
// 6. If the [[type]] internal slot of key is "private"
if key.key_type() == KeyType::Private {
// Set the d attribute of jwk according to the definition in Section 2 of [RFC8037].
- jwk.d = Some(base64_url_bytes_encode(key.okp_handle_bytes()));
+ jwk.d = Some(base64_url_bytes_encode(&okp_raw_private_key(cx.vm(), &key)?));
}
// 7. Set the key_ops attribute of jwk to the usages attribute of key.
@@ -10410,7 +10397,7 @@ impl AlgorithmMethods for Ed25519 {
// slot of key.
// 3. Let result be data.
// 4. Return result.
- return Ok(ExportKeyResult::Bytes(Bytes::new(key.okp_handle_bytes().to_vec())));
+ return Ok(ExportKeyResult::Bytes(okp_raw_public_key(cx.vm(), &key)?));
}
// 3. Otherwise:
@@ -10431,15 +10418,7 @@ impl AlgorithmMethods for Ed25519 {
// 2. Let result be the result of performing the Ed25519 signing process, as specified in [RFC8032], Section
// 5.1.6, with message as M, using the Ed25519 private key associated with key.
- let private_key = key.okp_handle_bytes();
-
- let maybe_public_key = okp_generate_public_key(OkpCurve::Ed25519, private_key);
- if maybe_public_key.is_err() {
- return Err(dom_error("OperationError", b"Failed to generate public key"));
- }
-
- let signature = libcrypto_rust::okp_sign(OkpCurve::Ed25519, key.okp_handle_bytes(), message.as_slice(), &[])
- .map(Bytes::new);
+ let signature = libcrypto_rust::okp_sign(key.handle(), message.as_slice(), &[]).map(Bytes::new);
let Ok(signature) = signature else {
return Err(dom_error("OperationError", b"Failed to sign message"));
};
@@ -10472,13 +10451,7 @@ impl AlgorithmMethods for Ed25519 {
// with message as M, using the Ed25519 public key associated with key.
// 5. Let result be a boolean with the value true if the signature is valid and the value false otherwise.
- let verified = libcrypto_rust::okp_verify(
- OkpCurve::Ed25519,
- key.okp_handle_bytes(),
- signature.as_slice(),
- message.as_slice(),
- &[],
- );
+ let verified = libcrypto_rust::okp_verify(key.handle(), signature.as_slice(), message.as_slice(), &[]);
let verified =
verified.map_err(|error| Exception::Dom("OperationError", Utf16String::from_utf8(error.message())))?;
@@ -10524,19 +10497,13 @@ impl AlgorithmMethods for Ed448 {
}
// 2. Generate an Ed448 key pair, as defined in [RFC8032], section 5.1.5.
- let maybe_private_key = okp_generate_private_key(OkpCurve::Ed448);
- let Ok(private_key_data) = maybe_private_key else {
- return Err(dom_error("OperationError", b"Failed to generate private key"));
- };
-
- let maybe_public_key = okp_generate_public_key(OkpCurve::Ed448, private_key_data.as_slice());
- let Ok(public_key_data) = maybe_public_key else {
- return Err(dom_error("OperationError", b"Failed to generate public key"));
+ let Ok(key_pair) = libcrypto_rust::okp_generate_key_pair(OkpCurve::Ed448) else {
+ return Err(dom_error("OperationError", b"Failed to generate key pair"));
};
// 5. Let publicKey be a new CryptoKey associated with the relevant global object of this [HTML],
// and representing the public key of the generated key pair.
- let public_key = CryptoKey::from_okp_handle(cx.vm(), false, public_key_data.as_slice());
+ let public_key = CryptoKey::create(cx.vm(), key_pair.public_key);
// 6. Set the [[type]] internal slot of publicKey to "public"
public_key.set_type(KeyType::Public);
@@ -10556,7 +10523,7 @@ impl AlgorithmMethods for Ed448 {
// 10. Let privateKey be a new CryptoKey associated with the relevant global object of this [HTML],
// and representing the private key of the generated key pair.
- let private_key = CryptoKey::from_okp_handle(cx.vm(), true, private_key_data.as_slice());
+ let private_key = CryptoKey::create(cx.vm(), key_pair.private_key);
// 11. Set the [[type]] internal slot of privateKey to "private"
private_key.set_type(KeyType::Private);
@@ -10635,7 +10602,7 @@ impl AlgorithmMethods for Ed448 {
// 7. Let key be a new CryptoKey associated with the relevant global object of this [HTML],
// and that represents publicKey.
- key = CryptoKey::from_okp_handle(cx.vm(), false, public_key);
+ key = okp_key(cx.vm(), OkpCurve::Ed448, false, public_key)?;
// 8. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -10686,7 +10653,7 @@ impl AlgorithmMethods for Ed448 {
// 8. Let key be a new CryptoKey associated with the relevant global object of this [HTML],
// and that represents the Ed448 private key identified by curvePrivateKey.
- key = CryptoKey::from_okp_handle(cx.vm(), true, curve_private_key_bytes.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::Ed448, true, curve_private_key_bytes.as_slice())?;
// 9. Set the [[type]] internal slot of key to "private"
key.set_type(KeyType::Private);
@@ -10798,14 +10765,15 @@ impl AlgorithmMethods for Ed448 {
return Err(dom_error("DataError", b"Invalid key length"));
}
- let derived_public_key = okp_generate_public_key(OkpCurve::Ed448, private_key.as_slice())
- .map_err(|()| out_of_memory(cx.vm()))?;
+ let private_key = okp_key_handle(cx.vm(), OkpCurve::Ed448, true, private_key.as_slice())?;
+ let derived_public_key =
+ libcrypto_rust::okp_raw_public_key(&private_key).map_err(|_| out_of_memory(cx.vm()))?;
if derived_public_key.as_slice() != public_key.as_slice() {
return Err(dom_error("DataError", b"Invalid key pair"));
}
// 2. Let key be a new CryptoKey object that represents the Ed448 private key identified by interpreting jwk according to Section 2 of [RFC8037].
- key = CryptoKey::from_okp_handle(cx.vm(), true, private_key.as_slice());
+ key = CryptoKey::create(cx.vm(), private_key);
// 3. Set the [[type]] internal slot of Key to "private".
key.set_type(KeyType::Private);
@@ -10840,7 +10808,7 @@ impl AlgorithmMethods for Ed448 {
}
// 2. Let key be a new CryptoKey object that represents the Ed448 public key identified by interpreting jwk according to Section 2 of [RFC8037].
- key = CryptoKey::from_okp_handle(cx.vm(), false, public_key.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::Ed448, false, public_key.as_slice())?;
// 3. Set the [[type]] internal slot of Key to "public".
key.set_type(KeyType::Public);
@@ -10878,7 +10846,7 @@ impl AlgorithmMethods for Ed448 {
}
// 6. Let key be a new CryptoKey associated with the relevant global object of this [HTML], and that represents data.
- key = CryptoKey::from_okp_handle(cx.vm(), false, data.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::Ed448, false, data.as_slice())?;
// 7. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -10923,7 +10891,7 @@ impl AlgorithmMethods for Ed448 {
// * Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
// * Set the algorithm object identifier to the id-Ed448 OID defined in [RFC8410].
// * Set the subjectPublicKey field to keyData.
- let data = okp_export_der(cx.vm(), OkpCurve::Ed448, true, key.okp_handle_bytes())?;
+ let data = okp_export_der(cx.vm(), &key)?;
// 3. Let result be a new ArrayBuffer associated with the relevant global object of this [HTML], and containing data.
return Ok(ExportKeyResult::Bytes(data));
@@ -10946,7 +10914,7 @@ impl AlgorithmMethods for Ed448 {
// Section 7 of [RFC8410], that represents the Ed448 private key represented by the [[handle]] internal
// slot of key
- let data = okp_export_der(cx.vm(), OkpCurve::Ed448, false, key.okp_handle_bytes())?;
+ let data = okp_export_der(cx.vm(), &key)?;
// 3. Let result be a new ArrayBuffer associated with the relevant global object of this [HTML], and containing data.
return Ok(ExportKeyResult::Bytes(data));
@@ -10967,22 +10935,12 @@ impl AlgorithmMethods for Ed448 {
jwk.crv = Some(Utf16String::from_ascii(b"Ed448"));
// 5. Set the x attribute of jwk according to the definition in Section 2 of [RFC8037].
- if key.key_type() == KeyType::Public {
- jwk.x = Some(base64_url_bytes_encode(key.okp_handle_bytes()));
- } else {
- // The "x" parameter of the "epk" field is set as follows:
- // Apply the appropriate ECDH function to the ephemeral private key (as scalar input)
- // and the standard base point (as u-coordinate input).
- // The base64url encoding of the output is the value for the "x" parameter of the "epk" field.
- let public_key = okp_generate_public_key(OkpCurve::Ed448, key.okp_handle_bytes())
- .map_err(|()| out_of_memory(cx.vm()))?;
- jwk.x = Some(base64_url_bytes_encode(public_key.as_slice()));
- }
+ jwk.x = Some(base64_url_bytes_encode(okp_raw_public_key(cx.vm(), &key)?.as_slice()));
// 6. If the [[type]] internal slot of key is "private"
if key.key_type() == KeyType::Private {
// Set the d attribute of jwk according to the definition in Section 2 of [RFC8037].
- jwk.d = Some(base64_url_bytes_encode(key.okp_handle_bytes()));
+ jwk.d = Some(base64_url_bytes_encode(&okp_raw_private_key(cx.vm(), &key)?));
}
// 7. Set the key_ops attribute of jwk to the usages attribute of key.
@@ -11010,7 +10968,7 @@ impl AlgorithmMethods for Ed448 {
// 2. Let data be an octet string representing the Ed448 public key represented by the [[handle]] internal slot of key.
// 3. Let result be a new ArrayBuffer associated with the relevant global object of this [HTML], and containing data.
// 4. Return result.
- return Ok(ExportKeyResult::Bytes(Bytes::new(key.okp_handle_bytes().to_vec())));
+ return Ok(ExportKeyResult::Bytes(okp_raw_public_key(cx.vm(), &key)?));
}
// 3. Otherwise:
@@ -11041,8 +10999,7 @@ impl AlgorithmMethods for Ed448 {
// 4. Perform the Ed448 signing process, as specified in [RFC8032], Section 5.2.6,
// with message as M and context as C, using the Ed448 private key associated with key.
- let signature = libcrypto_rust::okp_sign(OkpCurve::Ed448, key.okp_handle_bytes(), message.as_slice(), context)
- .map(Bytes::new);
+ let signature = libcrypto_rust::okp_sign(key.handle(), message.as_slice(), context).map(Bytes::new);
let Ok(signature) = signature else {
return Err(dom_error("OperationError", b"Failed to sign message"));
};
@@ -11087,13 +11044,7 @@ impl AlgorithmMethods for Ed448 {
// 6. Perform the Ed448 verification steps, as specified in [RFC8032], Section 5.2.7, using
// the cofactorless (unbatched) equation, [S]B = R + [k]A', on the signature,
// with message as M and context as C, using the Ed448 public key associated with key.
- let verified = libcrypto_rust::okp_verify(
- OkpCurve::Ed448,
- key.okp_handle_bytes(),
- signature.as_slice(),
- message.as_slice(),
- context,
- );
+ let verified = libcrypto_rust::okp_verify(key.handle(), signature.as_slice(), message.as_slice(), context);
let verified =
verified.map_err(|error| Exception::Dom("OperationError", Utf16String::from_utf8(error.message())))?;
@@ -11187,11 +11138,7 @@ impl AlgorithmMethods for X25519 {
// 7. Let secret be the result of performing the X25519 function specified in [RFC7748] Section 5 with
// key as the X25519 private key k and
// the X25519 public key represented by the [[handle]] internal slot of publicKey as the X25519 public key u.
- let private_key = key.okp_handle_bytes();
- let public_key_data = public_key.okp_handle_bytes();
-
- let secret =
- libcrypto_rust::okp_compute_coordinate(OkpCurve::X25519, private_key, public_key_data).map(Bytes::new);
+ let secret = libcrypto_rust::okp_compute_coordinate(key.handle(), public_key.handle()).map(Bytes::new);
let Ok(secret) = secret else {
return Err(dom_error("OperationError", b"Failed to compute secret"));
};
@@ -11254,18 +11201,12 @@ impl AlgorithmMethods for X25519 {
// 2. Generate an X25519 key pair, with the private key being 32 random bytes,
// and the public key being X25519(a, 9), as defined in [RFC7748], section 6.1.
- let maybe_private_key = okp_generate_private_key(OkpCurve::X25519);
- let Ok(private_key_data) = maybe_private_key else {
- return Err(dom_error("OperationError", b"Failed to generate private key"));
- };
-
- let maybe_public_key = okp_generate_public_key(OkpCurve::X25519, private_key_data.as_slice());
- let Ok(public_key_data) = maybe_public_key else {
- return Err(dom_error("OperationError", b"Failed to generate public key"));
+ let Ok(key_pair) = libcrypto_rust::okp_generate_key_pair(OkpCurve::X25519) else {
+ return Err(dom_error("OperationError", b"Failed to generate key pair"));
};
// 5. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
- let public_key = CryptoKey::from_okp_handle(cx.vm(), false, public_key_data.as_slice());
+ let public_key = CryptoKey::create(cx.vm(), key_pair.public_key);
// 6. Set the [[type]] internal slot of publicKey to "public"
public_key.set_type(KeyType::Public);
@@ -11284,7 +11225,7 @@ impl AlgorithmMethods for X25519 {
public_key.set_usages(Vec::new());
// 10. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
- let private_key = CryptoKey::from_okp_handle(cx.vm(), true, private_key_data.as_slice());
+ let private_key = CryptoKey::create(cx.vm(), key_pair.private_key);
// 11. Set the [[type]] internal slot of privateKey to "private"
private_key.set_type(KeyType::Private);
@@ -11361,7 +11302,7 @@ impl AlgorithmMethods for X25519 {
let public_key = spki.raw_key();
// 7. Let key be a new CryptoKey that represents publicKey.
- key = CryptoKey::from_okp_handle(cx.vm(), false, public_key);
+ key = okp_key(cx.vm(), OkpCurve::X25519, false, public_key)?;
// 8. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -11411,7 +11352,7 @@ impl AlgorithmMethods for X25519 {
let curve_private_key_bytes = parse_octet_string(cx.vm(), private_key_info.raw_key())?;
// 8. Let key be a new CryptoKey that represents the X25519 private key identified by curvePrivateKey.
- key = CryptoKey::from_okp_handle(cx.vm(), true, curve_private_key_bytes.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::X25519, true, curve_private_key_bytes.as_slice())?;
// 9. Set the [[type]] internal slot of key to "private"
key.set_type(KeyType::Private);
@@ -11510,14 +11451,15 @@ impl AlgorithmMethods for X25519 {
return Err(dom_error("DataError", b"Invalid key length"));
}
- let derived_public_key = okp_generate_public_key(OkpCurve::X25519, private_key.as_slice())
- .map_err(|()| out_of_memory(cx.vm()))?;
+ let private_key = okp_key_handle(cx.vm(), OkpCurve::X25519, true, private_key.as_slice())?;
+ let derived_public_key =
+ libcrypto_rust::okp_raw_public_key(&private_key).map_err(|_| out_of_memory(cx.vm()))?;
if derived_public_key.as_slice() != public_key.as_slice() {
return Err(dom_error("DataError", b"Invalid key pair"));
}
// 2. Let key be a new CryptoKey object that represents the X25519 private key identified by interpreting jwk according to Section 2 of [RFC8037].
- key = CryptoKey::from_okp_handle(cx.vm(), true, private_key.as_slice());
+ key = CryptoKey::create(cx.vm(), private_key);
// 3. Set the [[type]] internal slot of Key to "private".
key.set_type(KeyType::Private);
@@ -11553,7 +11495,7 @@ impl AlgorithmMethods for X25519 {
// 2. Let key be a new CryptoKey object that represents the X25519 public key identified by interpreting
// jwk according to Section 2 of [RFC8037].
- key = CryptoKey::from_okp_handle(cx.vm(), false, public_key.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::X25519, false, public_key.as_slice())?;
// 3. Set the [[type]] internal slot of Key to "public".
key.set_type(KeyType::Public);
@@ -11584,7 +11526,7 @@ impl AlgorithmMethods for X25519 {
}
// 5. Let key be a new CryptoKey representing the key data provided in keyData.
- key = CryptoKey::from_okp_handle(cx.vm(), false, data.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::X25519, false, data.as_slice())?;
// 6. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -11629,7 +11571,7 @@ impl AlgorithmMethods for X25519 {
// * Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
// * Set the algorithm object identifier to the id-X25519 OID defined in [RFC8410].
// * Set the subjectPublicKey field to keyData.
- let data = okp_export_der(cx.vm(), OkpCurve::X25519, true, key.okp_handle_bytes())?;
+ let data = okp_export_der(cx.vm(), &key)?;
// 3. Let result be the result of DER-encoding data.
ExportKeyResult::Bytes(data)
@@ -11651,7 +11593,7 @@ impl AlgorithmMethods for X25519 {
// Section 7 of [RFC8410], that represents the X25519 private key represented by the [[handle]]
// internal slot of key
- let data = okp_export_der(cx.vm(), OkpCurve::X25519, false, key.okp_handle_bytes())?;
+ let data = okp_export_der(cx.vm(), &key)?;
// 3. Let result be the result of DER-encoding data.
ExportKeyResult::Bytes(data)
@@ -11668,24 +11610,13 @@ impl AlgorithmMethods for X25519 {
jwk.crv = Some(Utf16String::from_ascii(b"X25519"));
// 4. Set the x attribute of jwk according to the definition in Section 2 of [RFC8037].
- if key.key_type() == KeyType::Public {
- let public_key = key.okp_handle_bytes();
- jwk.x = Some(base64_url_bytes_encode(public_key));
- } else {
- // The "x" parameter of the "epk" field is set as follows:
- // Apply the appropriate ECDH function to the ephemeral private key (as scalar input)
- // and the standard base point (as u-coordinate input).
- // The base64url encoding of the output is the value for the "x" parameter of the "epk" field.
- let public_key = okp_generate_public_key(OkpCurve::X25519, key.okp_handle_bytes())
- .map_err(|()| out_of_memory(cx.vm()))?;
- jwk.x = Some(base64_url_bytes_encode(public_key.as_slice()));
- }
+ jwk.x = Some(base64_url_bytes_encode(okp_raw_public_key(cx.vm(), &key)?.as_slice()));
// 5. If the [[type]] internal slot of key is "private"
if key.key_type() == KeyType::Private {
// Set the d attribute of jwk according to the definition in Section 2 of [RFC8037].
- let private_key = key.okp_handle_bytes();
- jwk.d = Some(base64_url_bytes_encode(private_key));
+ let private_key = okp_raw_private_key(cx.vm(), &key)?;
+ jwk.d = Some(base64_url_bytes_encode(&private_key));
}
// 6. Set the key_ops attribute of jwk to the usages attribute of key.
@@ -11713,10 +11644,10 @@ impl AlgorithmMethods for X25519 {
// 2. Let data be a byte sequence representing the X25519 public key represented by the [[handle]] internal
// slot of key.
- let public_key = key.okp_handle_bytes();
+ let public_key = okp_raw_public_key(cx.vm(), &key)?;
// 3. Let result be data.
- ExportKeyResult::Bytes(Bytes::new(public_key.to_vec()))
+ ExportKeyResult::Bytes(public_key)
}
// 3. Otherwise:
// throw a NotSupportedError.
@@ -11785,11 +11716,7 @@ impl AlgorithmMethods for X448 {
// 5. Let secret be the result of performing the X448 function specified in [RFC7748] Section 5
// with key as the X448 private key k and the X448 public key represented by the [[handle]]
// internal slot of publicKey as the X448 public key u.
- let private_key = key.okp_handle_bytes();
- let public_key_data = public_key.okp_handle_bytes();
-
- let secret =
- libcrypto_rust::okp_compute_coordinate(OkpCurve::X448, private_key, public_key_data).map(Bytes::new);
+ let secret = libcrypto_rust::okp_compute_coordinate(key.handle(), public_key.handle()).map(Bytes::new);
let Ok(secret) = secret else {
return Err(dom_error("OperationError", b"Failed to compute secret"));
};
@@ -11850,17 +11777,12 @@ impl AlgorithmMethods for X448 {
}
// 2. Generate an X448 key pair, with the private key being 56 random bytes, and the public key being X448(a, 5), as defined in [RFC7748], section 6.2.
- let maybe_private_key = okp_generate_private_key(OkpCurve::X448);
- let Ok(private_key_data) = maybe_private_key else {
- return Err(dom_error("OperationError", b"Failed to generate private key"));
- };
- let maybe_public_key = okp_generate_public_key(OkpCurve::X448, private_key_data.as_slice());
- let Ok(public_key_data) = maybe_public_key else {
- return Err(dom_error("OperationError", b"Failed to generate public key"));
+ let Ok(key_pair) = libcrypto_rust::okp_generate_key_pair(OkpCurve::X448) else {
+ return Err(dom_error("OperationError", b"Failed to generate key pair"));
};
// 5. Let publicKey be a new CryptoKey associated with the relevant global object of this [HTML], and representing the public key of the generated key pair.
- let public_key = CryptoKey::from_okp_handle(cx.vm(), false, public_key_data.as_slice());
+ let public_key = CryptoKey::create(cx.vm(), key_pair.public_key);
// 6. Set the [[type]] internal slot of publicKey to "public"
public_key.set_type(KeyType::Public);
@@ -11879,7 +11801,7 @@ impl AlgorithmMethods for X448 {
public_key.set_usages(Vec::new());
// 10. Let privateKey be a new CryptoKey associated with the relevant global object of this [HTML], and representing the private key of the generated key pair.
- let private_key = CryptoKey::from_okp_handle(cx.vm(), true, private_key_data.as_slice());
+ let private_key = CryptoKey::create(cx.vm(), key_pair.private_key);
// 11. Set the [[type]] internal slot of privateKey to "private"
private_key.set_type(KeyType::Private);
@@ -11930,7 +11852,7 @@ impl AlgorithmMethods for X448 {
// * Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
// * Set the algorithm object identifier to the id-X448 OID defined in [RFC8410].
// * Set the subjectPublicKey field to keyData.
- let data = okp_export_der(cx.vm(), OkpCurve::X448, true, key.okp_handle_bytes())?;
+ let data = okp_export_der(cx.vm(), &key)?;
// 3. Let result be a new ArrayBuffer associated with the relevant global object of this [HTML], and containing data.
return Ok(ExportKeyResult::Bytes(data));
@@ -11953,7 +11875,7 @@ impl AlgorithmMethods for X448 {
// Section 7 of [RFC8410], that represents the X448 private key represented by the [[handle]] internal
// slot of key
- let data = okp_export_der(cx.vm(), OkpCurve::X448, false, key.okp_handle_bytes())?;
+ let data = okp_export_der(cx.vm(), &key)?;
// 3. Let result be a new ArrayBuffer associated with the relevant global object of this [HTML], and containing data.
return Ok(ExportKeyResult::Bytes(data));
@@ -11971,18 +11893,12 @@ impl AlgorithmMethods for X448 {
jwk.crv = Some(Utf16String::from_ascii(b"X448"));
// 4. Set the x attribute of jwk according to the definition in Section 2 of [RFC8037].
- if key.key_type() == KeyType::Public {
- jwk.x = Some(base64_url_bytes_encode(key.okp_handle_bytes()));
- } else {
- let public_key = okp_generate_public_key(OkpCurve::X448, key.okp_handle_bytes())
- .map_err(|()| out_of_memory(cx.vm()))?;
- jwk.x = Some(base64_url_bytes_encode(public_key.as_slice()));
- }
+ jwk.x = Some(base64_url_bytes_encode(okp_raw_public_key(cx.vm(), &key)?.as_slice()));
// 5. If the [[type]] internal slot of key is "private"
if key.key_type() == KeyType::Private {
// Set the d attribute of jwk according to the definition in Section 2 of [RFC8037].
- jwk.d = Some(base64_url_bytes_encode(key.okp_handle_bytes()));
+ jwk.d = Some(base64_url_bytes_encode(&okp_raw_private_key(cx.vm(), &key)?));
}
// 6. Set the key_ops attribute of jwk to the usages attribute of key.
@@ -12010,7 +11926,7 @@ impl AlgorithmMethods for X448 {
// 2. Let data be an octet string representing the X448 public key represented by the [[handle]] internal slot of key.
// 3. Let result be a new ArrayBuffer associated with the relevant global object of this [HTML], and containing data.
// 4. Return result.
- return Ok(ExportKeyResult::Bytes(Bytes::new(key.okp_handle_bytes().to_vec())));
+ return Ok(ExportKeyResult::Bytes(okp_raw_public_key(cx.vm(), &key)?));
}
// 3. Otherwise:
@@ -12066,7 +11982,7 @@ impl AlgorithmMethods for X448 {
let public_key = spki.raw_key();
// 7. Let key be a new CryptoKey associated with the relevant global object of this [HTML], and that represents publicKey.
- let key = CryptoKey::from_okp_handle(cx.vm(), false, public_key);
+ let key = okp_key(cx.vm(), OkpCurve::X448, false, public_key)?;
// 8. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -12117,7 +12033,7 @@ impl AlgorithmMethods for X448 {
let curve_private_key_bytes = parse_octet_string(cx.vm(), private_key_info.raw_key())?;
// 8. Let key be a new CryptoKey associated with the relevant global object of this [HTML], and that represents the X448 private key identified by curvePrivateKey.
- let key = CryptoKey::from_okp_handle(cx.vm(), true, curve_private_key_bytes.as_slice());
+ let key = okp_key(cx.vm(), OkpCurve::X448, true, curve_private_key_bytes.as_slice())?;
// 9. Set the [[type]] internal slot of key to "private"
key.set_type(KeyType::Private);
@@ -12224,14 +12140,15 @@ impl AlgorithmMethods for X448 {
return Err(dom_error("DataError", b"Invalid key length"));
}
- let derived_public_key = okp_generate_public_key(OkpCurve::X448, private_key.as_slice())
- .map_err(|()| out_of_memory(cx.vm()))?;
+ let private_key = okp_key_handle(cx.vm(), OkpCurve::X448, true, private_key.as_slice())?;
+ let derived_public_key =
+ libcrypto_rust::okp_raw_public_key(&private_key).map_err(|_| out_of_memory(cx.vm()))?;
if derived_public_key.as_slice() != public_key.as_slice() {
return Err(dom_error("DataError", b"Invalid key pair"));
}
// 2. Let key be a new CryptoKey object that represents the X448 private key identified by interpreting jwk according to Section 2 of [RFC8037].
- key = CryptoKey::from_okp_handle(cx.vm(), true, private_key.as_slice());
+ key = CryptoKey::create(cx.vm(), private_key);
// 3. Set the [[type]] internal slot of Key to "private".
key.set_type(KeyType::Private);
@@ -12266,7 +12183,7 @@ impl AlgorithmMethods for X448 {
}
// 2. Let key be a new CryptoKey object that represents the X448 public key identified by interpreting jwk according to Section 2 of [RFC8037].
- key = CryptoKey::from_okp_handle(cx.vm(), false, public_key.as_slice());
+ key = okp_key(cx.vm(), OkpCurve::X448, false, public_key.as_slice())?;
// 3. Set the [[type]] internal slot of Key to "public".
key.set_type(KeyType::Public);
@@ -12300,7 +12217,7 @@ impl AlgorithmMethods for X448 {
}
// 6. Let key be a new CryptoKey associated with the relevant global object of this [HTML], and that represents data.
- let key = CryptoKey::from_okp_handle(cx.vm(), false, data.as_slice());
+ let key = okp_key(cx.vm(), OkpCurve::X448, false, data.as_slice())?;
// 7. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -13824,6 +13741,5 @@ impl AlgorithmMethods for MlKem {
}
pub(crate) fn public_key_for_private_key(vm: &Vm, key: Ref<CryptoKey>) -> Option<Ref<CryptoKey>> {
- let name = key.algorithm_name();
- libcrypto_rust::public_key_for_private_key(key.handle(), &name).map(|handle| CryptoKey::create(vm, handle))
+ libcrypto_rust::public_key_for_private_key(key.handle()).map(|handle| CryptoKey::create(vm, handle))
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
index 3a3e6205889..d809cfde7d8 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::{HandleTag, KeyHandle};
+use libcrypto_rust::{HandleTag, KeyHandle, OkpCurve};
use libjs_rust::api::{
Array, CellRoot, ErrorKind, ErrorType, Gc, GcRefCell, GcWeak, IntegrityLevel, MarkedVec, Must, Object,
PrimitiveString, PropertyKey, Trace, Value, Vm,
@@ -272,14 +272,6 @@ impl CryptoKey {
self.handle.secret_bytes()
}
- pub(crate) fn from_okp_handle(vm: &Vm, is_private: bool, bytes: &[u8]) -> Ref<Self> {
- Self::create(vm, KeyHandle::from_okp_bytes(is_private, bytes))
- }
-
- pub(crate) fn okp_handle_bytes(&self) -> &[u8] {
- self.handle.okp_bytes()
- }
-
pub(crate) fn handle(&self) -> &KeyHandle {
&self.handle
}
@@ -509,8 +501,7 @@ impl Serializable for CryptoKey {
// has-public-key flag, which is true, before its public key's buffers.
let stored = self.handle().to_stored();
serialized.write_u8(stored.tag as u8);
- let buffers = stored.buffers();
- for (index, buffer) in buffers.into_iter().enumerate() {
+ for (index, buffer) in stored.buffers().iter().enumerate() {
serialized.write_bytes(buffer);
if index == 0 && stored.tag == HandleTag::EcPrivate {
serialized.write_bool(false);
@@ -603,11 +594,20 @@ impl Serializable for CryptoKey {
}
}
+ let okp_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 Ok(handle) = KeyHandle::from_stored(
handle_tag,
&buffers,
has_ec_parameters.then_some(ec_parameters.as_slice()),
has_ec_public_key,
+ okp_curve,
) else {
return Err(data_clone_error(b"Invalid CryptoKey handle components"));
};
diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.h
index d43dd7b19e0..a1b82a3e13a 100644
--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h
+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h
@@ -735,6 +735,17 @@ inline ModuleLatticeKey mlkem_512_key()
return module_lattice_key_from_seed("ML-KEM-512", seed);
}
+// The key pair of RFC 8032's first Ed25519 test vector.
+inline Vector<u8> ed25519_public_key()
+{
+ return { 0xd7, 0x5a, 0x98, 0x01, 0x82, 0xb1, 0x0a, 0xb7, 0xd5, 0x4b, 0xfe, 0xd3, 0xc9, 0x64, 0x07, 0x3a, 0x0e, 0xe1, 0x72, 0xf3, 0xda, 0xa6, 0x23, 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07, 0x51, 0x1a };
+}
+
+inline Vector<u8> ed25519_private_key()
+{
+ return { 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60 };
+}
+
inline Vector<CryptoHandleGolden> crypto_handle_goldens()
{
using Web::Crypto::HandleTag;
@@ -747,7 +758,8 @@ inline Vector<CryptoHandleGolden> crypto_handle_goldens()
auto d = p256_private_value_one();
auto mldsa = mldsa_44_key();
auto mlkem = mlkem_512_key();
- auto okp = "okpokpokpokpokpo"sv.bytes();
+ auto okp_public_key = ed25519_public_key();
+ auto okp_private_key = ed25519_private_key();
Array<ReadonlyBytes, 8> rsa_components { modulus, exponent, exponent, modulus, modulus, exponent, exponent, modulus };
Vector<CryptoHandleGolden> goldens;
@@ -762,8 +774,8 @@ inline Vector<CryptoHandleGolden> crypto_handle_goldens()
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) });
+ goldens.append({ HandleTag::OKPPublicKey, "public"sv, "verify"sv, alg_key_algorithm("Ed25519"sv), handle_single_buffer(9, okp_public_key) });
+ goldens.append({ HandleTag::OKPPrivateKey, "private"sv, "sign"sv, alg_key_algorithm("Ed25519"sv), handle_single_buffer(10, okp_private_key) });
return goldens;
}
diff --git a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-10.bin b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-10.bin
index e7718682d2f..f0d5e3e0917 100644
Binary files a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-10.bin and b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-10.bin differ
diff --git a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-9.bin b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-9.bin
index 6b77c913895..be7cc865f8e 100644
Binary files a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-9.bin and b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-9.bin differ