1
//! Key manipulation functions for use with public keys.
2
//!
3
//! Tor does some interesting and not-standard things with its
4
//! curve25519 and ed25519 keys, for several reasons.
5
//!
6
//! In order to prove ownership of a curve25519 private key, Tor
7
//! converts it into an ed25519 key, and then uses that ed25519 key to
8
//! sign its identity key.  We implement this conversion with
9
//! [`convert_curve25519_to_ed25519_public`] and
10
//! [`convert_curve25519_to_ed25519_private`].
11
//!
12
//! In Tor's v3 onion service design, Tor uses a _key blinding_
13
//! algorithm to derive a publicly known Ed25519 key from a different
14
//! Ed25519 key used as the .onion address.  This algorithm allows
15
//! directories to validate the signatures on onion service
16
//! descriptors, without knowing which services they represent.  We
17
//! implement this blinding operation via [`blind_pubkey`].
18
//!
19
//! ## TODO
20
//!
21
//! Recommend more standardized ways to do these things.
22

            
23
// Ideally there would be a feature that we would use in the CI, rather than this ad-hoc list.
24
#![cfg_attr(
25
    not(all(test, feature = "hsv3-service", feature = "relay")),
26
    allow(unused_imports)
27
)]
28

            
29
use crate::{d, pk};
30
use digest::Digest;
31
use thiserror::Error;
32

            
33
use curve25519_dalek::scalar::Scalar;
34
use ed25519_dalek::hazmat::ExpandedSecretKey;
35
use pk::ed25519::{ExpandedKeypair, PublicKey};
36

            
37
/// Convert a curve25519 public key (with sign bit) to an ed25519
38
/// public key, for use in ntor key cross-certification.
39
///
40
/// Note that this formula is not standardized; don't use
41
/// it for anything besides cross-certification.
42
25316
pub fn convert_curve25519_to_ed25519_public(
43
25316
    pubkey: &pk::curve25519::PublicKey,
44
25316
    signbit: u8,
45
25316
) -> Option<pk::ed25519::PublicKey> {
46
    use curve25519_dalek::montgomery::MontgomeryPoint;
47

            
48
25316
    let point = MontgomeryPoint(*pubkey.as_bytes());
49
25316
    let edpoint = point.to_edwards(signbit)?;
50

            
51
    // TODO: This is inefficient; we shouldn't have to re-compress
52
    // this point to get the public key we wanted.  But there's no way
53
    // with the current API that I can to construct an ed25519 public
54
    // key from a compressed point.
55
25316
    let compressed_y = edpoint.compress();
56
25316
    pk::ed25519::PublicKey::from_bytes(compressed_y.as_bytes()).ok()
57
25316
}
58

            
59
/// Convert a curve25519 private key to an ed25519 private key (and
60
/// give a sign bit) to use with it, for use in ntor key cross-certification.
61
///
62
/// Note that this formula is not standardized; don't use
63
/// it for anything besides cross-certification.
64
///
65
/// *NEVER* use these keys to sign inputs that may be generated by an
66
/// attacker.
67
///
68
/// # Panics
69
///
70
/// If the `debug_assertions` feature is enabled, this function will
71
/// double-check that the key it is about to return is the right
72
/// private key for the public key returned by
73
/// `convert_curve25519_to_ed25519_public`.
74
///
75
/// This panic should be impossible unless there are implementation
76
/// bugs.
77
#[cfg(any(test, feature = "cvt-x25519"))]
78
300
pub fn convert_curve25519_to_ed25519_private(
79
300
    privkey: &pk::curve25519::StaticSecret,
80
300
) -> Option<(pk::ed25519::ExpandedKeypair, u8)> {
81
    use crate::{d::Sha512, pk::ed25519::PublicKey};
82
    use zeroize::Zeroizing;
83

            
84
300
    let h = Sha512::new()
85
300
        .chain_update(privkey.to_bytes())
86
300
        .chain_update(&b"Derive high part of ed25519 key from curve25519 key\0"[..])
87
300
        .finalize();
88
300

            
89
300
    let mut bytes = Zeroizing::new([0_u8; 64]);
90
300
    bytes[0..32].clone_from_slice(&privkey.to_bytes());
91
300
    bytes[32..64].clone_from_slice(&h[0..32]);
92
300

            
93
300
    let secret = ed25519_dalek::hazmat::ExpandedSecretKey::from_bytes(&bytes);
94
300
    let public: pk::ed25519::PublicKey = PublicKey((&secret).into());
95
300
    let signbit = public.as_bytes()[31] >> 7;
96
300

            
97
300
    #[cfg(debug_assertions)]
98
300
    {
99
300
        let curve_pubkey1 = pk::curve25519::PublicKey::from(privkey);
100
300
        let ed_pubkey1 = convert_curve25519_to_ed25519_public(&curve_pubkey1, signbit)?;
101
300
        assert_eq!(ed_pubkey1, public);
102
    }
103

            
104
300
    Some((pk::ed25519::ExpandedKeypair { public, secret }, signbit))
105
300
}
106

            
107
/// Convert an ed25519 private key to a curve25519 private key.
108
///
109
/// This creates a curve25519 key as described in section-5.1.5 of RFC8032: the bytes of the secret
110
/// part of `keypair` are hashed using SHA-512, and the result is clamped (the first 3 bits of the
111
/// first byte are cleared, the highest bit of the last byte is cleared, the second highest bit of
112
/// the last byte is set).
113
///
114
/// Note: Using the same keypair for multiple purposes (such as key-exchange and signing) is
115
/// considered bad practice. Don't use this function unless you know what you're doing.
116
/// See [On using the same key pair for Ed25519 and an X25519 based
117
/// KEM](https://eprint.iacr.org/2021/509.pdf).
118
///
119
/// This function is needed by the `ArtiNativeKeystore` from `tor-keymgr` to convert ed25519
120
/// private keys to x25519. This is because `ArtiNativeKeystore` stores x25519 private keys as
121
/// ssh-ed25519 OpenSSH keys. Other similar use cases are also valid.
122
///
123
/// It's important to note that converting a private key from ed25519 -> curve25519 -> ed25519 will
124
/// yield an [`ExpandedKeypair`] that is _not_ identical to the
125
/// expanded version of the original [`Keypair`](ed25519_dalek::SigningKey): the lower halves (the keys) of
126
/// the expanded key pairs will be the same, but their upper halves (the nonces) will be different.
127
///
128
/// # Panics
129
///
130
/// If the `debug_assertions` feature is enabled, this function will double-check that the key it
131
/// is about to return is clamped.
132
///
133
/// This panic should be impossible unless we have upgraded x25519-dalek without auditing this
134
/// function.
135
#[cfg(any(test, feature = "cvt-x25519"))]
136
#[deprecated(
137
    since = "0.6.0",
