agreement_tests.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // Copyright 2015-2017 Brian Smith.
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
  8. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
  10. // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. extern crate alloc;
  15. use ring::{agreement, error, rand, test, test_file};
  16. #[test]
  17. fn agreement_traits() {
  18. use alloc::vec::Vec;
  19. let rng = rand::SystemRandom::new();
  20. let private_key =
  21. agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng).unwrap();
  22. test::compile_time_assert_send::<agreement::EphemeralPrivateKey>();
  23. test::compile_time_assert_sync::<agreement::EphemeralPrivateKey>();
  24. assert_eq!(
  25. format!("{:?}", &private_key),
  26. "EphemeralPrivateKey { algorithm: Algorithm { curve: P256 } }"
  27. );
  28. let public_key = private_key.compute_public_key().unwrap();
  29. test::compile_time_assert_clone::<agreement::PublicKey>();
  30. test::compile_time_assert_send::<agreement::PublicKey>();
  31. test::compile_time_assert_sync::<agreement::PublicKey>();
  32. // Verify `PublicKey` implements `Debug`.
  33. //
  34. // TODO: Test the actual output.
  35. let _: &dyn core::fmt::Debug = &public_key;
  36. test::compile_time_assert_clone::<agreement::UnparsedPublicKey<&[u8]>>();
  37. test::compile_time_assert_copy::<agreement::UnparsedPublicKey<&[u8]>>();
  38. test::compile_time_assert_sync::<agreement::UnparsedPublicKey<&[u8]>>();
  39. test::compile_time_assert_clone::<agreement::UnparsedPublicKey<Vec<u8>>>();
  40. test::compile_time_assert_sync::<agreement::UnparsedPublicKey<Vec<u8>>>();
  41. let unparsed_public_key =
  42. agreement::UnparsedPublicKey::new(&agreement::X25519, &[0x01, 0x02, 0x03]);
  43. assert_eq!(
  44. format!("{:?}", unparsed_public_key),
  45. r#"UnparsedPublicKey { algorithm: Algorithm { curve: Curve25519 }, bytes: "010203" }"#
  46. );
  47. }
  48. #[test]
  49. fn agreement_agree_ephemeral() {
  50. let rng = rand::SystemRandom::new();
  51. test::run(test_file!("agreement_tests.txt"), |section, test_case| {
  52. assert_eq!(section, "");
  53. let curve_name = test_case.consume_string("Curve");
  54. let alg = alg_from_curve_name(&curve_name);
  55. let peer_public = agreement::UnparsedPublicKey::new(alg, test_case.consume_bytes("PeerQ"));
  56. match test_case.consume_optional_string("Error") {
  57. None => {
  58. let my_private = test_case.consume_bytes("D");
  59. let my_private = {
  60. let rng = test::rand::FixedSliceRandom { bytes: &my_private };
  61. agreement::EphemeralPrivateKey::generate(alg, &rng)?
  62. };
  63. let my_public = test_case.consume_bytes("MyQ");
  64. let output = test_case.consume_bytes("Output");
  65. assert_eq!(my_private.algorithm(), alg);
  66. let computed_public = my_private.compute_public_key().unwrap();
  67. assert_eq!(computed_public.as_ref(), &my_public[..]);
  68. assert_eq!(my_private.algorithm(), alg);
  69. let result =
  70. agreement::agree_ephemeral(my_private, &peer_public, (), |key_material| {
  71. assert_eq!(key_material, &output[..]);
  72. Ok(())
  73. });
  74. assert_eq!(result, Ok(()));
  75. }
  76. Some(_) => {
  77. // In the no-heap mode, some algorithms aren't supported so
  78. // we have to skip those algorithms' test cases.
  79. let dummy_private_key = agreement::EphemeralPrivateKey::generate(alg, &rng)?;
  80. fn kdf_not_called(_: &[u8]) -> Result<(), ()> {
  81. panic!(
  82. "The KDF was called during ECDH when the peer's \
  83. public key is invalid."
  84. );
  85. }
  86. assert!(agreement::agree_ephemeral(
  87. dummy_private_key,
  88. &peer_public,
  89. (),
  90. kdf_not_called
  91. )
  92. .is_err());
  93. }
  94. }
  95. Ok(())
  96. });
  97. }
  98. #[test]
  99. fn test_agreement_ecdh_x25519_rfc_iterated() {
  100. let mut k = h("0900000000000000000000000000000000000000000000000000000000000000");
  101. let mut u = k.clone();
  102. fn expect_iterated_x25519(
  103. expected_result: &str,
  104. range: core::ops::Range<usize>,
  105. k: &mut Vec<u8>,
  106. u: &mut Vec<u8>,
  107. ) {
  108. for _ in range {
  109. let new_k = x25519(k, u);
  110. *u = k.clone();
  111. *k = new_k;
  112. }
  113. assert_eq!(&h(expected_result), k);
  114. }
  115. expect_iterated_x25519(
  116. "422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079",
  117. 0..1,
  118. &mut k,
  119. &mut u,
  120. );
  121. expect_iterated_x25519(
  122. "684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51",
  123. 1..1_000,
  124. &mut k,
  125. &mut u,
  126. );
  127. // The spec gives a test vector for 1,000,000 iterations but it takes
  128. // too long to do 1,000,000 iterations by default right now. This
  129. // 10,000 iteration vector is self-computed.
  130. expect_iterated_x25519(
  131. "2c125a20f639d504a7703d2e223c79a79de48c4ee8c23379aa19a62ecd211815",
  132. 1_000..10_000,
  133. &mut k,
  134. &mut u,
  135. );
  136. if cfg!(feature = "slow_tests") {
  137. expect_iterated_x25519(
  138. "7c3911e0ab2586fd864497297e575e6f3bc601c0883c30df5f4dd2d24f665424",
  139. 10_000..1_000_000,
  140. &mut k,
  141. &mut u,
  142. );
  143. }
  144. }
  145. fn x25519(private_key: &[u8], public_key: &[u8]) -> Vec<u8> {
  146. x25519_(private_key, public_key).unwrap()
  147. }
  148. fn x25519_(private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, error::Unspecified> {
  149. let rng = test::rand::FixedSliceRandom { bytes: private_key };
  150. let private_key = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng)?;
  151. let public_key = agreement::UnparsedPublicKey::new(&agreement::X25519, public_key);
  152. agreement::agree_ephemeral(
  153. private_key,
  154. &public_key,
  155. error::Unspecified,
  156. |agreed_value| Ok(Vec::from(agreed_value)),
  157. )
  158. }
  159. fn h(s: &str) -> Vec<u8> {
  160. match test::from_hex(s) {
  161. Ok(v) => v,
  162. Err(msg) => {
  163. panic!("{} in {}", msg, s);
  164. }
  165. }
  166. }
  167. fn alg_from_curve_name(curve_name: &str) -> &'static agreement::Algorithm {
  168. if curve_name == "P-256" {
  169. &agreement::ECDH_P256
  170. } else if curve_name == "P-384" {
  171. &agreement::ECDH_P384
  172. } else if curve_name == "X25519" {
  173. &agreement::X25519
  174. } else {
  175. panic!("Unsupported curve: {}", curve_name);
  176. }
  177. }