Replace SharedSecret with a more generic alternative

This commit is contained in:
Elichai Turkel 2019-11-10 00:02:44 +02:00
parent e3aaf00710
commit 9759cb07f5
No known key found for this signature in database
GPG Key ID: 9383CDE9E8E66A7F
4 changed files with 93 additions and 83 deletions

View File

@ -72,7 +72,7 @@ pub type EcdhHashFn = unsafe extern "C" fn(
x: *const c_uchar, x: *const c_uchar,
y: *const c_uchar, y: *const c_uchar,
data: *mut c_void, data: *mut c_void,
); ) -> c_int;
/// A Secp256k1 context, containing various precomputed values and such /// A Secp256k1 context, containing various precomputed values and such
/// needed to do elliptic curve computations. If you create one of these /// needed to do elliptic curve computations. If you create one of these
@ -134,25 +134,6 @@ impl Default for Signature {
} }
} }
/// Library-internal representation of an ECDH shared secret
#[repr(C)]
pub struct SharedSecret([c_uchar; 32]);
impl_array_newtype!(SharedSecret, c_uchar, 32);
impl_raw_debug!(SharedSecret);
impl SharedSecret {
/// Create a new (zeroed) signature usable for the FFI interface
pub fn new() -> SharedSecret { SharedSecret([0; 32]) }
/// Create a new (uninitialized) signature usable for the FFI interface
#[deprecated(since = "0.15.3", note = "Please use the new function instead")]
pub unsafe fn blank() -> SharedSecret { SharedSecret::new() }
}
impl Default for SharedSecret {
fn default() -> Self {
SharedSecret::new()
}
}
#[cfg(not(feature = "fuzztarget"))] #[cfg(not(feature = "fuzztarget"))]
extern "C" { extern "C" {
@ -296,7 +277,7 @@ extern "C" {
#[cfg_attr(not(feature = "external-symbols"), link_name = "rustsecp256k1_v0_1_0_ecdh")] #[cfg_attr(not(feature = "external-symbols"), link_name = "rustsecp256k1_v0_1_0_ecdh")]
pub fn secp256k1_ecdh( pub fn secp256k1_ecdh(
cx: *const Context, cx: *const Context,
output: *mut SharedSecret, output: *mut c_uchar,
pubkey: *const PublicKey, pubkey: *const PublicKey,
privkey: *const c_uchar, privkey: *const c_uchar,
hashfp: EcdhHashFn, hashfp: EcdhHashFn,

View File

@ -144,6 +144,7 @@ macro_rules! impl_array_newtype {
} }
} }
#[macro_export]
macro_rules! impl_raw_debug { macro_rules! impl_raw_debug {
($thing:ident) => { ($thing:ident) => {
impl ::core::fmt::Debug for $thing { impl ::core::fmt::Debug for $thing {

View File

@ -16,83 +16,94 @@
//! Support for shared secret computations //! Support for shared secret computations
//! //!
use core::{ops, ptr}; use core::ptr;
use core::ops::Deref;
use key::{SecretKey, PublicKey}; use key::{SecretKey, PublicKey};
use ffi::{self, CPtr}; use ffi::{self, CPtr};
/// A tag used for recovering the public key from a compact signature /// A tag used for recovering the public key from a compact signature
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone)]
pub struct SharedSecret(ffi::SharedSecret); pub struct SharedSecret {
data: [u8; 256],
len: usize,
}
impl_raw_debug!(SharedSecret);
// This implementes `From<N>` for all `[u8; N]` arrays from 128bits(16 byte) to 2048bits allowing known hash lengths.
// Lower than 128 bits isn't resistant to collisions any more.
impl_from_array_len!(SharedSecret, 256, (16 20 28 32 48 64 96 128 256));
impl SharedSecret {
/// Create an empty SharedSecret
pub(crate) fn empty() -> SharedSecret {
SharedSecret {
data: [0u8; 256],
len: 0,
}
}
/// Get a pointer to the underlying data with the specified capacity.
pub(crate) fn get_data_mut_ptr(&mut self) -> *mut u8 {
self.data.as_mut_ptr()
}
/// Get the capacity of the underlying data buffer.
pub fn capacity(&self) -> usize {
self.data.len()
}
/// Get the len of the used data.
pub fn len(&self) -> usize {
self.len
}
/// Set the length of the object.
pub(crate) fn set_len(&mut self, len: usize) {
self.len = len;
}
}
impl PartialEq for SharedSecret {
fn eq(&self, other: &SharedSecret) -> bool {
&self.data[..self.len] == &other.data[..other.len]
}
}
impl AsRef<[u8]> for SharedSecret {
fn as_ref(&self) -> &[u8] {
&self.data[..self.len]
}
}
impl Deref for SharedSecret {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.data[..self.len]
}
}
impl SharedSecret { impl SharedSecret {
/// Creates a new shared secret from a pubkey and secret key /// Creates a new shared secret from a pubkey and secret key
#[inline] #[inline]
pub fn new(point: &PublicKey, scalar: &SecretKey) -> SharedSecret { pub fn new(point: &PublicKey, scalar: &SecretKey) -> SharedSecret {
unsafe { let mut ss = SharedSecret::empty();
let mut ss = ffi::SharedSecret::new(); let res = unsafe {
let res = ffi::secp256k1_ecdh( ffi::secp256k1_ecdh(
ffi::secp256k1_context_no_precomp, ffi::secp256k1_context_no_precomp,
&mut ss, ss.get_data_mut_ptr(),
point.as_c_ptr(), point.as_c_ptr(),
scalar.as_c_ptr(), scalar.as_c_ptr(),
ffi::secp256k1_ecdh_hash_function_default, ffi::secp256k1_ecdh_hash_function_default,
ptr::null_mut(), ptr::null_mut(),
); )
debug_assert_eq!(res, 1); };
SharedSecret(ss) debug_assert_eq!(res, 1); // The default `secp256k1_ecdh_hash_function_default` should always return 1.
} ss.set_len(32); // The default hash function is SHA256, which is 32 bytes long.
} ss
/// Obtains a raw pointer suitable for use with FFI functions
#[inline]
pub fn as_ptr(&self) -> *const ffi::SharedSecret {
&self.0 as *const _
}
}
/// Creates a new shared secret from a FFI shared secret
impl From<ffi::SharedSecret> for SharedSecret {
#[inline]
fn from(ss: ffi::SharedSecret) -> SharedSecret {
SharedSecret(ss)
}
}
impl ops::Index<usize> for SharedSecret {
type Output = u8;
#[inline]
fn index(&self, index: usize) -> &u8 {
&self.0[index]
}
}
impl ops::Index<ops::Range<usize>> for SharedSecret {
type Output = [u8];
#[inline]
fn index(&self, index: ops::Range<usize>) -> &[u8] {
&self.0[index]
}
}
impl ops::Index<ops::RangeFrom<usize>> for SharedSecret {
type Output = [u8];
#[inline]
fn index(&self, index: ops::RangeFrom<usize>) -> &[u8] {
&self.0[index.start..]
}
}
impl ops::Index<ops::RangeFull> for SharedSecret {
type Output = [u8];
#[inline]
fn index(&self, _: ops::RangeFull) -> &[u8] {
&self.0[..]
} }
} }

View File

@ -27,6 +27,23 @@ macro_rules! impl_pretty_debug {
} }
} }
macro_rules! impl_from_array_len {
($thing:ident, $capacity:tt, ($($N:tt)+)) => {
$(
impl From<[u8; $N]> for $thing {
fn from(arr: [u8; $N]) -> Self {
let mut data = [0u8; $capacity];
data[..$N].copy_from_slice(&arr);
$thing {
data,
len: $N,
}
}
}
)+
}
}
#[cfg(feature="serde")] #[cfg(feature="serde")]
/// Implements `Serialize` and `Deserialize` for a type `$t` which represents /// Implements `Serialize` and `Deserialize` for a type `$t` which represents
/// a newtype over a byte-slice over length `$len`. Type `$t` must implement /// a newtype over a byte-slice over length `$len`. Type `$t` must implement