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 use ring::{
16     error, rand,
17     signature::{self, Ed25519KeyPair, KeyPair},
18     test, test_file,
19 };
20 
21 #[cfg(target_arch = "wasm32")]
22 use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
23 
24 #[cfg(target_arch = "wasm32")]
25 wasm_bindgen_test_configure!(run_in_browser);
26 
27 /// Test vectors from BoringSSL.
28 #[test]
test_signature_ed25519()29 fn test_signature_ed25519() {
30     test::run(test_file!("ed25519_tests.txt"), |section, test_case| {
31         assert_eq!(section, "");
32         let seed = test_case.consume_bytes("SEED");
33         assert_eq!(32, seed.len());
34 
35         let public_key = test_case.consume_bytes("PUB");
36         assert_eq!(32, public_key.len());
37 
38         let msg = test_case.consume_bytes("MESSAGE");
39 
40         let expected_sig = test_case.consume_bytes("SIG");
41 
42         {
43             let key_pair = Ed25519KeyPair::from_seed_and_public_key(&seed, &public_key).unwrap();
44             let actual_sig = key_pair.sign(&msg);
45             assert_eq!(&expected_sig[..], actual_sig.as_ref());
46         }
47 
48         // Test PKCS#8 generation, parsing, and private-to-public calculations.
49         let rng = test::rand::FixedSliceRandom { bytes: &seed };
50         let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
51         let key_pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap();
52         assert_eq!(public_key, key_pair.public_key().as_ref());
53 
54         // Test Signature generation.
55         let actual_sig = key_pair.sign(&msg);
56         assert_eq!(&expected_sig[..], actual_sig.as_ref());
57 
58         // Test Signature verification.
59         test_signature_verification(&public_key, &msg, &expected_sig, Ok(()));
60 
61         let mut tampered_sig = expected_sig;
62         tampered_sig[0] ^= 1;
63 
64         test_signature_verification(&public_key, &msg, &tampered_sig, Err(error::Unspecified));
65 
66         Ok(())
67     });
68 }
69 
70 /// Test vectors from BoringSSL.
71 #[test]
test_signature_ed25519_verify()72 fn test_signature_ed25519_verify() {
73     test::run(
74         test_file!("ed25519_verify_tests.txt"),
75         |section, test_case| {
76             assert_eq!(section, "");
77 
78             let public_key = test_case.consume_bytes("PUB");
79             let msg = test_case.consume_bytes("MESSAGE");
80             let sig = test_case.consume_bytes("SIG");
81             let expected_result = match test_case.consume_string("Result").as_str() {
82                 "P" => Ok(()),
83                 "F" => Err(error::Unspecified),
84                 s => panic!("{:?} is not a valid result", s),
85             };
86             test_signature_verification(&public_key, &msg, &sig, expected_result);
87             Ok(())
88         },
89     );
90 }
91 
test_signature_verification( public_key: &[u8], msg: &[u8], sig: &[u8], expected_result: Result<(), error::Unspecified>, )92 fn test_signature_verification(
93     public_key: &[u8],
94     msg: &[u8],
95     sig: &[u8],
96     expected_result: Result<(), error::Unspecified>,
97 ) {
98     assert_eq!(
99         expected_result,
100         signature::UnparsedPublicKey::new(&signature::ED25519, public_key).verify(msg, sig)
101     );
102 }
103 
104 #[test]
test_ed25519_from_seed_and_public_key_misuse()105 fn test_ed25519_from_seed_and_public_key_misuse() {
106     const PRIVATE_KEY: &[u8] = include_bytes!("ed25519_test_private_key.bin");
107     const PUBLIC_KEY: &[u8] = include_bytes!("ed25519_test_public_key.bin");
108 
109     assert!(Ed25519KeyPair::from_seed_and_public_key(PRIVATE_KEY, PUBLIC_KEY).is_ok());
110 
111     // Truncated private key.
112     assert!(Ed25519KeyPair::from_seed_and_public_key(&PRIVATE_KEY[..31], PUBLIC_KEY).is_err());
113 
114     // Truncated public key.
115     assert!(Ed25519KeyPair::from_seed_and_public_key(PRIVATE_KEY, &PUBLIC_KEY[..31]).is_err());
116 
117     // Swapped public and private key.
118     assert!(Ed25519KeyPair::from_seed_and_public_key(PUBLIC_KEY, PRIVATE_KEY).is_err());
119 }
120 
121 enum FromPkcs8Variant {
122     Checked,
123     MaybeUnchecked,
124 }
125 
126 #[test]
test_ed25519_from_pkcs8_unchecked()127 fn test_ed25519_from_pkcs8_unchecked() {
128     test_ed25519_from_pkcs8_(
129         FromPkcs8Variant::MaybeUnchecked,
130         Ed25519KeyPair::from_pkcs8_maybe_unchecked,
131     )
132 }
133 
134 #[test]
test_ed25519_from_pkcs8()135 fn test_ed25519_from_pkcs8() {
136     test_ed25519_from_pkcs8_(FromPkcs8Variant::Checked, Ed25519KeyPair::from_pkcs8)
137 }
138 
test_ed25519_from_pkcs8_( variant: FromPkcs8Variant, f: impl Fn(&[u8]) -> Result<Ed25519KeyPair, error::KeyRejected>, )139 fn test_ed25519_from_pkcs8_(
140     variant: FromPkcs8Variant,
141     f: impl Fn(&[u8]) -> Result<Ed25519KeyPair, error::KeyRejected>,
142 ) {
143     // Just test that we can parse the input.
144     test::run(
145         test_file!("ed25519_from_pkcs8_tests.txt"),
146         |section, test_case| {
147             assert_eq!(section, "");
148             let input = test_case.consume_bytes("Input");
149             let expected_error = {
150                 let expected_checked = test_case.consume_string("Result-Checked");
151                 let expected_maybe_unchecked = test_case.consume_string("Result-Maybe-Unchecked");
152                 let expected_result = match variant {
153                     FromPkcs8Variant::Checked => expected_checked,
154                     FromPkcs8Variant::MaybeUnchecked => expected_maybe_unchecked,
155                 };
156                 if expected_result == "OK" {
157                     None
158                 } else {
159                     Some(expected_result)
160                 }
161             };
162             let expected_public = {
163                 let expected_if_no_error = test_case.consume_optional_bytes("Public");
164                 if expected_error.is_none() {
165                     Some(expected_if_no_error.unwrap())
166                 } else {
167                     None
168                 }
169             };
170 
171             match f(&input) {
172                 Ok(keypair) => {
173                     assert_eq!(expected_error, None);
174                     assert_eq!(
175                         expected_public.as_deref(),
176                         Some(keypair.public_key().as_ref())
177                     );
178                 }
179                 Err(actual_error) => {
180                     assert_eq!(expected_error, Some(format!("{}", actual_error)));
181                     assert_eq!(expected_public, None);
182                 }
183             }
184 
185             Ok(())
186         },
187     );
188 }
189 
190 #[test]
ed25519_test_generate_pkcs8()191 fn ed25519_test_generate_pkcs8() {
192     let rng = rand::SystemRandom::new();
193     let generated = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
194     let generated = generated.as_ref();
195 
196     let _ronudtripped = signature::Ed25519KeyPair::from_pkcs8(generated).unwrap();
197 
198     // Regression test: Verify we're generating the correct encoding, as
199     // `Ed25519KeyPair::from_pkcs8` also accepts our old wrong encoding.
200     assert_eq!(generated.len(), 19 + 32 + 32);
201     assert_eq!(&generated[..2], &[0x30, 0x51]);
202 }
203 
204 #[test]
ed25519_test_public_key_coverage()205 fn ed25519_test_public_key_coverage() {
206     const PRIVATE_KEY: &[u8] = include_bytes!("ed25519_test_private_key.p8");
207     const PUBLIC_KEY: &[u8] = include_bytes!("ed25519_test_public_key.der");
208     const PUBLIC_KEY_DEBUG: &str =
209         "PublicKey(\"5809e9fef6dcec58f0f2e3b0d67e9880a11957e083ace85835c3b6c8fbaf6b7d\")";
210 
211     let key_pair = signature::Ed25519KeyPair::from_pkcs8(PRIVATE_KEY).unwrap();
212 
213     // Test `AsRef<[u8]>`
214     assert_eq!(key_pair.public_key().as_ref(), PUBLIC_KEY);
215 
216     // Test `Clone`.
217     #[allow(clippy::clone_on_copy)]
218     let _: <Ed25519KeyPair as KeyPair>::PublicKey = key_pair.public_key().clone();
219 
220     // Test `Copy`.
221     let _: <Ed25519KeyPair as KeyPair>::PublicKey = *key_pair.public_key();
222 
223     // Test `Debug`.
224     assert_eq!(PUBLIC_KEY_DEBUG, format!("{:?}", key_pair.public_key()));
225     assert_eq!(
226         format!(
227             "Ed25519KeyPair {{ public_key: {:?} }}",
228             key_pair.public_key()
229         ),
230         format!("{:?}", key_pair)
231     );
232 }
233