• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
15 #![cfg(not(target_arch = "wasm32"))]
16 
17 extern crate alloc;
18 
19 use ring::{agreement, error, rand, test, test_file};
20 
21 #[test]
agreement_traits()22 fn agreement_traits() {
23     use alloc::vec::Vec;
24 
25     let rng = rand::SystemRandom::new();
26     let private_key =
27         agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng).unwrap();
28 
29     test::compile_time_assert_send::<agreement::EphemeralPrivateKey>();
30     test::compile_time_assert_sync::<agreement::EphemeralPrivateKey>();
31 
32     assert_eq!(
33         format!("{:?}", &private_key),
34         "EphemeralPrivateKey { algorithm: Algorithm { curve: P256 } }"
35     );
36 
37     let public_key = private_key.compute_public_key().unwrap();
38 
39     test::compile_time_assert_clone::<agreement::PublicKey>();
40     test::compile_time_assert_send::<agreement::PublicKey>();
41     test::compile_time_assert_sync::<agreement::PublicKey>();
42 
43     // Verify `PublicKey` implements `Debug`.
44     //
45     // TODO: Test the actual output.
46     let _: &dyn core::fmt::Debug = &public_key;
47 
48     test::compile_time_assert_clone::<agreement::UnparsedPublicKey<&[u8]>>();
49     test::compile_time_assert_copy::<agreement::UnparsedPublicKey<&[u8]>>();
50     test::compile_time_assert_sync::<agreement::UnparsedPublicKey<&[u8]>>();
51 
52     test::compile_time_assert_clone::<agreement::UnparsedPublicKey<Vec<u8>>>();
53     test::compile_time_assert_sync::<agreement::UnparsedPublicKey<Vec<u8>>>();
54 
55     let unparsed_public_key =
56         agreement::UnparsedPublicKey::new(&agreement::X25519, &[0x01, 0x02, 0x03]);
57 
58     assert_eq!(
59         format!("{:?}", unparsed_public_key),
60         r#"UnparsedPublicKey { algorithm: Algorithm { curve: Curve25519 }, bytes: "010203" }"#
61     );
62 }
63 
64 #[test]
agreement_agree_ephemeral()65 fn agreement_agree_ephemeral() {
66     let rng = rand::SystemRandom::new();
67 
68     test::run(test_file!("agreement_tests.txt"), |section, test_case| {
69         assert_eq!(section, "");
70 
71         let curve_name = test_case.consume_string("Curve");
72         let alg = alg_from_curve_name(&curve_name);
73         let peer_public = agreement::UnparsedPublicKey::new(alg, test_case.consume_bytes("PeerQ"));
74 
75         match test_case.consume_optional_string("Error") {
76             None => {
77                 let my_private = test_case.consume_bytes("D");
78                 let my_private = {
79                     let rng = test::rand::FixedSliceRandom { bytes: &my_private };
80                     agreement::EphemeralPrivateKey::generate(alg, &rng)?
81                 };
82                 let my_public = test_case.consume_bytes("MyQ");
83                 let output = test_case.consume_bytes("Output");
84 
85                 assert_eq!(my_private.algorithm(), alg);
86 
87                 let computed_public = my_private.compute_public_key().unwrap();
88                 assert_eq!(computed_public.as_ref(), &my_public[..]);
89 
90                 assert_eq!(my_private.algorithm(), alg);
91 
92                 let result = agreement::agree_ephemeral(my_private, &peer_public, |key_material| {
93                     assert_eq!(key_material, &output[..]);
94                 });
95                 assert_eq!(result, Ok(()));
96             }
97 
98             Some(_) => {
99                 // In the no-heap mode, some algorithms aren't supported so
100                 // we have to skip those algorithms' test cases.
101                 let dummy_private_key = agreement::EphemeralPrivateKey::generate(alg, &rng)?;
102                 fn kdf_not_called(_: &[u8]) -> Result<(), ()> {
103                     panic!(
104                         "The KDF was called during ECDH when the peer's \
105                          public key is invalid."
106                     );
107                 }
108                 assert!(agreement::agree_ephemeral(
109                     dummy_private_key,
110                     &peer_public,
111                     kdf_not_called
112                 )
113                 .is_err());
114             }
115         }
116 
117         Ok(())
118     });
119 }
120 
121 #[test]
test_agreement_ecdh_x25519_rfc_iterated()122 fn test_agreement_ecdh_x25519_rfc_iterated() {
123     let mut k = h("0900000000000000000000000000000000000000000000000000000000000000");
124     let mut u = k.clone();
125 
126     fn expect_iterated_x25519(
127         expected_result: &str,
128         range: core::ops::Range<usize>,
129         k: &mut Vec<u8>,
130         u: &mut Vec<u8>,
131     ) {
132         for _ in range {
133             let new_k = x25519(k, u);
134             *u = k.clone();
135             *k = new_k;
136         }
137         assert_eq!(&h(expected_result), k);
138     }
139 
140     expect_iterated_x25519(
141         "422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079",
142         0..1,
143         &mut k,
144         &mut u,
145     );
146     expect_iterated_x25519(
147         "684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51",
148         1..1_000,
149         &mut k,
150         &mut u,
151     );
152 
153     // The spec gives a test vector for 1,000,000 iterations but it takes
154     // too long to do 1,000,000 iterations by default right now. This
155     // 10,000 iteration vector is self-computed.
156     expect_iterated_x25519(
157         "2c125a20f639d504a7703d2e223c79a79de48c4ee8c23379aa19a62ecd211815",
158         1_000..10_000,
159         &mut k,
160         &mut u,
161     );
162 
163     if cfg!(feature = "slow_tests") {
164         expect_iterated_x25519(
165             "7c3911e0ab2586fd864497297e575e6f3bc601c0883c30df5f4dd2d24f665424",
166             10_000..1_000_000,
167             &mut k,
168             &mut u,
169         );
170     }
171 }
172 
x25519(private_key: &[u8], public_key: &[u8]) -> Vec<u8>173 fn x25519(private_key: &[u8], public_key: &[u8]) -> Vec<u8> {
174     x25519_(private_key, public_key).unwrap()
175 }
176 
x25519_(private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, error::Unspecified>177 fn x25519_(private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, error::Unspecified> {
178     let rng = test::rand::FixedSliceRandom { bytes: private_key };
179     let private_key = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng)?;
180     let public_key = agreement::UnparsedPublicKey::new(&agreement::X25519, public_key);
181     agreement::agree_ephemeral(private_key, &public_key, |agreed_value| {
182         Vec::from(agreed_value)
183     })
184 }
185 
h(s: &str) -> Vec<u8>186 fn h(s: &str) -> Vec<u8> {
187     match test::from_hex(s) {
188         Ok(v) => v,
189         Err(msg) => {
190             panic!("{} in {}", msg, s);
191         }
192     }
193 }
194 
alg_from_curve_name(curve_name: &str) -> &'static agreement::Algorithm195 fn alg_from_curve_name(curve_name: &str) -> &'static agreement::Algorithm {
196     if curve_name == "P-256" {
197         &agreement::ECDH_P256
198     } else if curve_name == "P-384" {
199         &agreement::ECDH_P384
200     } else if curve_name == "X25519" {
201         &agreement::X25519
202     } else {
203         panic!("Unsupported curve: {}", curve_name);
204     }
205 }
206