diff --git a/ecdsa/Cargo.toml b/ecdsa/Cargo.toml index d5293ac2..89d2d5e9 100644 --- a/ecdsa/Cargo.toml +++ b/ecdsa/Cargo.toml @@ -24,12 +24,13 @@ sha2 = { version = "0.9", default-features = false } [features] default = ["digest"] +alloc = [] dev = ["digest", "zeroize"] digest = ["elliptic-curve/digest", "signature/digest-preview"] hazmat = [] rand = ["elliptic-curve/rand", "signature/rand-preview"] sign = ["digest", "hazmat", "hmac", "zeroize"] -std = ["elliptic-curve/std", "signature/std"] +std = ["alloc", "elliptic-curve/std", "signature/std"] verify = ["digest", "hazmat"] zeroize = ["elliptic-curve/zeroize"] diff --git a/ecdsa/src/asn1.rs b/ecdsa/src/asn1.rs index c9c5cfbd..89e9ed08 100644 --- a/ecdsa/src/asn1.rs +++ b/ecdsa/src/asn1.rs @@ -17,6 +17,9 @@ use core::{ }; use elliptic_curve::{consts::U9, weierstrass::Curve, ElementBytes}; +#[cfg(feature = "alloc")] +use alloc::boxed::Box; + /// Maximum overhead of an ASN.1 DER-encoded ECDSA signature for a given curve: /// 9-bytes. /// @@ -92,6 +95,17 @@ where self.s_range.end } + /// Borrow this signature as a byte slice + pub fn as_bytes(&self) -> &[u8] { + &self.bytes.as_slice()[..self.len()] + } + + /// Serialize this signature as a boxed byte slice + #[cfg(feature = "alloc")] + pub fn to_bytes(&self) -> Box<[u8]> { + self.as_bytes().to_vec().into_boxed_slice() + } + /// Create an ASN.1 DER encoded signature from the `r` and `s` scalars pub(crate) fn from_scalars(r: &ElementBytes, s: &ElementBytes) -> Self { let r_len = int_length(r); @@ -144,7 +158,7 @@ where ::Output: Add + ArrayLength, { fn as_ref(&self) -> &[u8] { - &self.bytes.as_slice()[..self.len()] + self.as_bytes() } } diff --git a/ecdsa/src/lib.rs b/ecdsa/src/lib.rs index b905d55e..709a5e53 100644 --- a/ecdsa/src/lib.rs +++ b/ecdsa/src/lib.rs @@ -27,6 +27,9 @@ html_root_url = "https://docs.rs/ecdsa/0.7.2" )] +#[cfg(feature = "alloc")] +extern crate alloc; + pub mod asn1; #[cfg(feature = "dev")]