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