1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use core::{borrow::Borrow, ptr, str};
use secp256k1_sys::types::{c_int, c_uchar, c_void};
use crate::{constants, Error, ffi::{self, CPtr}, key::{PublicKey, SecretKey}};
const SHARED_SECRET_SIZE: usize = constants::SECRET_KEY_SIZE;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SharedSecret([u8; SHARED_SECRET_SIZE]);
impl_display_secret!(SharedSecret);
impl SharedSecret {
#[inline]
pub fn new(point: &PublicKey, scalar: &SecretKey) -> SharedSecret {
let mut buf = [0u8; SHARED_SECRET_SIZE];
let res = unsafe {
ffi::secp256k1_ecdh(
ffi::secp256k1_context_no_precomp,
buf.as_mut_ptr(),
point.as_c_ptr(),
scalar.as_c_ptr(),
ffi::secp256k1_ecdh_hash_function_default,
ptr::null_mut(),
)
};
debug_assert_eq!(res, 1);
SharedSecret(buf)
}
#[inline]
pub fn secret_bytes(&self) -> [u8; SHARED_SECRET_SIZE] {
self.0
}
#[inline]
pub fn from_bytes(bytes: [u8; SHARED_SECRET_SIZE]) -> SharedSecret {
SharedSecret(bytes)
}
#[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];
match crate::from_hex(s, &mut res) {
Ok(SHARED_SECRET_SIZE) => Ok(SharedSecret::from_bytes(res)),
_ => Err(Error::InvalidSharedSecret)
}
}
}
impl Borrow<[u8]> for SharedSecret {
fn borrow(&self) -> &[u8] {
&self.0
}
}
impl AsRef<[u8]> for SharedSecret {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
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(),
)
};
debug_assert_eq!(res, 1);
xy
}
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
}
#[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];
s.serialize_str(crate::to_hex(&self.0, &mut buf).expect("fixed-size hex serialization"))
} else {
s.serialize_bytes(self.as_ref())
}
}
}
#[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
))
}
}
}
#[cfg(test)]
#[allow(unused_imports)]
mod tests {
use rand::thread_rng;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test as test;
use crate::Secp256k1;
use super::SharedSecret;
#[test]
#[cfg(all(feature="rand-std", any(feature = "alloc", feature = "std")))]
fn ecdh() {
let s = Secp256k1::signing_only();
let (sk1, pk1) = s.generate_keypair(&mut thread_rng());
let (sk2, pk2) = s.generate_keypair(&mut thread_rng());
let sec1 = SharedSecret::new(&pk2, &sk1);
let sec2 = SharedSecret::new(&pk1, &sk2);
let sec_odd = SharedSecret::new(&pk1, &sk1);
assert_eq!(sec1, sec2);
assert!(sec_odd != sec2);
}
#[test]
fn test_c_callback() {
let x = [5u8; 32];
let y = [7u8; 32];
let mut output = [0u8; 64];
let res = unsafe { super::c_callback(output.as_mut_ptr(), x.as_ptr(), y.as_ptr(), core::ptr::null_mut()) };
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);
}
#[test]
#[cfg(not(fuzzing))]
#[cfg(all(feature="rand-std", feature = "std", feature = "bitcoin_hashes"))]
fn bitcoin_hashes_and_sys_generate_same_secret() {
use bitcoin_hashes::{sha256, Hash, HashEngine};
use crate::ecdh::shared_secret_point;
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);
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());
}
#[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
];
static STR: &str = "01010101010101010001020304050607ffff0000ffff00006363636363636363";
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)]);
}
}
#[cfg(bench)]
mod benches {
use test::{Bencher, black_box};
use rand::thread_rng;
use crate::Secp256k1;
use super::SharedSecret;
#[bench]
pub fn bench_ecdh(bh: &mut Bencher) {
let s = Secp256k1::signing_only();
let (sk, pk) = s.generate_keypair(&mut thread_rng());
bh.iter( || {
let res = SharedSecret::new(&pk, &sk);
black_box(res);
});
}
}