2015-09-18 20:22:48 +00:00
|
|
|
// Bitcoin secp256k1 bindings
|
|
|
|
// Written in 2015 by
|
|
|
|
// Andrew Poelstra
|
|
|
|
//
|
|
|
|
// To the extent possible under law, the author(s) have dedicated all
|
|
|
|
// copyright and related and neighboring rights to this software to
|
|
|
|
// the public domain worldwide. This software is distributed without
|
|
|
|
// any warranty.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the CC0 Public Domain Dedication
|
|
|
|
// along with this software.
|
|
|
|
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
|
|
|
|
//
|
|
|
|
|
2021-11-17 23:52:28 +00:00
|
|
|
//! Support for shared secret computations.
|
2015-09-18 20:22:48 +00:00
|
|
|
//!
|
|
|
|
|
2021-09-14 09:18:22 +00:00
|
|
|
use core::{borrow::Borrow, ptr, str};
|
2015-09-18 20:22:48 +00:00
|
|
|
|
2019-11-09 22:03:44 +00:00
|
|
|
use secp256k1_sys::types::{c_int, c_uchar, c_void};
|
2021-09-14 09:18:22 +00:00
|
|
|
|
|
|
|
use crate::{constants, Error, ffi::{self, CPtr}, key::{PublicKey, SecretKey}};
|
2022-02-18 12:10:02 +00:00
|
|
|
|
|
|
|
// The logic for displaying shared secrets relies on this (see `secret.rs`).
|
|
|
|
const SHARED_SECRET_SIZE: usize = constants::SECRET_KEY_SIZE;
|
2015-09-18 20:22:48 +00:00
|
|
|
|
2022-02-04 00:52:38 +00:00
|
|
|
/// Enables two parties to create a shared secret without revealing their own secrets.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
2022-02-11 07:44:16 +00:00
|
|
|
/// # #[cfg(all(feature = "std", feature = "rand-std"))] {
|
2022-02-04 00:52:38 +00:00
|
|
|
/// # use secp256k1::Secp256k1;
|
|
|
|
/// # use secp256k1::ecdh::SharedSecret;
|
|
|
|
/// # use secp256k1::rand::thread_rng;
|
|
|
|
/// let s = Secp256k1::new();
|
|
|
|
/// let (sk1, pk1) = s.generate_keypair(&mut thread_rng());
|
|
|
|
/// let (sk2, pk2) = s.generate_keypair(&mut thread_rng());
|
2022-02-21 13:11:30 +00:00
|
|
|
/// let sec1 = SharedSecret::new(&pk2, &sk1);
|
|
|
|
/// let sec2 = SharedSecret::new(&pk1, &sk2);
|
2022-02-04 00:52:38 +00:00
|
|
|
/// assert_eq!(sec1, sec2);
|
|
|
|
/// # }
|
|
|
|
// ```
|
2022-02-18 12:10:02 +00:00
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
|
|
pub struct SharedSecret([u8; SHARED_SECRET_SIZE]);
|
|
|
|
impl_display_secret!(SharedSecret);
|
2019-11-09 22:03:44 +00:00
|
|
|
|
2019-11-09 22:02:44 +00:00
|
|
|
impl SharedSecret {
|
2021-11-17 23:58:38 +00:00
|
|
|
/// Creates a new shared secret from a pubkey and secret key.
|
2015-09-18 20:22:48 +00:00
|
|
|
#[inline]
|
2019-11-09 22:02:44 +00:00
|
|
|
pub fn new(point: &PublicKey, scalar: &SecretKey) -> SharedSecret {
|
2022-02-18 12:10:02 +00:00
|
|
|
let mut buf = [0u8; SHARED_SECRET_SIZE];
|
2019-11-09 22:02:44 +00:00
|
|
|
let res = unsafe {
|
|
|
|
ffi::secp256k1_ecdh(
|
|
|
|
ffi::secp256k1_context_no_precomp,
|
2022-02-10 10:35:15 +00:00
|
|
|
buf.as_mut_ptr(),
|
2019-11-09 22:02:44 +00:00
|
|
|
point.as_c_ptr(),
|
|
|
|
scalar.as_c_ptr(),
|
|
|
|
ffi::secp256k1_ecdh_hash_function_default,
|
|
|
|
ptr::null_mut(),
|
|
|
|
)
|
|
|
|
};
|
2020-03-01 10:42:42 +00:00
|
|
|
debug_assert_eq!(res, 1);
|
2022-02-10 10:35:15 +00:00
|
|
|
SharedSecret(buf)
|
|
|
|
}
|
2022-02-18 12:10:02 +00:00
|
|
|
|
|
|
|
/// Returns the shared secret as a byte value.
|
|
|
|
#[inline]
|
|
|
|
pub fn secret_bytes(&self) -> [u8; SHARED_SECRET_SIZE] {
|
|
|
|
self.0
|
|
|
|
}
|
2022-03-10 14:57:29 +00:00
|
|
|
|
2022-03-10 23:18:32 +00:00
|
|
|
/// Creates a shared secret from `bytes` array.
|
|
|
|
#[inline]
|
2022-03-10 14:57:29 +00:00
|
|
|
pub fn from_bytes(bytes: [u8; SHARED_SECRET_SIZE]) -> SharedSecret {
|
|
|
|
SharedSecret(bytes)
|
|
|
|
}
|
2022-03-10 23:18:32 +00:00
|
|
|
|
|
|
|
/// Creates a shared secret from `bytes` slice.
|
|
|
|
#[inline]
|
|
|
|
pub fn from_slice(bytes: &[u8]) -> Result<SharedSecret, Error> {
|
|
|
|
match bytes.len() {
|
|
|
|
SHARED_SECRET_SIZE => {
|
|
|
|
let mut ret = [0u8; SHARED_SECRET_SIZE];
|
|
|
|
ret[..].copy_from_slice(bytes);
|
|
|
|
Ok(SharedSecret(ret))
|
|
|
|
}
|
|
|
|
_ => Err(Error::InvalidSharedSecret)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl str::FromStr for SharedSecret {
|
|
|
|
type Err = Error;
|
|
|
|
fn from_str(s: &str) -> Result<SharedSecret, Error> {
|
|
|
|
let mut res = [0u8; SHARED_SECRET_SIZE];
|
2021-09-14 09:18:22 +00:00
|
|
|
match crate::from_hex(s, &mut res) {
|
2022-03-10 23:18:32 +00:00
|
|
|
Ok(SHARED_SECRET_SIZE) => Ok(SharedSecret::from_bytes(res)),
|
|
|
|
_ => Err(Error::InvalidSharedSecret)
|
|
|
|
}
|
|
|
|
}
|
2022-02-10 10:35:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Borrow<[u8]> for SharedSecret {
|
|
|
|
fn borrow(&self) -> &[u8] {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsRef<[u8]> for SharedSecret {
|
|
|
|
fn as_ref(&self) -> &[u8] {
|
|
|
|
&self.0
|
2015-09-18 20:22:48 +00:00
|
|
|
}
|
2022-02-18 09:37:26 +00:00
|
|
|
}
|
2019-11-09 22:03:44 +00:00
|
|
|
|
2022-02-18 09:37:26 +00:00
|
|
|
/// Creates a shared point from public key and secret key.
|
|
|
|
///
|
2022-02-10 10:35:15 +00:00
|
|
|
/// **Important: use of a strong cryptographic hash function may be critical to security! Do NOT use
|
|
|
|
/// unless you understand cryptographical implications.** If not, use SharedSecret instead.
|
|
|
|
///
|
2022-02-18 09:37:26 +00:00
|
|
|
/// Can be used like `SharedSecret` but caller is responsible for then hashing the returned buffer.
|
|
|
|
/// This allows for the use of a custom hash function since `SharedSecret` uses SHA256.
|
|
|
|
///
|
|
|
|
/// # Returns
|
|
|
|
///
|
|
|
|
/// 64 bytes representing the (x,y) co-ordinates of a point on the curve (32 bytes each).
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
/// ```
|
|
|
|
/// # #[cfg(all(feature = "bitcoin_hashes", feature = "rand-std", feature = "std"))] {
|
|
|
|
/// # use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey};
|
|
|
|
/// # use secp256k1::hashes::{Hash, sha512};
|
|
|
|
/// # use secp256k1::rand::thread_rng;
|
|
|
|
///
|
|
|
|
/// let s = Secp256k1::new();
|
|
|
|
/// let (sk1, pk1) = s.generate_keypair(&mut thread_rng());
|
|
|
|
/// let (sk2, pk2) = s.generate_keypair(&mut thread_rng());
|
|
|
|
///
|
|
|
|
/// let point1 = ecdh::shared_secret_point(&pk2, &sk1);
|
|
|
|
/// let secret1 = sha512::Hash::hash(&point1);
|
|
|
|
/// let point2 = ecdh::shared_secret_point(&pk1, &sk2);
|
|
|
|
/// let secret2 = sha512::Hash::hash(&point2);
|
|
|
|
/// assert_eq!(secret1, secret2)
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
pub fn shared_secret_point(point: &PublicKey, scalar: &SecretKey) -> [u8; 64] {
|
|
|
|
let mut xy = [0u8; 64];
|
|
|
|
|
|
|
|
let res = unsafe {
|
|
|
|
ffi::secp256k1_ecdh(
|
|
|
|
ffi::secp256k1_context_no_precomp,
|
|
|
|
xy.as_mut_ptr(),
|
|
|
|
point.as_ptr(),
|
|
|
|
scalar.as_ptr(),
|
|
|
|
Some(c_callback),
|
|
|
|
ptr::null_mut(),
|
|
|
|
)
|
|
|
|
};
|
|
|
|
// Our callback *always* returns 1.
|
|
|
|
// The scalar was verified to be valid (0 > scalar > group_order) via the type system.
|
|
|
|
debug_assert_eq!(res, 1);
|
|
|
|
xy
|
2015-09-18 20:22:48 +00:00
|
|
|
}
|
|
|
|
|
2022-02-10 10:35:15 +00:00
|
|
|
unsafe extern "C" fn c_callback(output: *mut c_uchar, x: *const c_uchar, y: *const c_uchar, _data: *mut c_void) -> c_int {
|
|
|
|
ptr::copy_nonoverlapping(x, output, 32);
|
|
|
|
ptr::copy_nonoverlapping(y, output.offset(32), 32);
|
|
|
|
1
|
|
|
|
}
|
|
|
|
|
2022-03-10 23:18:32 +00:00
|
|
|
#[cfg(feature = "serde")]
|
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
|
|
|
|
impl ::serde::Serialize for SharedSecret {
|
|
|
|
fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
|
|
|
if s.is_human_readable() {
|
|
|
|
let mut buf = [0u8; SHARED_SECRET_SIZE * 2];
|
2021-09-14 09:18:22 +00:00
|
|
|
s.serialize_str(crate::to_hex(&self.0, &mut buf).expect("fixed-size hex serialization"))
|
2022-03-10 23:18:32 +00:00
|
|
|
} else {
|
2022-06-10 02:29:16 +00:00
|
|
|
s.serialize_bytes(self.as_ref())
|
2022-03-10 23:18:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "serde")]
|
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
|
|
|
|
impl<'de> ::serde::Deserialize<'de> for SharedSecret {
|
|
|
|
fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
|
|
|
if d.is_human_readable() {
|
|
|
|
d.deserialize_str(super::serde_util::FromStrVisitor::new(
|
|
|
|
"a hex string representing 32 byte SharedSecret"
|
|
|
|
))
|
|
|
|
} else {
|
|
|
|
d.deserialize_bytes(super::serde_util::BytesVisitor::new(
|
|
|
|
"raw 32 bytes SharedSecret",
|
|
|
|
SharedSecret::from_slice
|
|
|
|
))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-09-18 20:22:48 +00:00
|
|
|
#[cfg(test)]
|
2022-02-01 02:43:42 +00:00
|
|
|
#[allow(unused_imports)]
|
2015-09-18 20:22:48 +00:00
|
|
|
mod tests {
|
|
|
|
use rand::thread_rng;
|
2020-12-21 23:27:55 +00:00
|
|
|
#[cfg(target_arch = "wasm32")]
|
|
|
|
use wasm_bindgen_test::wasm_bindgen_test as test;
|
|
|
|
|
2021-09-14 09:18:22 +00:00
|
|
|
use crate::Secp256k1;
|
|
|
|
use super::SharedSecret;
|
|
|
|
|
2015-09-18 20:22:48 +00:00
|
|
|
#[test]
|
2022-02-01 02:43:42 +00:00
|
|
|
#[cfg(all(feature="rand-std", any(feature = "alloc", feature = "std")))]
|
2015-09-18 20:22:48 +00:00
|
|
|
fn ecdh() {
|
2018-06-03 08:47:14 +00:00
|
|
|
let s = Secp256k1::signing_only();
|
2018-06-03 09:08:09 +00:00
|
|
|
let (sk1, pk1) = s.generate_keypair(&mut thread_rng());
|
|
|
|
let (sk2, pk2) = s.generate_keypair(&mut thread_rng());
|
2015-09-18 20:22:48 +00:00
|
|
|
|
2022-02-21 13:11:30 +00:00
|
|
|
let sec1 = SharedSecret::new(&pk2, &sk1);
|
|
|
|
let sec2 = SharedSecret::new(&pk1, &sk2);
|
2018-11-06 22:04:02 +00:00
|
|
|
let sec_odd = SharedSecret::new(&pk1, &sk1);
|
2015-09-18 20:22:48 +00:00
|
|
|
assert_eq!(sec1, sec2);
|
|
|
|
assert!(sec_odd != sec2);
|
|
|
|
}
|
2019-11-09 22:04:05 +00:00
|
|
|
|
2019-11-10 11:24:53 +00:00
|
|
|
#[test]
|
2020-03-01 10:42:42 +00:00
|
|
|
fn test_c_callback() {
|
|
|
|
let x = [5u8; 32];
|
|
|
|
let y = [7u8; 32];
|
|
|
|
let mut output = [0u8; 64];
|
2021-09-14 09:18:22 +00:00
|
|
|
let res = unsafe { super::c_callback(output.as_mut_ptr(), x.as_ptr(), y.as_ptr(), core::ptr::null_mut()) };
|
2020-03-01 10:42:42 +00:00
|
|
|
assert_eq!(res, 1);
|
|
|
|
let mut new_x = [0u8; 32];
|
|
|
|
let mut new_y = [0u8; 32];
|
|
|
|
new_x.copy_from_slice(&output[..32]);
|
|
|
|
new_y.copy_from_slice(&output[32..]);
|
|
|
|
assert_eq!(x, new_x);
|
|
|
|
assert_eq!(y, new_y);
|
2019-11-10 11:24:53 +00:00
|
|
|
}
|
2022-02-10 10:35:15 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[cfg(not(fuzzing))]
|
|
|
|
#[cfg(all(feature="rand-std", feature = "std", feature = "bitcoin_hashes"))]
|
|
|
|
fn bitcoin_hashes_and_sys_generate_same_secret() {
|
2021-09-14 09:18:22 +00:00
|
|
|
use bitcoin_hashes::{sha256, Hash, HashEngine};
|
|
|
|
use crate::ecdh::shared_secret_point;
|
2022-02-10 10:35:15 +00:00
|
|
|
|
|
|
|
let s = Secp256k1::signing_only();
|
|
|
|
let (sk1, _) = s.generate_keypair(&mut thread_rng());
|
|
|
|
let (_, pk2) = s.generate_keypair(&mut thread_rng());
|
|
|
|
|
|
|
|
let secret_sys = SharedSecret::new(&pk2, &sk1);
|
|
|
|
|
|
|
|
let xy = shared_secret_point(&pk2, &sk1);
|
|
|
|
|
|
|
|
// Mimics logic in `bitcoin-core/secp256k1/src/module/main_impl.h`
|
|
|
|
let version = (xy[63] & 0x01) | 0x02;
|
|
|
|
let mut engine = sha256::HashEngine::default();
|
|
|
|
engine.input(&[version]);
|
|
|
|
engine.input(&xy.as_ref()[..32]);
|
|
|
|
let secret_bh = sha256::Hash::from_engine(engine);
|
|
|
|
|
|
|
|
assert_eq!(secret_bh.as_inner(), secret_sys.as_ref());
|
|
|
|
}
|
2022-03-10 23:18:32 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[cfg(all(feature = "serde", any(feature = "alloc", feature = "std")))]
|
|
|
|
fn serde() {
|
|
|
|
use serde_test::{Configure, Token, assert_tokens};
|
|
|
|
static BYTES: [u8; 32] = [
|
|
|
|
1, 1, 1, 1, 1, 1, 1, 1,
|
|
|
|
0, 1, 2, 3, 4, 5, 6, 7,
|
|
|
|
0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0,
|
|
|
|
99, 99, 99, 99, 99, 99, 99, 99
|
|
|
|
];
|
2022-06-10 02:25:03 +00:00
|
|
|
static STR: &str = "01010101010101010001020304050607ffff0000ffff00006363636363636363";
|
2022-03-10 23:18:32 +00:00
|
|
|
|
|
|
|
let secret = SharedSecret::from_slice(&BYTES).unwrap();
|
|
|
|
|
|
|
|
assert_tokens(&secret.compact(), &[Token::BorrowedBytes(&BYTES[..])]);
|
|
|
|
assert_tokens(&secret.compact(), &[Token::Bytes(&BYTES)]);
|
|
|
|
assert_tokens(&secret.compact(), &[Token::ByteBuf(&BYTES)]);
|
|
|
|
|
|
|
|
assert_tokens(&secret.readable(), &[Token::BorrowedStr(STR)]);
|
|
|
|
assert_tokens(&secret.readable(), &[Token::Str(STR)]);
|
|
|
|
assert_tokens(&secret.readable(), &[Token::String(STR)]);
|
|
|
|
}
|
2015-09-18 20:22:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(all(test, feature = "unstable"))]
|
|
|
|
mod benches {
|
|
|
|
use test::{Bencher, black_box};
|
|
|
|
|
2021-09-14 09:18:22 +00:00
|
|
|
use rand::thread_rng;
|
|
|
|
|
|
|
|
use crate::Secp256k1;
|
|
|
|
|
2015-09-20 20:18:53 +00:00
|
|
|
use super::SharedSecret;
|
2015-09-18 20:22:48 +00:00
|
|
|
|
|
|
|
#[bench]
|
|
|
|
pub fn bench_ecdh(bh: &mut Bencher) {
|
2018-06-03 08:47:14 +00:00
|
|
|
let s = Secp256k1::signing_only();
|
2018-06-03 09:08:09 +00:00
|
|
|
let (sk, pk) = s.generate_keypair(&mut thread_rng());
|
2015-09-18 20:22:48 +00:00
|
|
|
|
|
|
|
bh.iter( || {
|
2018-11-06 22:04:02 +00:00
|
|
|
let res = SharedSecret::new(&pk, &sk);
|
2015-09-18 20:22:48 +00:00
|
|
|
black_box(res);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|