rsa_tests.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Copyright 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. #[cfg(feature = "alloc")]
  15. use ring::{
  16. error,
  17. io::der,
  18. rand,
  19. signature::{self, KeyPair},
  20. test, test_file,
  21. };
  22. use std::convert::TryFrom;
  23. #[cfg(all(target_arch = "wasm32", feature = "wasm32_c"))]
  24. use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};
  25. #[cfg(all(target_arch = "wasm32", feature = "wasm32_c"))]
  26. wasm_bindgen_test_configure!(run_in_browser);
  27. #[cfg(feature = "alloc")]
  28. #[test]
  29. #[cfg_attr(all(target_arch = "wasm32", feature = "wasm32_c"), wasm_bindgen_test)]
  30. fn rsa_from_pkcs8_test() {
  31. test::run(
  32. test_file!("rsa_from_pkcs8_tests.txt"),
  33. |section, test_case| {
  34. assert_eq!(section, "");
  35. let input = test_case.consume_bytes("Input");
  36. let error = test_case.consume_optional_string("Error");
  37. match (signature::RsaKeyPair::from_pkcs8(&input), error) {
  38. (Ok(_), None) => (),
  39. (Err(e), None) => panic!("Failed with error \"{}\", but expected to succeed", e),
  40. (Ok(_), Some(e)) => panic!("Succeeded, but expected error \"{}\"", e),
  41. (Err(actual), Some(expected)) => assert_eq!(format!("{}", actual), expected),
  42. };
  43. Ok(())
  44. },
  45. );
  46. }
  47. #[cfg(feature = "alloc")]
  48. #[test]
  49. #[cfg_attr(all(target_arch = "wasm32", feature = "wasm32_c"), wasm_bindgen_test)]
  50. fn test_signature_rsa_pkcs1_sign() {
  51. let rng = rand::SystemRandom::new();
  52. test::run(
  53. test_file!("rsa_pkcs1_sign_tests.txt"),
  54. |section, test_case| {
  55. assert_eq!(section, "");
  56. let digest_name = test_case.consume_string("Digest");
  57. let alg = match digest_name.as_ref() {
  58. "SHA256" => &signature::RSA_PKCS1_SHA256,
  59. "SHA384" => &signature::RSA_PKCS1_SHA384,
  60. "SHA512" => &signature::RSA_PKCS1_SHA512,
  61. _ => panic!("Unsupported digest: {}", digest_name),
  62. };
  63. let private_key = test_case.consume_bytes("Key");
  64. let msg = test_case.consume_bytes("Msg");
  65. let expected = test_case.consume_bytes("Sig");
  66. let result = test_case.consume_string("Result");
  67. let key_pair = signature::RsaKeyPair::from_der(&private_key);
  68. if result == "Fail-Invalid-Key" {
  69. assert!(key_pair.is_err());
  70. return Ok(());
  71. }
  72. let key_pair = key_pair.unwrap();
  73. // XXX: This test is too slow on Android ARM Travis CI builds.
  74. // TODO: re-enable these tests on Android ARM.
  75. let mut actual = vec![0u8; key_pair.public_modulus_len()];
  76. key_pair
  77. .sign(alg, &rng, &msg, actual.as_mut_slice())
  78. .unwrap();
  79. assert_eq!(actual.as_slice() == &expected[..], result == "Pass");
  80. Ok(())
  81. },
  82. );
  83. }
  84. #[cfg(feature = "alloc")]
  85. #[test]
  86. #[cfg_attr(all(target_arch = "wasm32", feature = "wasm32_c"), wasm_bindgen_test)]
  87. fn test_signature_rsa_pss_sign() {
  88. test::run(
  89. test_file!("rsa_pss_sign_tests.txt"),
  90. |section, test_case| {
  91. assert_eq!(section, "");
  92. let digest_name = test_case.consume_string("Digest");
  93. let alg = match digest_name.as_ref() {
  94. "SHA256" => &signature::RSA_PSS_SHA256,
  95. "SHA384" => &signature::RSA_PSS_SHA384,
  96. "SHA512" => &signature::RSA_PSS_SHA512,
  97. _ => panic!("Unsupported digest: {}", digest_name),
  98. };
  99. let result = test_case.consume_string("Result");
  100. let private_key = test_case.consume_bytes("Key");
  101. let key_pair = signature::RsaKeyPair::from_der(&private_key);
  102. if key_pair.is_err() && result == "Fail-Invalid-Key" {
  103. return Ok(());
  104. }
  105. let key_pair = key_pair.unwrap();
  106. let msg = test_case.consume_bytes("Msg");
  107. let salt = test_case.consume_bytes("Salt");
  108. let expected = test_case.consume_bytes("Sig");
  109. let rng = test::rand::FixedSliceRandom { bytes: &salt };
  110. let mut actual = vec![0u8; key_pair.public_modulus_len()];
  111. key_pair.sign(alg, &rng, &msg, actual.as_mut_slice())?;
  112. assert_eq!(actual.as_slice() == &expected[..], result == "Pass");
  113. Ok(())
  114. },
  115. );
  116. }
  117. #[cfg(feature = "alloc")]
  118. #[test]
  119. #[cfg_attr(all(target_arch = "wasm32", feature = "wasm32_c"), wasm_bindgen_test)]
  120. fn test_signature_rsa_pkcs1_verify() {
  121. let sha1_params = &[
  122. (
  123. &signature::RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
  124. 1024,
  125. ),
  126. (
  127. &signature::RSA_PKCS1_2048_8192_SHA1_FOR_LEGACY_USE_ONLY,
  128. 2048,
  129. ),
  130. ];
  131. let sha256_params = &[
  132. (
  133. &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY,
  134. 1024,
  135. ),
  136. (&signature::RSA_PKCS1_2048_8192_SHA256, 2048),
  137. ];
  138. let sha384_params = &[
  139. (&signature::RSA_PKCS1_2048_8192_SHA384, 2048),
  140. (&signature::RSA_PKCS1_3072_8192_SHA384, 3072),
  141. ];
  142. let sha512_params = &[
  143. (
  144. &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY,
  145. 1024,
  146. ),
  147. (&signature::RSA_PKCS1_2048_8192_SHA512, 2048),
  148. ];
  149. test::run(
  150. test_file!("rsa_pkcs1_verify_tests.txt"),
  151. |section, test_case| {
  152. assert_eq!(section, "");
  153. let digest_name = test_case.consume_string("Digest");
  154. let params: &[_] = match digest_name.as_ref() {
  155. "SHA1" => sha1_params,
  156. "SHA256" => sha256_params,
  157. "SHA384" => sha384_params,
  158. "SHA512" => sha512_params,
  159. _ => panic!("Unsupported digest: {}", digest_name),
  160. };
  161. let public_key = test_case.consume_bytes("Key");
  162. // Sanity check that we correctly DER-encoded the originally-
  163. // provided separate (n, e) components. When we add test vectors
  164. // for improperly-encoded signatures, we'll have to revisit this.
  165. let key_bits = untrusted::Input::from(&public_key)
  166. .read_all(error::Unspecified, |input| {
  167. der::nested(input, der::Tag::Sequence, error::Unspecified, |input| {
  168. let n_bytes =
  169. der::positive_integer(input)?.big_endian_without_leading_zero();
  170. let _e = der::positive_integer(input)?;
  171. // Because `n_bytes` has the leading zeros stripped and is big-endian, there
  172. // must be less than 8 leading zero bits.
  173. let n_leading_zeros = usize::try_from(n_bytes[0].leading_zeros()).unwrap();
  174. assert!(n_leading_zeros < 8);
  175. Ok((n_bytes.len() * 8) - n_leading_zeros)
  176. })
  177. })
  178. .expect("invalid DER");
  179. let msg = test_case.consume_bytes("Msg");
  180. let sig = test_case.consume_bytes("Sig");
  181. let is_valid = test_case.consume_string("Result") == "P";
  182. for &(alg, min_bits) in params {
  183. let width_ok = key_bits >= min_bits;
  184. let actual_result =
  185. signature::UnparsedPublicKey::new(alg, &public_key).verify(&msg, &sig);
  186. assert_eq!(actual_result.is_ok(), is_valid && width_ok);
  187. }
  188. Ok(())
  189. },
  190. );
  191. }
  192. #[cfg(feature = "alloc")]
  193. #[test]
  194. #[cfg_attr(all(target_arch = "wasm32", feature = "wasm32_c"), wasm_bindgen_test)]
  195. fn test_signature_rsa_pss_verify() {
  196. test::run(
  197. test_file!("rsa_pss_verify_tests.txt"),
  198. |section, test_case| {
  199. assert_eq!(section, "");
  200. let digest_name = test_case.consume_string("Digest");
  201. let alg = match digest_name.as_ref() {
  202. "SHA256" => &signature::RSA_PSS_2048_8192_SHA256,
  203. "SHA384" => &signature::RSA_PSS_2048_8192_SHA384,
  204. "SHA512" => &signature::RSA_PSS_2048_8192_SHA512,
  205. _ => panic!("Unsupported digest: {}", digest_name),
  206. };
  207. let public_key = test_case.consume_bytes("Key");
  208. // Sanity check that we correctly DER-encoded the originally-
  209. // provided separate (n, e) components. When we add test vectors
  210. // for improperly-encoded signatures, we'll have to revisit this.
  211. assert!(untrusted::Input::from(&public_key)
  212. .read_all(error::Unspecified, |input| der::nested(
  213. input,
  214. der::Tag::Sequence,
  215. error::Unspecified,
  216. |input| {
  217. let _ = der::positive_integer(input)?;
  218. let _ = der::positive_integer(input)?;
  219. Ok(())
  220. }
  221. ))
  222. .is_ok());
  223. let msg = test_case.consume_bytes("Msg");
  224. let sig = test_case.consume_bytes("Sig");
  225. let is_valid = test_case.consume_string("Result") == "P";
  226. let actual_result =
  227. signature::UnparsedPublicKey::new(alg, &public_key).verify(&msg, &sig);
  228. assert_eq!(actual_result.is_ok(), is_valid);
  229. Ok(())
  230. },
  231. );
  232. }
  233. // Test for `primitive::verify()`. Read public key parts from a file
  234. // and use them to verify a signature.
  235. #[cfg(feature = "alloc")]
  236. #[test]
  237. #[cfg_attr(all(target_arch = "wasm32", feature = "wasm32_c"), wasm_bindgen_test)]
  238. fn test_signature_rsa_primitive_verification() {
  239. test::run(
  240. test_file!("rsa_primitive_verify_tests.txt"),
  241. |section, test_case| {
  242. assert_eq!(section, "");
  243. let n = test_case.consume_bytes("n");
  244. let e = test_case.consume_bytes("e");
  245. let msg = test_case.consume_bytes("Msg");
  246. let sig = test_case.consume_bytes("Sig");
  247. let expected = test_case.consume_string("Result");
  248. let public_key = signature::RsaPublicKeyComponents { n: &n, e: &e };
  249. let result = public_key.verify(&signature::RSA_PKCS1_2048_8192_SHA256, &msg, &sig);
  250. assert_eq!(result.is_ok(), expected == "Pass");
  251. Ok(())
  252. },
  253. )
  254. }
  255. #[cfg(feature = "alloc")]
  256. #[test]
  257. #[cfg_attr(all(target_arch = "wasm32", feature = "wasm32_c"), wasm_bindgen_test)]
  258. fn rsa_test_public_key_coverage() {
  259. const PRIVATE_KEY: &[u8] = include_bytes!("rsa_test_private_key_2048.p8");
  260. const PUBLIC_KEY: &[u8] = include_bytes!("rsa_test_public_key_2048.der");
  261. const PUBLIC_KEY_DEBUG: &str = include_str!("rsa_test_public_key_2048_debug.txt");
  262. let key_pair = signature::RsaKeyPair::from_pkcs8(PRIVATE_KEY).unwrap();
  263. // Test `AsRef<[u8]>`
  264. assert_eq!(key_pair.public_key().as_ref(), PUBLIC_KEY);
  265. // Test `Clone`.
  266. let _ = key_pair.public_key().clone();
  267. // Test `exponent()`.
  268. assert_eq!(
  269. &[0x01, 0x00, 0x01],
  270. key_pair
  271. .public_key()
  272. .exponent()
  273. .big_endian_without_leading_zero()
  274. );
  275. // Test `Debug`
  276. assert_eq!(PUBLIC_KEY_DEBUG, format!("{:?}", key_pair.public_key()));
  277. assert_eq!(
  278. format!("RsaKeyPair {{ public_key: {:?} }}", key_pair.public_key()),
  279. format!("{:?}", key_pair)
  280. );
  281. }