138
    note = "ed25519_to_curve25519 conversion is unused, and no longer supported."
139
)]
140
2
pub fn convert_ed25519_to_curve25519_private(
141
2
    keypair: &pk::ed25519::Keypair,
142
2
) -> pk::curve25519::StaticSecret {
143
    use crate::d::Sha512;
144
    use zeroize::{Zeroize as _, Zeroizing};
145

            
146
    // Generate the key according to section-5.1.5 of rfc8032
147
2
    let h = Sha512::digest(keypair.to_bytes());
148
2

            
149
2
    let mut bytes = Zeroizing::new([0_u8; 32]);
150
2
    bytes.clone_from_slice(&h[0..32]);
151
2

            
152
2
    // Clamp the bytes.  We do not necessarily have to do this, since
153
2
    // x25519-dalek will handle clamping before it does any computation,  but we
154
2
    // want to make sure that the StaticSecret we generate is in the usual
155
2
    // format.
156
2
    let mut bytes = curve25519_dalek::scalar::clamp_integer(*bytes);
157
2

            
158
2
    let secret = pk::curve25519::StaticSecret::from(bytes);
159
2
    bytes.zeroize();
160
2

            
161
2
    secret
162
2
}
163

            
164
/// An error occurred during a key-blinding operation.
165
#[derive(Error, Debug, PartialEq, Eq)]
166
#[non_exhaustive]
167
pub enum BlindingError {
168
    /// A bad public key was provided for blinding
169
    #[error("Public key was invalid")]
170
    BadPubkey,
171
    /// Dalek failed the scalar multiplication
172
    #[error("Key blinding failed")]
173
    BlindingFailed,
174
}
175

            
176
// Convert this dalek error to a BlindingError
177
impl From<ed25519_dalek::SignatureError> for BlindingError {
178
    fn from(_: ed25519_dalek::SignatureError) -> BlindingError {
179
        BlindingError::BlindingFailed
180
    }
181
}
182

            
183
/// Helper: clamp a blinding factor and use it to compute a blinding factor.
184
///
185
/// Described in part of rend-spec-v3 A.2.
186
///
187
/// This is a common step for public-key and private-key blinding.
188
#[cfg(any(feature = "hsv3-client", feature = "hsv3-service"))]
189
2280
fn clamp_blinding_factor(h: [u8; 32]) -> Scalar {
190
2280
    // Transform it into a scalar so that we can do scalar mult.
191
2280
    Scalar::from_bytes_mod_order(curve25519_dalek::scalar::clamp_integer(h))
192
2280
}
193

            
194
/// Blind the ed25519 public key `pk` using the blinding factor
195
/// `h`, and return the blinded public key.
196
///
197
/// This algorithm is described in `rend-spec-v3.txt`, section A.2.
198
/// In the terminology of that section, the value `pk` corresponds to
199
/// `A`, and
200
/// `h` is the value `h = H(...)`, before clamping.
201
///
202
/// Note that the approach used to clamp `h` to a scalar means
203
/// that different possible values for `h` may yield the same
204
/// output for a given `pk`.  This and other limitations make this
205
/// function unsuitable for use outside the context of
206
/// `rend-spec-v3.txt` without careful analysis.
207
///
208
/// # Errors
209
///
210
/// This function can fail if the input is not actually a valid
211
/// Ed25519 public key.
212
#[cfg(any(feature = "hsv3-client", feature = "hsv3-service"))]
213
#[cfg_attr(docsrs, doc(cfg(feature = "hsv3-client")))]
214
1668
#[cfg_attr(feature = "hsv3-client", visibility::make(pub))]
215
1668
fn blind_pubkey(pk: &PublicKey, h: [u8; 32]) -> Result<PublicKey, BlindingError> {
216
    use curve25519_dalek::edwards::CompressedEdwardsY;
217

            
218
1668
    let blinding_factor = clamp_blinding_factor(h);
219

            
220
    // Convert the public key to a point on the curve
221
1668
    let pubkey_point = CompressedEdwardsY(pk.to_bytes())
222
1668
        .decompress()
223
1668
        .ok_or(BlindingError::BadPubkey)?;
224

            
225
    // Do the scalar multiplication and get a point back
226
1668
    let blinded_pubkey_point = (blinding_factor * pubkey_point).compress();
227
1668
    // Turn the point back into bytes and return it
228
1668
    Ok(PublicKey::from_bytes(&blinded_pubkey_point.0)?)
229
1668
}
230

            
231
/// Blind the ed25519 secret key `sk` using the blinding factor `h`, and
232
/// return the blinded secret key.
233
///
234
/// This algorithm is described in `rend-spec-v3.txt`, section A.2.
235
/// `h` is the value `h = H(...)`, before clamping.
236
///
237
/// Note that the approach used to clamp `h` to a scalar means that
238
/// different possible values for `h` may yield the same output for a given
239
/// `pk`.  This and other limitations make this function unsuitable for use
240
/// outside the context of `rend-spec-v3.txt` without careful analysis.
241
///
242
/// # Errors
243
///
244
/// This function can fail if the input is not actually a valid Ed25519 secret
245
/// key.
246
#[cfg(feature = "hsv3-service")]
247
#[cfg_attr(docsrs, doc(cfg(feature = "hsv3-service")))]
248
612
pub fn blind_keypair(
249
612
    keypair: &ExpandedKeypair,
250
612
    h: [u8; 32],
251
612
) -> Result<ExpandedKeypair, BlindingError> {
252
    use zeroize::Zeroizing;
253

            
254
    /// Fixed string specified in rend-spec-v3.txt, used for blinding the
255
    /// original nonce.  (Technically, any string would do, but this one keeps
256
    /// implementations consistent.)
257
    const RH_BLIND_STRING: &[u8] = b"Derive temporary signing key hash input";
258

            
259
612
    let blinding_factor = clamp_blinding_factor(h);
260
612

            
261
612
    let blinded_secret_scalar = keypair.secret.scalar * blinding_factor;
262
612

            
263
612
    let blinded_secret_hash_prefix = {
264
612
        let mut h = d::Sha512::new();
265
612
        h.update(RH_BLIND_STRING);
266
612
        h.update(keypair.secret.hash_prefix);
267
612
        let mut d = Zeroizing::new([0_u8; 64]);
268
612
        h.finalize_into(d.as_mut().into());
269
612
        d[0..32].try_into().expect("slice cast failed")
270
612
    };
271
612

            
272
612
    let secret = ExpandedSecretKey {
273
612
        scalar: blinded_secret_scalar,
274
612
        hash_prefix: blinded_secret_hash_prefix,
275
612
    };
276
612
    let public = PublicKey(ed25519_dalek::VerifyingKey::from(&secret));
277

            
278
    {
279
        // Make sure that the public key that derives from our
280
        // blinded key is the same as the key that we get when we re-blind the
281
        // public key.
282
612
        let public2 = blind_pubkey(keypair.public(), h)?;
283
612
        assert_eq!(public, public2);
284
    }
285

            
286
612
    Ok(ExpandedKeypair { secret, public })
287
612
}
288

            
289
#[cfg(test)]
290
mod tests {
291
    // @@ begin test lint list maintained by maint/add_warning @@
292
    #![allow(clippy::bool_assert_comparison)]
293
    #![allow(clippy::clone_on_copy)]
294
    #![allow(clippy::dbg_macro)]
295
    #![allow(clippy::mixed_attributes_style)]
296
    #![allow(clippy::print_stderr)]
297
    #![allow(clippy::print_stdout)]
298
    #![allow(clippy::single_char_pattern)]
299
    #![allow(clippy::unwrap_used)]
300
    #![allow(clippy::unchecked_duration_subtraction)]
301
    #![allow(clippy::useless_vec)]
302
    #![allow(clippy::needless_pass_by_value)]
303
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
304
    use super::*;
305
    use crate::pk::ed25519::Keypair;
306

            
307
    #[test]
308
    fn curve_to_ed_compatible() {
309
        use crate::pk::{curve25519, ed25519};
310
        use tor_basic_utils::test_rng::testing_rng;
311

            
312
        let rng = testing_rng();
313

            
314
        let curve_sk = curve25519::StaticSecret::random_from_rng(rng);
315
        let curve_pk = curve25519::PublicKey::from(&curve_sk);
316

            
317
        let (ed_kp, signbit) = convert_curve25519_to_ed25519_private(&curve_sk).unwrap();
318
        let ed_sk = &ed_kp.secret;
319
        let ed_pk0 = ed_kp.public;
320
        let ed_pk1: ed25519::PublicKey = ed25519::PublicKey((ed_sk).into());
321
        let ed_pk2 = convert_curve25519_to_ed25519_public(&curve_pk, signbit).unwrap();
322

            
323
        let msg = b"tis the gift to be simple";
324
        let sig1 = ed_kp.sign(&msg[..]);
325
        assert!(ed_pk1.verify(&msg[..], &sig1).is_ok());
326
        assert!(ed_pk2.verify(&msg[..], &sig1).is_ok());
327

            
328
        assert_eq!(ed_pk1, ed_pk0);
329
        assert_eq!(ed_pk1, ed_pk2);
330
    }
331

            
332
    #[test]
333
    fn ed_to_curve_compatible() {
334
        use crate::pk::{curve25519, ed25519};
335
        use tor_basic_utils::test_rng::testing_rng;
336

            
337
        let mut rng = testing_rng();
338
        let ed_kp = ed25519::Keypair::generate(&mut rng);
339
        let ed_ekp1 = ExpandedKeypair::from(&ed_kp);
340

            
341
        #[allow(deprecated)]
342
        let curve_sk = convert_ed25519_to_curve25519_private(&ed_kp);
343
        let curve_pk = curve25519::PublicKey::from(&curve_sk);
344

            
345
        let (ed_ekp2, signbit) = convert_curve25519_to_ed25519_private(&curve_sk).unwrap();
346
        let ed_pk2 = convert_curve25519_to_ed25519_public(&curve_pk, signbit).unwrap();
347

            
348
        assert_eq!(ed_ekp1.public, ed_ekp2.public);
349
        assert_eq!(ed_ekp2.public, ed_pk2);
350
        assert_eq!(ed_ekp1.secret.scalar, ed_ekp2.secret.scalar);
351

            
352
        // Make sure the 2 secret keys are the same. Note: we only look at the
353
        // scalar part of the (expanded) key, not the hash prefix.
354
        assert_eq!(ed_ekp1.secret.scalar, ed_ekp2.secret.scalar);
355

            
356
        let msg = b"tis the gift to be simple";
357

            
358
        for kp in &[&ed_ekp1, &ed_ekp2] {
359
            let sig = kp.sign(&msg[..]);
360
            assert!(ed_ekp1.public.verify(&msg[..], &sig).is_ok());
361
            assert!(ed_ekp2.public.verify(&msg[..], &sig).is_ok());
362
        }
363
    }
364

            
365
    #[test]
366
    #[cfg(all(feature = "hsv3-client", feature = "hsv3-service"))]
367
    fn blinding() {
368
        // Test the ed25519 blinding function.
369
        //
370
        // These test vectors are from our ed25519 implementation and related
371
        // functions. These were automatically generated by the
372
        // ed25519_exts_ref.py script in little-t-tor and they are also used by
373
        // little-t-tor and onionbalance:
374

            
375
        let seckeys = vec![
376
            b"26c76712d89d906e6672dafa614c42e5cb1caac8c6568e4d2493087db51f0d36",
377
            b"fba7a5366b5cb98c2667a18783f5cf8f4f8d1a2ce939ad22a6e685edde85128d",
378
            b"67e3aa7a14fac8445d15e45e38a523481a69ae35513c9e4143eb1c2196729a0e",
379
            b"d51385942033a76dc17f089a59e6a5a7fe80d9c526ae8ddd8c3a506b99d3d0a6",
380
            b"5c8eac469bb3f1b85bc7cd893f52dc42a9ab66f1b02b5ce6a68e9b175d3bb433",
381
            b"eda433d483059b6d1ff8b7cfbd0fe406bfb23722c8f3c8252629284573b61b86",
382
            b"4377c40431c30883c5fbd9bc92ae48d1ed8a47b81d13806beac5351739b5533d",
383
            b"c6bbcce615839756aed2cc78b1de13884dd3618f48367a17597a16c1cd7a290b",
384
            b"c6bbcce615839756aed2cc78b1de13884dd3618f48367a17597a16c1cd7a290b",
385
            b"c6bbcce615839756aed2cc78b1de13884dd3618f48367a17597a16c1cd7a290b",
386
        ];
387
        let expanded_seckeys = vec![
388
            b"c0a4de23cc64392d85aa1da82b3defddbea946d13bb053bf8489fa9296281f495022f1f7ec0dcf52f07d4c7965c4eaed121d5d88d0a8ff546b06116a20e97755",
389
            b"18a8a69a06790dac778e882f7e868baacfa12521a5c058f5194f3a729184514a2a656fe7799c3e41f43d756da8d9cd47a061316cfe6147e23ea2f90d1ca45f30",
390
            b"58d84f8862d2ecfa30eb491a81c36d05b574310ea69dae18ecb57e992a896656b982187ee96c15bf4caeeab2d0b0ae4cd0b8d17470fc7efa98bb26428f4ef36d",
391
            b"50702d20b3550c6e16033db5ad4fba16436f1ecc7485be6af62b0732ceb5d173c47ccd9d044b6ea99dd99256adcc9c62191be194e7cb1a5b58ddcec85d876a2b",
392
            b"7077464c864c2ed5ed21c9916dc3b3ba6256f8b742fec67658d8d233dadc8d5a7a82c371083cc86892c2c8782dda2a09b6baf016aec51b689183ae59ce932ff2",
393
            b"8883c1387a6c86fc0bd7b9f157b4e4cd83f6885bf55e2706d2235d4527a2f05311a3595953282e436df0349e1bb313a19b3ddbf7a7b91ecce8a2c34abadb38b3",
394
            b"186791ac8d03a3ac8efed6ac360467edd5a3bed2d02b3be713ddd5be53b3287ee37436e5fd7ac43794394507ad440ecfdf59c4c255f19b768a273109e06d7d8e",
395
            b"b003077c1e52a62308eef7950b2d532e1d4a7eea50ad22d8ac11b892851f1c40ffb9c9ff8dcd0c6c233f665a2e176324d92416bfcfcd1f787424c0c667452d86",
396
            b"b003077c1e52a62308eef7950b2d532e1d4a7eea50ad22d8ac11b892851f1c40ffb9c9ff8dcd0c6c233f665a2e176324d92416bfcfcd1f787424c0c667452d86",
397
            b"b003077c1e52a62308eef7950b2d532e1d4a7eea50ad22d8ac11b892851f1c40ffb9c9ff8dcd0c6c233f665a2e176324d92416bfcfcd1f787424c0c667452d86",
398
        ];
399

            
400
        let pubkeys = vec![
401
            b"c2247870536a192d142d056abefca68d6193158e7c1a59c1654c954eccaff894",
402
            b"1519a3b15816a1aafab0b213892026ebf5c0dc232c58b21088d88cb90e9b940d",
403
            b"081faa81992e360ea22c06af1aba096e7a73f1c665bc8b3e4e531c46455fd1dd",
404
            b"73cfa1189a723aad7966137cbffa35140bb40d7e16eae4c40b79b5f0360dd65a",
405
            b"66c1a77104d86461b6f98f73acf3cd229c80624495d2d74d6fda1e940080a96b",
406
            b"d21c294db0e64cb2d8976625786ede1d9754186ae8197a64d72f68c792eecc19",
407
            b"c4d58b4cf85a348ff3d410dd936fa460c4f18da962c01b1963792b9dcc8a6ea6",
408
            b"95126f14d86494020665face03f2d42ee2b312a85bc729903eb17522954a1c4a",
409
            b"95126f14d86494020665face03f2d42ee2b312a85bc729903eb17522954a1c4a",
410
            b"95126f14d86494020665face03f2d42ee2b312a85bc729903eb17522954a1c4a",
411
        ];
412
        let params = vec![
413
            "54a513898b471d1d448a2f3c55c1de2c0ef718c447b04497eeb999ed32027823",
414
            "831e9b5325b5d31b7ae6197e9c7a7baf2ec361e08248bce055908971047a2347",
415
            "ac78a1d46faf3bfbbdc5af5f053dc6dc9023ed78236bec1760dadfd0b2603760",
416
            "f9c84dc0ac31571507993df94da1b3d28684a12ad14e67d0a068aba5c53019fc",
417
            "b1fe79d1dec9bc108df69f6612c72812755751f21ecc5af99663b30be8b9081f",
418
            "81f1512b63ab5fb5c1711a4ec83d379c420574aedffa8c3368e1c3989a3a0084",
419
            "97f45142597c473a4b0e9a12d64561133ad9e1155fe5a9807fe6af8a93557818",
420
            "3f44f6a5a92cde816635dfc12ade70539871078d2ff097278be2a555c9859cd0",
421
            "0000000000000000000000000000000000000000000000000000000000000000",
422
            "1111111111111111111111111111111111111111111111111111111111111111",
423
        ];
424
        let blinded_pubkeys = vec![
425
            "1fc1fa4465bd9d4956fdbdc9d3acb3c7019bb8d5606b951c2e1dfe0b42eaeb41",
426
            "1cbbd4a88ce8f165447f159d9f628ada18674158c4f7c5ead44ce8eb0fa6eb7e",
427
            "c5419ad133ffde7e0ac882055d942f582054132b092de377d587435722deb028",
428
            "3e08d0dc291066272e313014bfac4d39ad84aa93c038478a58011f431648105f",
429
            "59381f06acb6bf1389ba305f70874eed3e0f2ab57cdb7bc69ed59a9b8899ff4d",
430
            "2b946a484344eb1c17c89dd8b04196a84f3b7222c876a07a4cece85f676f87d9",
431
            "c6b585129b135f8769df2eba987e76e089e80ba3a2a6729134d3b28008ac098e",
432
            "0eefdc795b59cabbc194c6174e34ba9451e8355108520554ec285acabebb34ac",
433
            "312404d06a0a9de489904b18d5233e83a50b225977fa8734f2c897a73c067952",
434
            "952a908a4a9e0e5176a2549f8f328955aca6817a9fdc59e3acec5dec50838108",
435
        ];
436
        let blinded_seckeys = vec![
437
            "293c3acff4e902f6f63ddc5d5caa2a57e771db4f24de65d4c28df3232f47fa01171d43f24e3f53e70ec7ac280044ac77d4942dee5d6807118a59bdf3ee647e89",
438
            "38b88f9f9440358da544504ee152fb475528f7c51c285bd1c68b14ade8e29a07b8ceff20dfcf53eb52b891fc078c934efbf0353af7242e7dc51bb32a093afa29",
439
            "4d03ce16a3f3249846aac9de0a0075061495c3b027248eeee47da4ddbaf9e0049217f52e92797462bd890fc274672e05c98f2c82970d640084781334aae0f940",
440
            "51d7db01aaa0d937a9fd7c8c7381445a14d8fa61f43347af5460d7cd8fda9904509ecee77082ce088f7c19d5a00e955eeef8df6fa41686abc1030c2d76807733",
441
            "1f76cab834e222bd2546efa7e073425680ab88df186ff41327d3e40770129b00b57b95a440570659a440a3e4771465022a8e67af86bdf2d0990c54e7bb87ff9a",
442
            "c23588c23ee76093419d07b27c6df5922a03ac58f96c53671456a7d1bdbf560ec492fc87d5ec2a1b185ca5a40541fdef0b1e128fd5c2380c888bfa924711bcab",
443
            "3ed249c6932d076e1a2f6916975914b14e8c739da00992358b8f37d3e790650691b4768f8e556d78f4bdcb9a13b6f6066fe81d3134ae965dc48cd0785b3af2b8",
444
            "288cbfd923cb286d48c084555b5bdd06c05e92fb81acdb45271367f57515380e053d9c00c81e1331c06ab50087be8cfc7dc11691b132614474f1aa9c2503cccd",
445
            "e5cd03eb4cc456e11bc36724b558873df0045729b22d8b748360067a7770ac02053d9c00c81e1331c06ab50087be8cfc7dc11691b132614474f1aa9c2503cccd",
446
            "2cf7ed8b163f5af960d2fc62e1883aa422a6090736b4f18a5456ddcaf78ede0c053d9c00c81e1331c06ab50087be8cfc7dc11691b132614474f1aa9c2503cccd",
447
        ];
448

            
449
        for i in 0..pubkeys.len() {
450
            let sk: [u8; 32] = hex::decode(seckeys[i]).unwrap().try_into().unwrap();
451
            let esk: ExpandedSecretKey = ExpandedSecretKey::from(&sk);
452
            let kp = Keypair((&sk).into());
453

            
454
            let esk_bytes_from_c_tor = hex::decode(expanded_seckeys[i]).unwrap();
455
            // Because of the differences in how we calculate the scalar, we
456
            // don't get the same _representation_ of the scalar as we did with
457
            // the C tor implementation.
458
            //
459
            // Therefore we have to do through this silliness to check our result.
460
            let c_scalar =
461
                Scalar::from_bytes_mod_order(esk_bytes_from_c_tor[0..32].try_into().unwrap());
462
            assert_eq!(c_scalar, esk.scalar);
463
            assert_eq!(
464
                hex::encode(esk.hash_prefix),
465
                hex::encode(&esk_bytes_from_c_tor[32..])
466
            );
467

            
468
            let public = PublicKey((&esk).into());
469
            let kp_in = ExpandedKeypair {
470
                secret: esk,
471
                public,
472
            };
473

            
474
            let pk =
475
                PublicKey::from_bytes(&hex::decode(pubkeys[i]).unwrap()[..].try_into().unwrap())
476
                    .unwrap();
477
            assert_eq!(pk, PublicKey((&kp.0).into()));
478

            
479
            let param = hex::decode(params[i]).unwrap().try_into().unwrap();
480
            // Blind the secret key, and make sure that the result is expected.
481
            let blinded_kp = blind_keypair(&kp_in, param).unwrap();
482
            assert_eq!(
483
                hex::encode(blinded_kp.to_secret_key_bytes()),
484
                blinded_seckeys[i]
485
            );
486

            
487
            // Make sure that the secret key can be encoded and decoded.
488
            {
489
                let blinded_kp2 =
490
                    ExpandedKeypair::from_secret_key_bytes(blinded_kp.to_secret_key_bytes())
491
                        .unwrap();
492
                assert_eq!(blinded_kp2.public, blinded_kp.public);
493
                assert_eq!(blinded_kp2.secret.scalar, blinded_kp.secret.scalar);
494
                assert_eq!(
495
                    blinded_kp2.secret.hash_prefix,
496
                    blinded_kp.secret.hash_prefix
497
                );
498
            }
499

            
500
            let blinded_pk = blind_pubkey(&pk, param).unwrap();
501

            
502
            // Make sure blinded pk is as expected.
503
            assert_eq!(hex::encode(blinded_pk.to_bytes()), blinded_pubkeys[i]);
504

            
505
            // Make sure that signature made with blinded sk is validated by
506
            // blinded pk.
507
            let sig = blinded_kp.sign(b"hello world");
508
            blinded_pk.verify(b"hello world", &sig).unwrap();
509

            
510
            let blinded_sk_scalar = blinded_kp.secret.scalar;
511
            let pk2 = blinded_sk_scalar * curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
512
            let pk2 = pk2.compress();
513
            assert_eq!(pk2.as_bytes(), blinded_pk.as_bytes());
514
        }
515
    }
516
}