diffie_hellman.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. use num_bigint::BigUint;
  2. use num_traits::FromPrimitive;
  3. use rand::Rng;
  4. use crate::util;
  5. lazy_static! {
  6. pub static ref DH_GENERATOR: BigUint = BigUint::from_u64(0x2).unwrap();
  7. pub static ref DH_PRIME: BigUint = BigUint::from_bytes_be(&[
  8. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2,
  9. 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67,
  10. 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e,
  11. 0x34, 0x04, 0xdd, 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d,
  12. 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5,
  13. 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff,
  14. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  15. ]);
  16. }
  17. pub struct DHLocalKeys {
  18. private_key: BigUint,
  19. public_key: BigUint,
  20. }
  21. impl DHLocalKeys {
  22. pub fn random<R: Rng>(rng: &mut R) -> DHLocalKeys {
  23. let key_data = util::rand_vec(rng, 95);
  24. let private_key = BigUint::from_bytes_be(&key_data);
  25. let public_key = util::powm(&DH_GENERATOR, &private_key, &DH_PRIME);
  26. DHLocalKeys {
  27. private_key: private_key,
  28. public_key: public_key,
  29. }
  30. }
  31. pub fn public_key(&self) -> Vec<u8> {
  32. self.public_key.to_bytes_be()
  33. }
  34. pub fn shared_secret(&self, remote_key: &[u8]) -> Vec<u8> {
  35. let shared_key = util::powm(
  36. &BigUint::from_bytes_be(remote_key),
  37. &self.private_key,
  38. &DH_PRIME,
  39. );
  40. shared_key.to_bytes_be()
  41. }
  42. }