]> git.proxmox.com Git - rustc.git/blob - vendor/ed25519-compact/src/ed25519.rs
New upstream version 1.70.0+dfsg2
[rustc.git] / vendor / ed25519-compact / src / ed25519.rs
1 use core::fmt;
2 use core::ops::{Deref, DerefMut};
3
4 use super::common::*;
5 #[cfg(feature = "blind-keys")]
6 use super::edwards25519::{ge_scalarmult, sc_invert, sc_mul};
7 use super::edwards25519::{
8 ge_scalarmult_base, is_identity, sc_muladd, sc_reduce, sc_reduce32, sc_reject_noncanonical,
9 GeP2, GeP3,
10 };
11 use super::error::Error;
12 use super::sha512;
13
14 /// A public key.
15 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
16 pub struct PublicKey([u8; PublicKey::BYTES]);
17
18 impl PublicKey {
19 /// Number of raw bytes in a public key.
20 pub const BYTES: usize = 32;
21
22 /// Creates a public key from raw bytes.
23 pub fn new(pk: [u8; PublicKey::BYTES]) -> Self {
24 PublicKey(pk)
25 }
26
27 /// Creates a public key from a slice.
28 pub fn from_slice(pk: &[u8]) -> Result<Self, Error> {
29 let mut pk_ = [0u8; PublicKey::BYTES];
30 if pk.len() != pk_.len() {
31 return Err(Error::InvalidPublicKey);
32 }
33 pk_.copy_from_slice(pk);
34 Ok(PublicKey::new(pk_))
35 }
36 }
37
38 impl Deref for PublicKey {
39 type Target = [u8; PublicKey::BYTES];
40
41 /// Returns a public key as bytes.
42 fn deref(&self) -> &Self::Target {
43 &self.0
44 }
45 }
46
47 impl DerefMut for PublicKey {
48 /// Returns a public key as mutable bytes.
49 fn deref_mut(&mut self) -> &mut Self::Target {
50 &mut self.0
51 }
52 }
53
54 /// A secret key.
55 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
56 pub struct SecretKey([u8; SecretKey::BYTES]);
57
58 impl SecretKey {
59 /// Number of bytes in a secret key.
60 pub const BYTES: usize = 32 + PublicKey::BYTES;
61
62 /// Creates a secret key from raw bytes.
63 pub fn new(sk: [u8; SecretKey::BYTES]) -> Self {
64 SecretKey(sk)
65 }
66
67 /// Creates a secret key from a slice.
68 pub fn from_slice(sk: &[u8]) -> Result<Self, Error> {
69 let mut sk_ = [0u8; SecretKey::BYTES];
70 if sk.len() != sk_.len() {
71 return Err(Error::InvalidSecretKey);
72 }
73 sk_.copy_from_slice(sk);
74 Ok(SecretKey::new(sk_))
75 }
76
77 /// Returns the public counterpart of a secret key.
78 pub fn public_key(&self) -> PublicKey {
79 let mut pk = [0u8; PublicKey::BYTES];
80 pk.copy_from_slice(&self[Seed::BYTES..]);
81 PublicKey(pk)
82 }
83
84 /// Returns the seed of a secret key.
85 pub fn seed(&self) -> Seed {
86 Seed::from_slice(&self[0..Seed::BYTES]).unwrap()
87 }
88
89 /// Returns `Ok(())` if the given public key is the public counterpart of
90 /// this secret key.
91 /// Returns `Err(Error::InvalidPublicKey)` otherwise.
92 /// The public key is recomputed (not just copied) from the secret key,
93 /// so this will detect corruption of the secret key.
94 pub fn validate_public_key(&self, pk: &PublicKey) -> Result<(), Error> {
95 let kp = KeyPair::from_seed(self.seed());
96 if kp.pk != *pk {
97 return Err(Error::InvalidPublicKey);
98 }
99 Ok(())
100 }
101 }
102
103 impl Drop for SecretKey {
104 fn drop(&mut self) {
105 Mem::wipe(self.0)
106 }
107 }
108
109 impl Deref for SecretKey {
110 type Target = [u8; SecretKey::BYTES];
111
112 /// Returns a secret key as bytes.
113 fn deref(&self) -> &Self::Target {
114 &self.0
115 }
116 }
117
118 impl DerefMut for SecretKey {
119 /// Returns a secret key as mutable bytes.
120 fn deref_mut(&mut self) -> &mut Self::Target {
121 &mut self.0
122 }
123 }
124
125 /// A key pair.
126 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
127 pub struct KeyPair {
128 /// Public key part of the key pair.
129 pub pk: PublicKey,
130 /// Secret key part of the key pair.
131 pub sk: SecretKey,
132 }
133
134 /// An Ed25519 signature.
135 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
136 pub struct Signature([u8; Signature::BYTES]);
137
138 impl fmt::Debug for Signature {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 f.write_fmt(format_args!("{:x?}", &self.0))
141 }
142 }
143
144 impl AsRef<[u8]> for Signature {
145 fn as_ref(&self) -> &[u8] {
146 &self.0
147 }
148 }
149
150 impl Signature {
151 /// Number of raw bytes in a signature.
152 pub const BYTES: usize = 64;
153
154 /// Creates a signature from raw bytes.
155 pub fn new(bytes: [u8; Signature::BYTES]) -> Self {
156 Signature(bytes)
157 }
158
159 /// Creates a signature key from a slice.
160 pub fn from_slice(signature: &[u8]) -> Result<Self, Error> {
161 let mut signature_ = [0u8; Signature::BYTES];
162 if signature.len() != signature_.len() {
163 return Err(Error::InvalidSignature);
164 }
165 signature_.copy_from_slice(signature);
166 Ok(Signature::new(signature_))
167 }
168 }
169
170 impl Deref for Signature {
171 type Target = [u8; Signature::BYTES];
172
173 /// Returns a signture as bytes.
174 fn deref(&self) -> &Self::Target {
175 &self.0
176 }
177 }
178
179 impl DerefMut for Signature {
180 /// Returns a signature as mutable bytes.
181 fn deref_mut(&mut self) -> &mut Self::Target {
182 &mut self.0
183 }
184 }
185
186 /// The state of a streaming verification operation.
187 #[derive(Clone)]
188 pub struct VerifyingState {
189 hasher: sha512::Hash,
190 signature: Signature,
191 a: GeP3,
192 }
193
194 impl Drop for VerifyingState {
195 fn drop(&mut self) {
196 Mem::wipe(self.signature.0);
197 }
198 }
199
200 impl VerifyingState {
201 fn new(pk: &PublicKey, signature: &Signature) -> Result<Self, Error> {
202 let r = &signature[0..32];
203 let s = &signature[32..64];
204 sc_reject_noncanonical(s)?;
205 if is_identity(pk) || pk.iter().fold(0, |acc, x| acc | x) == 0 {
206 return Err(Error::WeakPublicKey);
207 }
208 let a = match GeP3::from_bytes_negate_vartime(pk) {
209 Some(g) => g,
210 None => {
211 return Err(Error::InvalidPublicKey);
212 }
213 };
214 let mut hasher = sha512::Hash::new();
215 hasher.update(r);
216 hasher.update(&pk[..]);
217 Ok(VerifyingState {
218 hasher,
219 signature: *signature,
220 a,
221 })
222 }
223
224 /// Appends data to the message being verified.
225 pub fn absorb(&mut self, chunk: impl AsRef<[u8]>) {
226 self.hasher.update(chunk)
227 }
228
229 /// Verifies the signature and return it.
230 pub fn verify(&self) -> Result<(), Error> {
231 let mut expected_r_bytes = [0u8; 32];
232 expected_r_bytes.copy_from_slice(&self.signature[0..32]);
233 let expected_r =
234 GeP3::from_bytes_vartime(&expected_r_bytes).ok_or(Error::InvalidSignature)?;
235 let s = &self.signature[32..64];
236
237 let mut hash = self.hasher.finalize();
238 sc_reduce(&mut hash);
239
240 let r = GeP2::double_scalarmult_vartime(hash.as_ref(), self.a, s);
241 if (expected_r - GeP3::from(r)).has_small_order() {
242 Ok(())
243 } else {
244 Err(Error::SignatureMismatch)
245 }
246 }
247 }
248
249 impl PublicKey {
250 /// Verify the signature of a multi-part message (streaming).
251 pub fn verify_incremental(&self, signature: &Signature) -> Result<VerifyingState, Error> {
252 VerifyingState::new(self, signature)
253 }
254
255 /// Verifies that the signature `signature` is valid for the message
256 /// `message`.
257 pub fn verify(&self, message: impl AsRef<[u8]>, signature: &Signature) -> Result<(), Error> {
258 let mut st = VerifyingState::new(self, signature)?;
259 st.absorb(message);
260 st.verify()
261 }
262 }
263
264 /// The state of a streaming signature operation.
265 #[derive(Clone)]
266 pub struct SigningState {
267 hasher: sha512::Hash,
268 az: [u8; 64],
269 nonce: [u8; 64],
270 }
271
272 impl Drop for SigningState {
273 fn drop(&mut self) {
274 Mem::wipe(self.az);
275 Mem::wipe(self.nonce);
276 }
277 }
278
279 impl SigningState {
280 fn new(nonce: [u8; 64], az: [u8; 64], pk_: &[u8]) -> Self {
281 let mut prefix: [u8; 64] = [0; 64];
282 let r = ge_scalarmult_base(&nonce[0..32]);
283 prefix[0..32].copy_from_slice(&r.to_bytes()[..]);
284 prefix[32..64].copy_from_slice(pk_);
285
286 let mut st = sha512::Hash::new();
287 st.update(prefix);
288
289 SigningState {
290 hasher: st,
291 nonce,
292 az,
293 }
294 }
295
296 /// Appends data to the message being signed.
297 pub fn absorb(&mut self, chunk: impl AsRef<[u8]>) {
298 self.hasher.update(chunk)
299 }
300
301 /// Computes the signature and return it.
302 pub fn sign(&self) -> Signature {
303 let mut signature: [u8; 64] = [0; 64];
304 let r = ge_scalarmult_base(&self.nonce[0..32]);
305 signature[0..32].copy_from_slice(&r.to_bytes()[..]);
306 let mut hram = self.hasher.finalize();
307 sc_reduce(&mut hram);
308 sc_muladd(
309 &mut signature[32..64],
310 &hram[0..32],
311 &self.az[0..32],
312 &self.nonce[0..32],
313 );
314 Signature(signature)
315 }
316 }
317
318 impl SecretKey {
319 /// Sign a multi-part message (streaming API).
320 /// It is critical for `noise` to never repeat.
321 pub fn sign_incremental(&self, noise: Noise) -> SigningState {
322 let seed = &self[0..32];
323 let pk = &self[32..64];
324 let az: [u8; 64] = {
325 let mut hash_output = sha512::Hash::hash(seed);
326 hash_output[0] &= 248;
327 hash_output[31] &= 63;
328 hash_output[31] |= 64;
329 hash_output
330 };
331 let mut st = sha512::Hash::new();
332 #[cfg(feature = "random")]
333 {
334 let additional_noise = Noise::generate();
335 st.update(additional_noise.as_ref());
336 }
337 st.update(noise.as_ref());
338 st.update(seed);
339 let nonce = st.finalize();
340 SigningState::new(nonce, az, pk)
341 }
342
343 /// Computes a signature for the message `message` using the secret key.
344 /// The noise parameter is optional, but recommended in order to mitigate
345 /// fault attacks.
346 pub fn sign(&self, message: impl AsRef<[u8]>, noise: Option<Noise>) -> Signature {
347 let seed = &self[0..32];
348 let pk = &self[32..64];
349 let az: [u8; 64] = {
350 let mut hash_output = sha512::Hash::hash(seed);
351 hash_output[0] &= 248;
352 hash_output[31] &= 63;
353 hash_output[31] |= 64;
354 hash_output
355 };
356 let nonce = {
357 let mut hasher = sha512::Hash::new();
358 if let Some(noise) = noise {
359 hasher.update(&noise[..]);
360 hasher.update(&az[..]);
361 } else {
362 hasher.update(&az[32..64]);
363 }
364 hasher.update(&message);
365 let mut hash_output = hasher.finalize();
366 sc_reduce(&mut hash_output[0..64]);
367 hash_output
368 };
369 let mut st = SigningState::new(nonce, az, pk);
370 st.absorb(&message);
371 let signature = st.sign();
372
373 #[cfg(feature = "self-verify")]
374 {
375 PublicKey::from_slice(pk)
376 .expect("Key length changed")
377 .verify(message, &signature)
378 .expect("Newly created signature cannot be verified");
379 }
380
381 signature
382 }
383 }
384
385 impl KeyPair {
386 /// Number of bytes in a key pair.
387 pub const BYTES: usize = SecretKey::BYTES;
388
389 /// Generates a new key pair.
390 #[cfg(feature = "random")]
391 pub fn generate() -> KeyPair {
392 KeyPair::from_seed(Seed::default())
393 }
394
395 /// Generates a new key pair using a secret seed.
396 pub fn from_seed(seed: Seed) -> KeyPair {
397 if seed.iter().fold(0, |acc, x| acc | x) == 0 {
398 panic!("All-zero seed");
399 }
400 let (scalar, _) = {
401 let hash_output = sha512::Hash::hash(&seed[..]);
402 KeyPair::split(&hash_output, false, true)
403 };
404 let pk = ge_scalarmult_base(&scalar).to_bytes();
405 let mut sk = [0u8; 64];
406 sk[0..32].copy_from_slice(&*seed);
407 sk[32..64].copy_from_slice(&pk);
408 KeyPair {
409 pk: PublicKey(pk),
410 sk: SecretKey(sk),
411 }
412 }
413
414 /// Creates a key pair from a slice.
415 pub fn from_slice(bytes: &[u8]) -> Result<Self, Error> {
416 let sk = SecretKey::from_slice(bytes)?;
417 let pk = sk.public_key();
418 Ok(KeyPair { pk, sk })
419 }
420
421 /// Clamp a scalar.
422 pub fn clamp(scalar: &mut [u8]) {
423 scalar[0] &= 248;
424 scalar[31] &= 63;
425 scalar[31] |= 64;
426 }
427
428 /// Split a serialized representation of a key pair into a secret scalar and
429 /// a prefix.
430 pub fn split(bytes: &[u8; 64], reduce: bool, clamp: bool) -> ([u8; 32], [u8; 32]) {
431 let mut scalar = [0u8; 32];
432 scalar.copy_from_slice(&bytes[0..32]);
433 if clamp {
434 Self::clamp(&mut scalar);
435 }
436 if reduce {
437 sc_reduce32(&mut scalar);
438 }
439 let mut prefix = [0u8; 32];
440 prefix.copy_from_slice(&bytes[32..64]);
441 (scalar, prefix)
442 }
443
444 /// Check that the public key is valid for the secret key.
445 pub fn validate(&self) -> Result<(), Error> {
446 self.sk.validate_public_key(&self.pk)
447 }
448 }
449
450 impl Deref for KeyPair {
451 type Target = [u8; KeyPair::BYTES];
452
453 /// Returns a key pair as bytes.
454 fn deref(&self) -> &Self::Target {
455 &self.sk
456 }
457 }
458
459 impl DerefMut for KeyPair {
460 /// Returns a key pair as mutable bytes.
461 fn deref_mut(&mut self) -> &mut Self::Target {
462 &mut self.sk
463 }
464 }
465
466 /// Noise, for non-deterministic signatures.
467 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
468 pub struct Noise([u8; Noise::BYTES]);
469
470 impl Noise {
471 /// Number of raw bytes for a noise component.
472 pub const BYTES: usize = 16;
473
474 /// Creates a new noise component from raw bytes.
475 pub fn new(noise: [u8; Noise::BYTES]) -> Self {
476 Noise(noise)
477 }
478
479 /// Creates noise from a slice.
480 pub fn from_slice(noise: &[u8]) -> Result<Self, Error> {
481 let mut noise_ = [0u8; Noise::BYTES];
482 if noise.len() != noise_.len() {
483 return Err(Error::InvalidSeed);
484 }
485 noise_.copy_from_slice(noise);
486 Ok(Noise::new(noise_))
487 }
488 }
489
490 impl Deref for Noise {
491 type Target = [u8; Noise::BYTES];
492
493 /// Returns the noise as bytes.
494 fn deref(&self) -> &Self::Target {
495 &self.0
496 }
497 }
498
499 impl DerefMut for Noise {
500 /// Returns the noise as mutable bytes.
501 fn deref_mut(&mut self) -> &mut Self::Target {
502 &mut self.0
503 }
504 }
505
506 #[cfg(feature = "random")]
507 impl Default for Noise {
508 /// Generates random noise.
509 fn default() -> Self {
510 let mut noise = [0u8; Noise::BYTES];
511 getrandom::getrandom(&mut noise).expect("RNG failure");
512 Noise(noise)
513 }
514 }
515
516 #[cfg(feature = "random")]
517 impl Noise {
518 /// Generates random noise.
519 pub fn generate() -> Self {
520 Noise::default()
521 }
522 }
523
524 #[cfg(feature = "traits")]
525 mod ed25519_trait {
526 use ::ed25519::signature as ed25519_trait;
527
528 use super::{PublicKey, SecretKey, Signature};
529
530 impl ed25519_trait::Signature for Signature {
531 fn from_bytes(bytes: &[u8]) -> Result<Self, ed25519_trait::Error> {
532 let mut bytes_ = [0u8; Signature::BYTES];
533 bytes_.copy_from_slice(bytes);
534 Ok(Signature::new(bytes_))
535 }
536 }
537
538 impl ed25519_trait::Signer<Signature> for SecretKey {
539 fn try_sign(&self, message: &[u8]) -> Result<Signature, ed25519_trait::Error> {
540 Ok(self.sign(message, None))
541 }
542 }
543
544 impl ed25519_trait::Verifier<Signature> for PublicKey {
545 fn verify(
546 &self,
547 message: &[u8],
548 signature: &Signature,
549 ) -> Result<(), ed25519_trait::Error> {
550 #[cfg(feature = "std")]
551 {
552 self.verify(message, signature)
553 .map_err(|e| ed25519_trait::Error::from_source(e))
554 }
555
556 #[cfg(not(feature = "std"))]
557 {
558 self.verify(message, signature)
559 .map_err(|_| ed25519_trait::Error::new())
560 }
561 }
562 }
563 }
564
565 #[test]
566 fn test_ed25519() {
567 let kp = KeyPair::from_seed([42u8; 32].into());
568 let message = b"Hello, World!";
569 let signature = kp.sk.sign(message, None);
570 assert!(kp.pk.verify(message, &signature).is_ok());
571 assert!(kp.pk.verify(b"Hello, world!", &signature).is_err());
572 assert_eq!(
573 signature.as_ref(),
574 [
575 196, 182, 1, 15, 182, 182, 231, 166, 227, 62, 243, 85, 49, 174, 169, 9, 162, 196, 98,
576 104, 30, 81, 22, 38, 184, 136, 253, 128, 10, 160, 128, 105, 127, 130, 138, 164, 57, 86,
577 94, 160, 216, 85, 153, 139, 81, 100, 38, 124, 235, 210, 26, 95, 231, 90, 73, 206, 33,
578 216, 171, 15, 188, 181, 136, 7,
579 ]
580 );
581 }
582
583 #[cfg(feature = "blind-keys")]
584 mod blind_keys {
585 use super::*;
586
587 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
588 pub struct Blind([u8; Blind::BYTES]);
589
590 impl From<[u8; 32]> for Blind {
591 fn from(blind: [u8; 32]) -> Self {
592 Blind(blind)
593 }
594 }
595
596 impl Blind {
597 /// Number of raw bytes in a blind.
598 pub const BYTES: usize = 32;
599
600 /// Creates a blind from raw bytes.
601 pub fn new(blind: [u8; Blind::BYTES]) -> Self {
602 Blind(blind)
603 }
604
605 /// Creates a blind from a slice.
606 pub fn from_slice(blind: &[u8]) -> Result<Self, Error> {
607 let mut blind_ = [0u8; Blind::BYTES];
608 if blind.len() != blind_.len() {
609 return Err(Error::InvalidBlind);
610 }
611 blind_.copy_from_slice(blind);
612 Ok(Blind::new(blind_))
613 }
614 }
615
616 impl Drop for Blind {
617 fn drop(&mut self) {
618 Mem::wipe(self.0)
619 }
620 }
621
622 #[cfg(feature = "random")]
623 impl Default for Blind {
624 /// Generates a random blind.
625 fn default() -> Self {
626 let mut blind = [0u8; Blind::BYTES];
627 getrandom::getrandom(&mut blind).expect("RNG failure");
628 Blind(blind)
629 }
630 }
631
632 #[cfg(feature = "random")]
633 impl Blind {
634 /// Generates a random blind.
635 pub fn generate() -> Self {
636 Blind::default()
637 }
638 }
639
640 impl Deref for Blind {
641 type Target = [u8; Blind::BYTES];
642
643 /// Returns a blind as bytes.
644 fn deref(&self) -> &Self::Target {
645 &self.0
646 }
647 }
648
649 impl DerefMut for Blind {
650 /// Returns a blind as mutable bytes.
651 fn deref_mut(&mut self) -> &mut Self::Target {
652 &mut self.0
653 }
654 }
655
656 /// A blind public key.
657 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
658 pub struct BlindPublicKey([u8; PublicKey::BYTES]);
659
660 impl Deref for BlindPublicKey {
661 type Target = [u8; BlindPublicKey::BYTES];
662
663 /// Returns a public key as bytes.
664 fn deref(&self) -> &Self::Target {
665 &self.0
666 }
667 }
668
669 impl DerefMut for BlindPublicKey {
670 /// Returns a public key as mutable bytes.
671 fn deref_mut(&mut self) -> &mut Self::Target {
672 &mut self.0
673 }
674 }
675
676 impl BlindPublicKey {
677 /// Number of bytes in a blind public key.
678 pub const BYTES: usize = PublicKey::BYTES;
679
680 /// Creates a blind public key from raw bytes.
681 pub fn new(bpk: [u8; PublicKey::BYTES]) -> Self {
682 BlindPublicKey(bpk)
683 }
684
685 /// Creates a blind public key from a slice.
686 pub fn from_slice(bpk: &[u8]) -> Result<Self, Error> {
687 let mut bpk_ = [0u8; PublicKey::BYTES];
688 if bpk.len() != bpk_.len() {
689 return Err(Error::InvalidPublicKey);
690 }
691 bpk_.copy_from_slice(bpk);
692 Ok(BlindPublicKey::new(bpk_))
693 }
694
695 /// Unblinds a public key.
696 pub fn unblind(&self, blind: &Blind, ctx: impl AsRef<[u8]>) -> Result<PublicKey, Error> {
697 let pk_p3 = GeP3::from_bytes_vartime(&self.0).ok_or(Error::InvalidPublicKey)?;
698 let mut hx = sha512::Hash::new();
699 hx.update(&blind[..]);
700 hx.update([0u8]);
701 hx.update(ctx.as_ref());
702 let hash_output = hx.finalize();
703 let (blind_factor, _) = KeyPair::split(&hash_output, true, false);
704 let inverse = sc_invert(&blind_factor);
705 Ok(PublicKey(ge_scalarmult(&inverse, &pk_p3).to_bytes()))
706 }
707
708 /// Verifies that the signature `signature` is valid for the message
709 /// `message`.
710 pub fn verify(
711 &self,
712 message: impl AsRef<[u8]>,
713 signature: &Signature,
714 ) -> Result<(), Error> {
715 PublicKey::new(self.0).verify(message, signature)
716 }
717 }
718
719 impl From<PublicKey> for BlindPublicKey {
720 fn from(pk: PublicKey) -> Self {
721 BlindPublicKey(pk.0)
722 }
723 }
724
725 impl From<BlindPublicKey> for PublicKey {
726 fn from(bpk: BlindPublicKey) -> Self {
727 PublicKey(bpk.0)
728 }
729 }
730
731 /// A blind secret key.
732 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
733 pub struct BlindSecretKey {
734 pub prefix: [u8; 2 * Seed::BYTES],
735 pub blind_scalar: [u8; 32],
736 pub blind_pk: BlindPublicKey,
737 }
738
739 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
740 pub struct BlindKeyPair {
741 /// Public key part of the blind key pair.
742 pub blind_pk: BlindPublicKey,
743 /// Secret key part of the blind key pair.
744 pub blind_sk: BlindSecretKey,
745 }
746
747 impl BlindSecretKey {
748 /// Computes a signature for the message `message` using the blind
749 /// secret key. The noise parameter is optional, but recommended
750 /// in order to mitigate fault attacks.
751 pub fn sign(&self, message: impl AsRef<[u8]>, noise: Option<Noise>) -> Signature {
752 let nonce = {
753 let mut hasher = sha512::Hash::new();
754 if let Some(noise) = noise {
755 hasher.update(&noise[..]);
756 hasher.update(self.prefix);
757 } else {
758 hasher.update(self.prefix);
759 }
760 hasher.update(&message);
761 let mut hash_output = hasher.finalize();
762 sc_reduce(&mut hash_output[0..64]);
763 hash_output
764 };
765 let mut signature: [u8; 64] = [0; 64];
766 let r = ge_scalarmult_base(&nonce[0..32]);
767 signature[0..32].copy_from_slice(&r.to_bytes()[..]);
768 signature[32..64].copy_from_slice(&self.blind_pk.0);
769 let mut hasher = sha512::Hash::new();
770 hasher.update(signature.as_ref());
771 hasher.update(&message);
772 let mut hram = hasher.finalize();
773 sc_reduce(&mut hram);
774 sc_muladd(
775 &mut signature[32..64],
776 &hram[0..32],
777 &self.blind_scalar,
778 &nonce[0..32],
779 );
780 let signature = Signature(signature);
781
782 #[cfg(feature = "self-verify")]
783 {
784 PublicKey::from_slice(&self.blind_pk.0)
785 .expect("Key length changed")
786 .verify(message, &signature)
787 .expect("Newly created signature cannot be verified");
788 }
789 signature
790 }
791 }
792
793 impl Drop for BlindSecretKey {
794 fn drop(&mut self) {
795 Mem::wipe(self.prefix);
796 Mem::wipe(self.blind_scalar);
797 }
798 }
799
800 impl PublicKey {
801 /// Returns a blind version of the public key.
802 pub fn blind(&self, blind: &Blind, ctx: impl AsRef<[u8]>) -> Result<BlindPublicKey, Error> {
803 let (blind_factor, _prefix2) = {
804 let mut hx = sha512::Hash::new();
805 hx.update(&blind[..]);
806 hx.update([0u8]);
807 hx.update(ctx.as_ref());
808 let hash_output = hx.finalize();
809 KeyPair::split(&hash_output, true, false)
810 };
811 let pk_p3 = GeP3::from_bytes_vartime(&self.0).ok_or(Error::InvalidPublicKey)?;
812 Ok(BlindPublicKey(
813 ge_scalarmult(&blind_factor, &pk_p3).to_bytes(),
814 ))
815 }
816 }
817
818 impl KeyPair {
819 /// Returns a blind version of the key pair.
820 pub fn blind(&self, blind: &Blind, ctx: impl AsRef<[u8]>) -> BlindKeyPair {
821 let seed = self.sk.seed();
822 let (scalar, prefix1) = {
823 let hash_output = sha512::Hash::hash(&seed[..]);
824 KeyPair::split(&hash_output, false, true)
825 };
826
827 let (blind_factor, prefix2) = {
828 let mut hx = sha512::Hash::new();
829 hx.update(&blind[..]);
830 hx.update([0u8]);
831 hx.update(ctx.as_ref());
832 let hash_output = hx.finalize();
833 KeyPair::split(&hash_output, true, false)
834 };
835
836 let blind_scalar = sc_mul(&scalar, &blind_factor);
837 let blind_pk = ge_scalarmult_base(&blind_scalar).to_bytes();
838
839 let mut prefix = [0u8; 2 * Seed::BYTES];
840 prefix[0..32].copy_from_slice(&prefix1);
841 prefix[32..64].copy_from_slice(&prefix2);
842 let blind_pk = BlindPublicKey::new(blind_pk);
843
844 BlindKeyPair {
845 blind_pk,
846 blind_sk: BlindSecretKey {
847 prefix,
848 blind_scalar,
849 blind_pk,
850 },
851 }
852 }
853 }
854 }
855
856 #[cfg(feature = "blind-keys")]
857 pub use blind_keys::*;
858
859 #[test]
860 #[cfg(feature = "blind-keys")]
861 fn test_blind_ed25519() {
862 use ct_codecs::{Decoder, Hex};
863
864 let kp = KeyPair::generate();
865 let blind = Blind::new([69u8; 32]);
866 let blind_kp = kp.blind(&blind, "ctx");
867 let message = b"Hello, World!";
868 let signature = blind_kp.blind_sk.sign(message, None);
869 assert!(blind_kp.blind_pk.verify(message, &signature).is_ok());
870 let recovered_pk = blind_kp.blind_pk.unblind(&blind, "ctx").unwrap();
871 assert!(recovered_pk == kp.pk);
872
873 let kp = KeyPair::from_seed(
874 Seed::from_slice(
875 &Hex::decode_to_vec(
876 "875532ab039b0a154161c284e19c74afa28d5bf5454e99284bbcffaa71eebf45",
877 None,
878 )
879 .unwrap(),
880 )
881 .unwrap(),
882 );
883 assert_eq!(
884 Hex::decode_to_vec(
885 "3b5983605b277cd44918410eb246bb52d83adfc806ccaa91a60b5b2011bc5973",
886 None
887 )
888 .unwrap(),
889 kp.pk.as_ref()
890 );
891
892 let blind = Blind::from_slice(
893 &Hex::decode_to_vec(
894 "c461e8595f0ac41d374f878613206704978115a226f60470ffd566e9e6ae73bf",
895 None,
896 )
897 .unwrap(),
898 )
899 .unwrap();
900 let blind_kp = kp.blind(&blind, "ctx");
901 assert_eq!(
902 Hex::decode_to_vec(
903 "246dcd43930b81d5e4d770db934a9fcd985b75fd014bc2a98b0aea02311c1836",
904 None
905 )
906 .unwrap(),
907 blind_kp.blind_pk.as_ref()
908 );
909
910 let message = Hex::decode_to_vec("68656c6c6f20776f726c64", None).unwrap();
911 let signature = blind_kp.blind_sk.sign(message, None);
912 assert_eq!(Hex::decode_to_vec("947bacfabc63448f8955dc20630e069e58f37b72bb433ae17f2fa904ea860b44deb761705a3cc2168a6673ee0b41ff7765c7a4896941eec6833c1689315acb0b",
913 None).unwrap(), signature.as_ref());
914 }
915
916 #[test]
917 fn test_streaming() {
918 let kp = KeyPair::generate();
919
920 let msg1 = "mes";
921 let msg2 = "sage";
922 let mut st = kp.sk.sign_incremental(Noise::default());
923 st.absorb(msg1);
924 st.absorb(msg2);
925 let signature = st.sign();
926
927 let msg1 = "mess";
928 let msg2 = "age";
929 let mut st = kp.pk.verify_incremental(&signature).unwrap();
930 st.absorb(msg1);
931 st.absorb(msg2);
932 assert!(st.verify().is_ok());
933 }
934
935 #[test]
936 #[cfg(feature = "random")]
937 fn test_ed25519_invalid_keypair() {
938 let kp1 = KeyPair::generate();
939 let kp2 = KeyPair::generate();
940
941 assert_eq!(
942 kp1.sk.validate_public_key(&kp2.pk).unwrap_err(),
943 Error::InvalidPublicKey
944 );
945 assert_eq!(
946 kp2.sk.validate_public_key(&kp1.pk).unwrap_err(),
947 Error::InvalidPublicKey
948 );
949 assert!(kp1.sk.validate_public_key(&kp1.pk).is_ok());
950 assert!(kp2.sk.validate_public_key(&kp2.pk).is_ok());
951 assert!(kp1.validate().is_ok());
952 }