Skip to content

Truly independent web browser

LibCrypto: Export EC private keys as other browsers do

Shannon Boothce51485f86a7
diff --git a/Libraries/LibCrypto/Rust/src/ec.rs b/Libraries/LibCrypto/Rust/src/ec.rs
index dd2f37c6759..6bbe6058b6e 100644
--- a/Libraries/LibCrypto/Rust/src/ec.rs
+++ b/Libraries/LibCrypto/Rust/src/ec.rs
@@ -21,13 +21,10 @@ pub(crate) struct EcPublicKey {
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>,
+ public_key: EcPublicKey,
}
impl EcCurve {
@@ -154,18 +151,13 @@ 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)
+ let (x, y) = coordinates(&key, curve)?;
+ let public_key = EcPublicKey::from_coordinates(&x, &y)?;
+ Ok(Self { key, curve, public_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> {
+ fn from_scalar(d: &[u8], 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"))?;
@@ -181,36 +173,17 @@ impl EcPrivateKey {
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,
- })
+ let public_key = match public_key {
+ Some(public_key) => public_key,
+ None => EcPublicKey::from_octets(&point)?,
+ };
+ Ok(Self { key, curve, 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
@@ -238,24 +211,21 @@ pub(crate) fn parse_private_key_info(curve: EcCurve, key: Pkey, encoded: &[u8])
.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 private_key = EcPrivateKey::from_scalar(&d, None)?;
+ let uncompressed = private_key.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 parameters in [None, Some(curve)] {
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;
+ if matches {
+ return Ok(KeyHandle(Key::EcPrivate(private_key)));
}
- 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"))
@@ -282,7 +252,7 @@ fn private_key(key: &KeyHandle) -> &EcPrivateKey {
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)?;
+ let public_key = private_key.public_key.clone();
Ok(KeyPair {
public_key: KeyHandle(Key::EcPublic(public_key)),
private_key: KeyHandle(Key::EcPrivate(private_key)),
@@ -314,7 +284,7 @@ pub fn ec_key_from_coordinates(x: &[u8], y: &[u8], d: Option<&[u8]>) -> Option<K
let Some(d) = d else {
return Some(KeyHandle(Key::EcPublic(public_key)));
};
- let private_key = EcPrivateKey::from_scalar(d, false, Some(public_key)).ok()?;
+ let private_key = EcPrivateKey::from_scalar(d, Some(public_key)).ok()?;
Some(KeyHandle(Key::EcPrivate(private_key)))
}
@@ -342,10 +312,15 @@ pub fn ec_export_der(curve: EcCurve, key: &KeyHandle, is_public: bool) -> Result
&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)
+ // NB: The ECPrivateKey has its public key and not its parameters, which the PrivateKeyInfo already has.
+ let private_key = private_key(key);
+ let public_point = private_key.public_key.to_uncompressed()?;
+ let encoded = SecretBytes::new(encode_private_key(&private_key.d_bytes()?, None, Some(&public_point)));
+ Ok(der::private_key_info(
+ KeyAlgorithm::Ec.oid(),
+ Some(&parameters),
+ &encoded,
+ ))
}
pub fn ec_export_uncompressed(key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
@@ -355,10 +330,7 @@ pub fn ec_export_uncompressed(key: &KeyHandle) -> Result<Vec<u8>, CryptoError> {
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(),
- },
+ Key::EcPrivate(private_key) => private_key.public_key.coordinates(),
_ => panic!("The key is not an EC key"),
}
}
@@ -383,10 +355,7 @@ 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()?)))
+ Some(KeyHandle(Key::EcPublic(private_key.public_key.clone())))
}
impl EcPublicKey {
@@ -398,20 +367,20 @@ impl EcPublicKey {
}
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.
+ /// The stored form of the key: its private value, then its public key's coordinates.
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(),
- }
+ let (x, y) = self
+ .public_key
+ .coordinates()
+ .expect("OpenSSL gives an EC key's coordinates");
+ StoredKey::new(
+ HandleTag::EcPrivate,
+ vec![
+ self.d_bytes().expect("OpenSSL gives an EC key's private value"),
+ SecretBytes::new(x),
+ SecretBytes::new(y),
+ ],
+ )
}
}
@@ -433,9 +402,8 @@ pub(crate) fn decode_stored(
} 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.
+ let private_key = EcPrivateKey::from_scalar(buffers[0], public_key).map_err(invalid)?;
+ // NB: A stored key may have its own curve's parameters, and may not have its public key.
if parameters.is_some_and(|parameters| parameters != private_key.curve.arcs()) {
return Err(KeyDecodeError::InvalidComponents);
}
diff --git a/Libraries/LibCrypto/Rust/src/key.rs b/Libraries/LibCrypto/Rust/src/key.rs
index ea16ee0bc2e..f39fd5e250f 100644
--- a/Libraries/LibCrypto/Rust/src/key.rs
+++ b/Libraries/LibCrypto/Rust/src/key.rs
@@ -86,23 +86,16 @@ impl TryFrom<u8> for HandleTag {
}
}
-/// 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.
+/// The stored form of a key: its tag and its buffers. An EC private key's buffers are its private value and its public
+/// key's coordinates.
pub struct StoredKey {
pub tag: HandleTag,
- pub(crate) buffers: Vec<SecretBytes>,
- pub ec_parameters: Option<Vec<u32>>,
- pub has_ec_public_key: bool,
+ buffers: Vec<SecretBytes>,
}
impl StoredKey {
pub(crate) fn new(tag: HandleTag, buffers: Vec<SecretBytes>) -> Self {
- Self {
- tag,
- buffers,
- ec_parameters: None,
- has_ec_public_key: false,
- }
+ Self { tag, buffers }
}
pub fn buffers(&self) -> Vec<&[u8]> {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
index a878197904f..3a3e6205889 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs
@@ -505,29 +505,17 @@ impl Serializable for CryptoKey {
}
// 5. Set serialized.[[Handle]] to the [[handle]] internal slot of value.
- // NB: An EC private key's parameters and whether it has its public key follow its first buffer.
+ // NB: An EC private key's first buffer is followed by a has-parameters flag, which is false, and a
+ // 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();
- if stored.tag != HandleTag::EcPrivate {
- for buffer in buffers {
- serialized.write_bytes(buffer);
+ for (index, buffer) in buffers.into_iter().enumerate() {
+ serialized.write_bytes(buffer);
+ if index == 0 && stored.tag == HandleTag::EcPrivate {
+ serialized.write_bool(false);
+ serialized.write_bool(true);
}
- return Ok(());
- }
-
- 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(())
}
diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.h
index fec66cd2d21..d43dd7b19e0 100644
--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h
+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h
@@ -644,6 +644,13 @@ inline Vector<u8> ec_coordinate(u8 fill)
}
// The base point of P-256, which EC key handles must hold a point on.
+inline Vector<u8> p256_private_value_one()
+{
+ auto bytes = ec_coordinate(0);
+ bytes.last() = 1;
+ return bytes;
+}
+
inline Vector<u8> p256_base_point_x()
{
return { 0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96 };
@@ -736,7 +743,8 @@ inline Vector<CryptoHandleGolden> crypto_handle_goldens()
Array<u8, 4> modulus { 0xC0, 0x00, 0x00, 0x01 };
auto x = p256_base_point_x();
auto y = p256_base_point_y();
- auto d = ec_coordinate(0x33);
+ // NB: The base point is the public key of the private value 1.
+ auto d = p256_private_value_one();
auto mldsa = mldsa_44_key();
auto mlkem = mlkem_512_key();
auto okp = "okpokpokpokpokpo"sv.bytes();
@@ -749,7 +757,7 @@ inline Vector<CryptoHandleGolden> crypto_handle_goldens()
goldens.append({ HandleTag::RSAPrivateKey, "private"sv, "sign"sv,
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::ECPrivateKey, "private"sv, "sign"sv, alg_ec_key_algorithm("ECDSA"sv, "P-256"sv), handle_ec_private_key(d, {}, Array<ReadonlyBytes, 2> { x, y }) });
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) });
diff --git a/Tests/LibWeb/TestStructuredSerializeDurability.cpp b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
index 56479a3e5be..08ef28bb2e8 100644
--- a/Tests/LibWeb/TestStructuredSerializeDurability.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
@@ -645,6 +645,24 @@ TEST_CASE(crypto_key_handle_variants_decode_from_frozen_bytes)
}
}
+TEST_CASE(crypto_key_ec_private_key_stored_without_its_public_key_or_with_its_parameters_decodes)
+{
+ auto x = p256_base_point_x();
+ auto y = p256_base_point_y();
+ auto d = p256_private_value_one();
+ Vector<int> p256 { 1, 2, 840, 10045, 3, 1, 7 };
+ auto algorithm = alg_ec_key_algorithm("ECDSA"sv, "P-256"sv);
+ auto expected = crypto_key_full_record("private"sv, "sign"sv, algorithm, handle_ec_private_key(d, {}, Array<ReadonlyBytes, 2> { x, y }));
+
+ // A stored EC private key may have its curve's parameters and may not have its public key. It is stored again with
+ // its public key and without parameters.
+ for (auto const& handle : { handle_ec_private_key(d, {}, {}), handle_ec_private_key(d, p256, {}), handle_ec_private_key(d, p256, Array<ReadonlyBytes, 2> { x, y }) }) {
+ auto record = crypto_key_full_record("private"sv, "sign"sv, algorithm, handle);
+ auto value = MUST(principal_storage_deserialize(record));
+ EXPECT_EQ(storage_serialize(GC::Ref { value.as_object() }).data.span(), expected.data.span());
+ }
+}
+
TEST_CASE(crypto_key_handle_completeness)
{
// Every HandleTag needs a decode golden.
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-EC-pkcs8-export-form.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-EC-pkcs8-export-form.txt
new file mode 100644
index 00000000000..6f97c1f3be5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-EC-pkcs8-export-form.txt
@@ -0,0 +1,5 @@
+params+pub: exported with the public key and without the parameters
+pub only: exported with the public key and without the parameters
+params only: exported with the public key and without the parameters
+neither: exported with the public key and without the parameters
+params+compressed pub: exported with the public key and without the parameters
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-EC-pkcs8-export-form.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-EC-pkcs8-export-form.html
new file mode 100644
index 00000000000..03e73b73e50
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-EC-pkcs8-export-form.html
@@ -0,0 +1,24 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ const bytes = string => Uint8Array.from(string.match(/../g), byte => parseInt(byte, 16));
+ const hex = buffer => Array.from(new Uint8Array(buffer), byte => byte.toString(16).padStart(2, "0")).join("");
+
+ promiseTest(async () => {
+ // The same P-256 key, its ECPrivateKey with or without the optional parameters and public key.
+ const forms = [
+ ["params+pub", "308193020100301306072a8648ce3d020106082a8648ce3d030107047930770201010420a210ff3aa9bcdbb7ff984e127bcbf1127492b99eae5b16ac022620f8fbc52a07a00a06082a8648ce3d030107a1440342000477657ff1b7a6ef5f7f1d41007335cf04f3e6ef93f8388dee6e4a3d62b656113d8e6973eae73689ad969b087be2703072af9ad480dab52759640f837b44b398ae"],
+ ["pub only", "308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b0201010420a210ff3aa9bcdbb7ff984e127bcbf1127492b99eae5b16ac022620f8fbc52a07a1440342000477657ff1b7a6ef5f7f1d41007335cf04f3e6ef93f8388dee6e4a3d62b656113d8e6973eae73689ad969b087be2703072af9ad480dab52759640f837b44b398ae"],
+ ["params only", "304d020100301306072a8648ce3d020106082a8648ce3d030107043330310201010420a210ff3aa9bcdbb7ff984e127bcbf1127492b99eae5b16ac022620f8fbc52a07a00a06082a8648ce3d030107"],
+ ["neither", "3041020100301306072a8648ce3d020106082a8648ce3d030107042730250201010420a210ff3aa9bcdbb7ff984e127bcbf1127492b99eae5b16ac022620f8fbc52a07"],
+ ["params+compressed pub", "3073020100301306072a8648ce3d020106082a8648ce3d030107045930570201010420a210ff3aa9bcdbb7ff984e127bcbf1127492b99eae5b16ac022620f8fbc52a07a00a06082a8648ce3d030107a1240322000277657ff1b7a6ef5f7f1d41007335cf04f3e6ef93f8388dee6e4a3d62b656113d"],
+ ];
+ // The form that other browsers export: with the uncompressed public key, without the parameters.
+ const exported = forms[1][1];
+ for (const [name, data] of forms) {
+ const key = await crypto.subtle.importKey("pkcs8", bytes(data), { name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]);
+ const result = hex(await crypto.subtle.exportKey("pkcs8", key));
+ println(`${name}: ${result === exported ? "exported with the public key and without the parameters" : result}`);
+ }
+ });
+</script>