• 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 use ring::{
16     error,
17     signature::{self, Ed25519KeyPair, KeyPair},
18     test, test_file,
19 };
20 
21 /// Test vectors from BoringSSL.
22 #[test]
test_signature_ed25519()23 fn test_signature_ed25519() {
24     test::run(test_file!("ed25519_tests.txt"), |section, test_case| {
25         assert_eq!(section, "");
26         let seed = test_case.consume_bytes("SEED");
27         assert_eq!(32, seed.len());
28 
29         let public_key = test_case.consume_bytes("PUB");
30         assert_eq!(32, public_key.len());
31 
32         let msg = test_case.consume_bytes("MESSAGE");
33 
34         let expected_sig = test_case.consume_bytes("SIG");
35 
36         {
37             let key_pair = Ed25519KeyPair::from_seed_and_public_key(&seed, &public_key).unwrap();
38             let actual_sig = key_pair.sign(&msg);
39             assert_eq!(&expected_sig[..], actual_sig.as_ref());
40         }
41 
42         // Test PKCS#8 generation, parsing, and private-to-public calculations.
43         let rng = test::rand::FixedSliceRandom { bytes: &seed };
44         let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
45         let key_pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap();
46         assert_eq!(public_key, key_pair.public_key().as_ref());
47 
48         // Test Signature generation.
49         let actual_sig = key_pair.sign(&msg);
50         assert_eq!(&expected_sig[..], actual_sig.as_ref());
51 
52         // Test Signature verification.
53         test_signature_verification(&public_key, &msg, &expected_sig, Ok(()));
54 
55         let mut tampered_sig = expected_sig;
56         tampered_sig[0] ^= 1;
57 
58         test_signature_verification(&public_key, &msg, &tampered_sig, Err(error::Unspecified));
59 
60         Ok(())
61     });
62 }
63 
64 /// Test vectors from BoringSSL.
65 #[test]
test_signature_ed25519_verify()66 fn test_signature_ed25519_verify() {
67     test::run(
68         test_file!("ed25519_verify_tests.txt"),
69         |section, test_case| {
70             assert_eq!(section, "");
71 
72             let public_key = test_case.consume_bytes("PUB");
73             let msg = test_case.consume_bytes("MESSAGE");
74             let sig = test_case.consume_bytes("SIG");
75             let expected_result = match test_case.consume_string("Result").as_str() {
76                 "P" => Ok(()),
77                 "F" => Err(error::Unspecified),
78                 s => panic!("{:?} is not a valid result", s),
79             };
80             test_signature_verification(&public_key, &msg, &sig, expected_result);
81             Ok(())
82         },
83     );
84 }
85 
test_signature_verification( public_key: &[u8], msg: &[u8], sig: &[u8], expected_result: Result<(), error::Unspecified>, )86 fn test_signature_verification(
87     public_key: &[u8],
88     msg: &[u8],
89     sig: &[u8],
90     expected_result: Result<(), error::Unspecified>,
91 ) {
92     assert_eq!(
93         expected_result,
94         signature::UnparsedPublicKey::new(&signature::ED25519, public_key).verify(msg, sig)
95     );
96 }
97 
98 #[test]
test_ed25519_from_seed_and_public_key_misuse()99 fn test_ed25519_from_seed_and_public_key_misuse() {
100     const PRIVATE_KEY: &[u8] = include_bytes!("ed25519_test_private_key.bin");
101     const PUBLIC_KEY: &[u8] = include_bytes!("ed25519_test_public_key.bin");
102 
103     assert!(Ed25519KeyPair::from_seed_and_public_key(PRIVATE_KEY, PUBLIC_KEY).is_ok());
104 
105     // Truncated private key.
106     assert!(Ed25519KeyPair::from_seed_and_public_key(&PRIVATE_KEY[..31], PUBLIC_KEY).is_err());
107 
108     // Truncated public key.
109     assert!(Ed25519KeyPair::from_seed_and_public_key(PRIVATE_KEY, &PUBLIC_KEY[..31]).is_err());
110 
111     // Swapped public and private key.
112     assert!(Ed25519KeyPair::from_seed_and_public_key(PUBLIC_KEY, PRIVATE_KEY).is_err());
113 }
114 
115 #[test]
test_ed25519_from_pkcs8_unchecked()116 fn test_ed25519_from_pkcs8_unchecked() {
117     // Just test that we can parse the input.
118     test::run(
119         test_file!("ed25519_from_pkcs8_unchecked_tests.txt"),
120         |section, test_case| {
121             assert_eq!(section, "");
122             let input = test_case.consume_bytes("Input");
123             let error = test_case.consume_optional_string("Error");
124 
125             match (Ed25519KeyPair::from_pkcs8_maybe_unchecked(&input), error) {
126                 (Ok(_), None) => (),
127                 (Err(e), None) => panic!("Failed with error \"{}\", but expected to succeed", e),
128                 (Ok(_), Some(e)) => panic!("Succeeded, but expected error \"{}\"", e),
129                 (Err(actual), Some(expected)) => assert_eq!(actual.description_(), expected),
130             };
131 
132             Ok(())
133         },
134     );
135 }
136 
137 #[test]
test_ed25519_from_pkcs8()138 fn test_ed25519_from_pkcs8() {
139     // Just test that we can parse the input.
140     test::run(
141         test_file!("ed25519_from_pkcs8_tests.txt"),
142         |section, test_case| {
143             assert_eq!(section, "");
144             let input = test_case.consume_bytes("Input");
145             let error = test_case.consume_optional_string("Error");
146 
147             match (Ed25519KeyPair::from_pkcs8(&input), error) {
148                 (Ok(_), None) => (),
149                 (Err(e), None) => panic!("Failed with error \"{}\", but expected to succeed", e),
150                 (Ok(_), Some(e)) => panic!("Succeeded, but expected error \"{}\"", e),
151                 (Err(actual), Some(expected)) => assert_eq!(actual.description_(), expected),
152             };
153 
154             Ok(())
155         },
156     );
157 }
158 
159 #[test]
ed25519_test_public_key_coverage()160 fn ed25519_test_public_key_coverage() {
161     const PRIVATE_KEY: &[u8] = include_bytes!("ed25519_test_private_key.p8");
162     const PUBLIC_KEY: &[u8] = include_bytes!("ed25519_test_public_key.der");
163     const PUBLIC_KEY_DEBUG: &str =
164         "PublicKey(\"5809e9fef6dcec58f0f2e3b0d67e9880a11957e083ace85835c3b6c8fbaf6b7d\")";
165 
166     let key_pair = signature::Ed25519KeyPair::from_pkcs8(PRIVATE_KEY).unwrap();
167 
168     // Test `AsRef<[u8]>`
169     assert_eq!(key_pair.public_key().as_ref(), PUBLIC_KEY);
170 
171     // Test `Clone`.
172     #[allow(clippy::clone_on_copy)]
173     let _: <Ed25519KeyPair as KeyPair>::PublicKey = key_pair.public_key().clone();
174 
175     // Test `Copy`.
176     let _: <Ed25519KeyPair as KeyPair>::PublicKey = *key_pair.public_key();
177 
178     // Test `Debug`.
179     assert_eq!(PUBLIC_KEY_DEBUG, format!("{:?}", key_pair.public_key()));
180     assert_eq!(
181         format!(
182             "Ed25519KeyPair {{ public_key: {:?} }}",
183             key_pair.public_key()
184         ),
185         format!("{:?}", key_pair)
186     );
187 }
188