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 // Test `AsRef<[u8]>`
64 assert_eq!(unparsed_public_key.as_ref(), &[0x01, 0x02, 0x03]);
65 }
66
67 #[test]
agreement_agree_ephemeral()68 fn agreement_agree_ephemeral() {
69 let rng = rand::SystemRandom::new();
70
71 test::run(test_file!("agreement_tests.txt"), |section, test_case| {
72 assert_eq!(section, "");
73
74 let curve_name = test_case.consume_string("Curve");
75 let alg = alg_from_curve_name(&curve_name);
76 let peer_public = agreement::UnparsedPublicKey::new(alg, test_case.consume_bytes("PeerQ"));
77
78 match test_case.consume_optional_string("Error") {
79 None => {
80 let my_private = test_case.consume_bytes("D");
81 let my_private = {
82 let rng = test::rand::FixedSliceRandom { bytes: &my_private };
83 agreement::EphemeralPrivateKey::generate(alg, &rng)?
84 };
85 let my_public = test_case.consume_bytes("MyQ");
86 let output = test_case.consume_bytes("Output");
87
88 assert_eq!(my_private.algorithm(), alg);
89
90 let computed_public = my_private.compute_public_key().unwrap();
91 assert_eq!(computed_public.as_ref(), &my_public[..]);
92
93 assert_eq!(my_private.algorithm(), alg);
94
95 let result = agreement::agree_ephemeral(my_private, &peer_public, |key_material| {
96 assert_eq!(key_material, &output[..]);
97 });
98 assert_eq!(result, Ok(()));
99 }
100
101 Some(_) => {
102 // In the no-heap mode, some algorithms aren't supported so
103 // we have to skip those algorithms' test cases.
104 let dummy_private_key = agreement::EphemeralPrivateKey::generate(alg, &rng)?;
105 fn kdf_not_called(_: &[u8]) -> Result<(), ()> {
106 panic!(
107 "The KDF was called during ECDH when the peer's \
108 public key is invalid."
109 );
110 }
111 assert!(agreement::agree_ephemeral(
112 dummy_private_key,
113 &peer_public,
114 kdf_not_called
115 )
116 .is_err());
117 }
118 }
119
120 Ok(())
121 });
122 }
123
124 #[test]
test_agreement_ecdh_x25519_rfc_iterated()125 fn test_agreement_ecdh_x25519_rfc_iterated() {
126 let mut k = h("0900000000000000000000000000000000000000000000000000000000000000");
127 let mut u = k.clone();
128
129 fn expect_iterated_x25519(
130 expected_result: &str,
131 range: core::ops::Range<usize>,
132 k: &mut Vec<u8>,
133 u: &mut Vec<u8>,
134 ) {
135 for _ in range {
136 let new_k = x25519(k, u);
137 *u = k.clone();
138 *k = new_k;
139 }
140 assert_eq!(&h(expected_result), k);
141 }
142
143 expect_iterated_x25519(
144 "422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079",
145 0..1,
146 &mut k,
147 &mut u,
148 );
149 expect_iterated_x25519(
150 "684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51",
151 1..1_000,
152 &mut k,
153 &mut u,
154 );
155
156 // The spec gives a test vector for 1,000,000 iterations but it takes
157 // too long to do 1,000,000 iterations by default right now. This
158 // 10,000 iteration vector is self-computed.
159 expect_iterated_x25519(
160 "2c125a20f639d504a7703d2e223c79a79de48c4ee8c23379aa19a62ecd211815",
161 1_000..10_000,
162 &mut k,
163 &mut u,
164 );
165
166 if cfg!(feature = "slow_tests") {
167 expect_iterated_x25519(
168 "7c3911e0ab2586fd864497297e575e6f3bc601c0883c30df5f4dd2d24f665424",
169 10_000..1_000_000,
170 &mut k,
171 &mut u,
172 );
173 }
174 }
175
x25519(private_key: &[u8], public_key: &[u8]) -> Vec<u8>176 fn x25519(private_key: &[u8], public_key: &[u8]) -> Vec<u8> {
177 x25519_(private_key, public_key).unwrap()
178 }
179
x25519_(private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, error::Unspecified>180 fn x25519_(private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, error::Unspecified> {
181 let rng = test::rand::FixedSliceRandom { bytes: private_key };
182 let private_key = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng)?;
183 let public_key = agreement::UnparsedPublicKey::new(&agreement::X25519, public_key);
184 agreement::agree_ephemeral(private_key, &public_key, |agreed_value| {
185 Vec::from(agreed_value)
186 })
187 }
188
h(s: &str) -> Vec<u8>189 fn h(s: &str) -> Vec<u8> {
190 match test::from_hex(s) {
191 Ok(v) => v,
192 Err(msg) => {
193 panic!("{} in {}", msg, s);
194 }
195 }
196 }
197
alg_from_curve_name(curve_name: &str) -> &'static agreement::Algorithm198 fn alg_from_curve_name(curve_name: &str) -> &'static agreement::Algorithm {
199 if curve_name == "P-256" {
200 &agreement::ECDH_P256
201 } else if curve_name == "P-384" {
202 &agreement::ECDH_P384
203 } else if curve_name == "X25519" {
204 &agreement::X25519
205 } else {
206 panic!("Unsupported curve: {}", curve_name);
207 }
208 }
209