Skip to content

Commit c17860f

Browse files
authored
When serializing EC private keys, ensure the key is padded out to the group degree (#13657)
1 parent d8eb450 commit c17860f

File tree

2 files changed

+14
-1
lines changed
  • src/rust/cryptography-key-parsing/src
  • tests/hazmat/primitives

2 files changed

+14
-1
lines changed

src/rust/cryptography-key-parsing/src/ec.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,9 @@ pub fn serialize_pkcs1_private_key(
130130
None
131131
};
132132

133-
let private_key_bytes = ec.private_key().to_vec();
133+
let private_key_bytes = ec
134+
.private_key()
135+
.to_vec_padded(ec.group().order_bits().div_ceil(8).try_into().unwrap())?;
134136

135137
let mut bn_ctx = openssl::bn::BigNumContext::new()?;
136138
let public_key_bytes = ec.public_key().to_bytes(

tests/hazmat/primitives/test_ec.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1237,6 +1237,17 @@ def test_private_bytes_high_private_key_bit_set(self):
12371237
== data
12381238
)
12391239

1240+
def test_private_bytes_small_key(self):
1241+
key = ec.derive_private_key(private_value=1, curve=ec.SECP256R1())
1242+
der = key.private_bytes(
1243+
serialization.Encoding.DER,
1244+
serialization.PrivateFormat.TraditionalOpenSSL,
1245+
serialization.NoEncryption(),
1246+
)
1247+
# Ensure that serialized keys are always padded to the group order
1248+
# length.
1249+
assert (b"\x00" * 31 + b"\x01") in der
1250+
12401251

12411252
class TestEllipticCurvePEMPublicKeySerialization:
12421253
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)