Project import generated by Copybara.
GitOrigin-RevId: b6ca065e6fc9504c3ff07067ef2da184afaf0c78
Change-Id: Ie3b3a5835bf622e679fd21e0a9149dd85da59aca
diff --git a/nearby/crypto/crypto_provider/src/hkdf.rs b/nearby/crypto/crypto_provider/src/hkdf.rs
index dab4e13..c905302 100644
--- a/nearby/crypto/crypto_provider/src/hkdf.rs
+++ b/nearby/crypto/crypto_provider/src/hkdf.rs
@@ -33,3 +33,292 @@
/// an invalid length
#[derive(Debug)]
pub struct InvalidLength;
+
+/// Test cases exported for testing specific hkdf implementations
+#[cfg(feature = "testing")]
+pub mod testing {
+ extern crate alloc;
+ use crate::hkdf::Hkdf;
+ pub use crate::testing::prelude::*;
+ use crate::CryptoProvider;
+ use alloc::vec;
+ use alloc::vec::Vec;
+ use core::iter;
+ use core::marker::PhantomData;
+ use hex_literal::hex;
+ use rstest_reuse::template;
+
+ /// Generates the test cases to validate the hkdf implementation.
+ /// For example, to test `MyCryptoProvider`:
+ ///
+ /// ```
+ /// mod tests {
+ /// use std::marker::PhantomData;
+ /// use crypto_provider::testing::CryptoProviderTestCase;
+ /// #[apply(hkdf_test_cases)]
+ /// fn hkdf_tests(testcase: CryptoProviderTestCase<MyCryptoProvider>){
+ /// testcase(PhantomData::<MyCryptoProvider>);
+ /// }
+ /// }
+ /// ```
+ #[template]
+ #[export]
+ #[rstest]
+ #[case::basic_test_hkdf(basic_test_hkdf)]
+ #[case::test_rfc5869_sha256(test_rfc5869_sha256)]
+ #[case::test_lengths(test_lengths)]
+ #[case::test_max_length(test_max_length)]
+ #[case::test_max_length_exceeded(test_max_length_exceeded)]
+ #[case::test_unsupported_length(test_unsupported_length)]
+ #[case::test_expand_multi_info(test_expand_multi_info)]
+ #[case::run_hkdf_sha256_vectors(run_hkdf_sha256_vectors)]
+ #[case::run_hkdf_sha512_vectors(run_hkdf_sha512_vectors)]
+ fn hkdf_test_cases<C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>) {}
+
+ const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160
+
+ ///
+ pub struct Test<'a> {
+ ikm: &'a [u8],
+ salt: &'a [u8],
+ info: &'a [u8],
+ okm: &'a [u8],
+ }
+
+ /// data taken from sample code in Readme of crates.io page
+ pub fn basic_test_hkdf<C: CryptoProvider>(_: PhantomData<C>) {
+ let ikm = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
+ let salt = hex!("000102030405060708090a0b0c");
+ let info = hex!("f0f1f2f3f4f5f6f7f8f9");
+
+ let hk = C::HkdfSha256::new(Some(&salt[..]), &ikm);
+ let mut okm = [0u8; 42];
+ hk.expand(&info, &mut okm)
+ .expect("42 is a valid length for Sha256 to output");
+
+ let expected = hex!(
+ "
+ 3cb25f25faacd57a90434f64d0362f2a
+ 2d2d0a90cf1a5a4c5db02d56ecc4c5bf
+ 34007208d5b887185865
+ "
+ );
+ assert_eq!(okm, expected);
+ }
+
+ // Test Vectors from https://tools.ietf.org/html/rfc5869.
+ #[rustfmt::skip]
+ ///
+ pub fn test_rfc5869_sha256<C: CryptoProvider>(_: PhantomData<C>) {
+ let tests = [
+ Test {
+ // Test Case 1
+ ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
+ salt: &hex!("000102030405060708090a0b0c"),
+ info: &hex!("f0f1f2f3f4f5f6f7f8f9"),
+ okm: &hex!("
+ 3cb25f25faacd57a90434f64d0362f2a
+ 2d2d0a90cf1a5a4c5db02d56ecc4c5bf
+ 34007208d5b887185865
+ "),
+ },
+ Test {
+ // Test Case 2
+ ikm: &hex!("
+ 000102030405060708090a0b0c0d0e0f
+ 101112131415161718191a1b1c1d1e1f
+ 202122232425262728292a2b2c2d2e2f
+ 303132333435363738393a3b3c3d3e3f
+ 404142434445464748494a4b4c4d4e4f
+ "),
+ salt: &hex!("
+ 606162636465666768696a6b6c6d6e6f
+ 707172737475767778797a7b7c7d7e7f
+ 808182838485868788898a8b8c8d8e8f
+ 909192939495969798999a9b9c9d9e9f
+ a0a1a2a3a4a5a6a7a8a9aaabacadaeaf
+ "),
+ info: &hex!("
+ b0b1b2b3b4b5b6b7b8b9babbbcbdbebf
+ c0c1c2c3c4c5c6c7c8c9cacbcccdcecf
+ d0d1d2d3d4d5d6d7d8d9dadbdcdddedf
+ e0e1e2e3e4e5e6e7e8e9eaebecedeeef
+ f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
+ "),
+ okm: &hex!("
+ b11e398dc80327a1c8e7f78c596a4934
+ 4f012eda2d4efad8a050cc4c19afa97c
+ 59045a99cac7827271cb41c65e590e09
+ da3275600c2f09b8367793a9aca3db71
+ cc30c58179ec3e87c14c01d5c1f3434f
+ 1d87
+ "),
+ },
+ Test {
+ // Test Case 3
+ ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
+ salt: &hex!(""),
+ info: &hex!(""),
+ okm: &hex!("
+ 8da4e775a563c18f715f802a063c5a31
+ b8a11f5c5ee1879ec3454e5f3c738d2d
+ 9d201395faa4b61a96c8
+ "),
+ },
+ ];
+ for Test { ikm, salt, info, okm } in tests.iter() {
+ let salt = if salt.is_empty() {
+ None
+ } else {
+ Some(&salt[..])
+ };
+ let hkdf = C::HkdfSha256::new(salt, ikm);
+ let mut okm2 = vec![0u8; okm.len()];
+ assert!(hkdf.expand(&info[..], &mut okm2).is_ok());
+ assert_eq!(okm2[..], okm[..]);
+ }
+ }
+
+ ///
+ pub fn test_lengths<C: CryptoProvider>(_: PhantomData<C>) {
+ let hkdf = C::HkdfSha256::new(None, &[]);
+ let mut longest = vec![0u8; MAX_SHA256_LENGTH];
+ assert!(hkdf.expand(&[], &mut longest).is_ok());
+ // Runtime is O(length), so exhaustively testing all legal lengths
+ // would take too long (at least without --release). Only test a
+ // subset: the first 500, the last 10, and every 100th in between.
+ // 0 is an invalid key length for openssl, so start at 1
+ let lengths = (1..MAX_SHA256_LENGTH + 1)
+ .filter(|&len| !(500..=MAX_SHA256_LENGTH - 10).contains(&len) || len % 100 == 0);
+
+ for length in lengths {
+ let mut okm = vec![0u8; length];
+
+ assert!(hkdf.expand(&[], &mut okm).is_ok());
+ assert_eq!(okm.len(), length);
+ assert_eq!(okm[..], longest[..length]);
+ }
+ }
+
+ ///
+ pub fn test_max_length<C: CryptoProvider>(_: PhantomData<C>) {
+ let hkdf = C::HkdfSha256::new(Some(&[]), &[]);
+ let mut okm = vec![0u8; MAX_SHA256_LENGTH];
+ assert!(hkdf.expand(&[], &mut okm).is_ok());
+ }
+
+ ///
+ pub fn test_max_length_exceeded<C: CryptoProvider>(_: PhantomData<C>) {
+ let hkdf = C::HkdfSha256::new(Some(&[]), &[]);
+ let mut okm = vec![0u8; MAX_SHA256_LENGTH + 1];
+ assert!(hkdf.expand(&[], &mut okm).is_err());
+ }
+
+ ///
+ pub fn test_unsupported_length<C: CryptoProvider>(_: PhantomData<C>) {
+ let hkdf = C::HkdfSha256::new(Some(&[]), &[]);
+ let mut okm = vec![0u8; 90000];
+ assert!(hkdf.expand(&[], &mut okm).is_err());
+ }
+
+ ///
+ pub fn test_expand_multi_info<C: CryptoProvider>(_: PhantomData<C>) {
+ let info_components = &[
+ &b"09090909090909090909090909090909090909090909"[..],
+ &b"8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a"[..],
+ &b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"[..],
+ &b"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4"[..],
+ &b"1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d"[..],
+ ];
+
+ let hkdf = C::HkdfSha256::new(None, b"some ikm here");
+
+ // Compute HKDF-Expand on the concatenation of all the info components
+ let mut oneshot_res = [0u8; 16];
+ hkdf.expand(&info_components.concat(), &mut oneshot_res)
+ .unwrap();
+
+ // Now iteratively join the components of info_components until it's all 1 component. The value
+ // of HKDF-Expand should be the same throughout
+ let mut num_concatted = 0;
+ let mut info_head = Vec::new();
+
+ while num_concatted < info_components.len() {
+ info_head.extend(info_components[num_concatted]);
+
+ // Build the new input to be the info head followed by the remaining components
+ let input: Vec<&[u8]> = iter::once(info_head.as_slice())
+ .chain(info_components.iter().cloned().skip(num_concatted + 1))
+ .collect();
+
+ // Compute and compare to the one-shot answer
+ let mut multipart_res = [0u8; 16];
+ hkdf.expand_multi_info(&input, &mut multipart_res).unwrap();
+ assert_eq!(multipart_res, oneshot_res);
+ num_concatted += 1;
+ }
+ }
+
+ ///
+ pub fn run_hkdf_sha256_vectors<C: CryptoProvider>(_: PhantomData<C>) {
+ run_hkdf_test_vectors::<C::HkdfSha256>(HashAlg::Sha256)
+ }
+
+ ///
+ pub fn run_hkdf_sha512_vectors<C: CryptoProvider>(_: PhantomData<C>) {
+ run_hkdf_test_vectors::<C::HkdfSha512>(HashAlg::Sha512)
+ }
+
+ enum HashAlg {
+ Sha256,
+ Sha512,
+ }
+
+ ///
+ fn run_hkdf_test_vectors<K: Hkdf>(hash: HashAlg) {
+ let test_name = match hash {
+ HashAlg::Sha256 => wycheproof::hkdf::TestName::HkdfSha256,
+ HashAlg::Sha512 => wycheproof::hkdf::TestName::HkdfSha512,
+ };
+
+ let test_set =
+ wycheproof::hkdf::TestSet::load(test_name).expect("should be able to load test set");
+ for test_group in test_set.test_groups {
+ for test in test_group.tests {
+ let ikm = test.ikm;
+ let salt = test.salt;
+ let info = test.info;
+ let okm = test.okm;
+ let tc_id = test.tc_id;
+ if let Some(desc) = run_test::<K>(
+ ikm.as_slice(),
+ salt.as_slice(),
+ info.as_slice(),
+ okm.as_slice(),
+ ) {
+ panic!(
+ "\n\
+ Failed test {tc_id}: {desc}\n\
+ ikm:\t{ikm:?}\n\
+ salt:\t{salt:?}\n\
+ info:\t{info:?}\n\
+ okm:\t{okm:?}\n"
+ );
+ }
+ }
+ }
+ }
+
+ fn run_test<K: Hkdf>(ikm: &[u8], salt: &[u8], info: &[u8], okm: &[u8]) -> Option<&'static str> {
+ let prk = K::new(Some(salt), ikm);
+ let mut got_okm = vec![0; okm.len()];
+
+ if prk.expand(info, &mut got_okm).is_err() {
+ return Some("prk expand");
+ }
+ if got_okm != okm {
+ return Some("mismatch in okm");
+ }
+ None
+ }
+}
diff --git a/nearby/crypto/crypto_provider/src/hmac.rs b/nearby/crypto/crypto_provider/src/hmac.rs
index c5a9ae1..40be189 100644
--- a/nearby/crypto/crypto_provider/src/hmac.rs
+++ b/nearby/crypto/crypto_provider/src/hmac.rs
@@ -44,3 +44,125 @@
/// Error output when the provided key material length is invalid
#[derive(Debug)]
pub struct InvalidLength;
+
+/// Test cases exported for testing specific hmac implementations
+#[cfg(feature = "testing")]
+pub mod testing {
+ use crate::hmac::Hmac;
+ use crate::rstest_reuse::template;
+ pub use crate::testing::prelude::*;
+ use crate::CryptoProvider;
+ use core::cmp::min;
+ use core::marker::PhantomData;
+ use wycheproof::TestResult;
+
+ /// Generates the test cases to validate the hmac implementation.
+ /// For example, to test `MyCryptoProvider`:
+ ///
+ /// ```
+ /// mod tests {
+ /// use std::marker::PhantomData;
+ /// use crypto_provider::testing::CryptoProviderTestCase;
+ /// #[apply(hmac_test_cases)]
+ /// fn hmac_tests(testcase: CryptoProviderTestCase<MyCryptoProvider>){
+ /// testcase(PhantomData::<MyCryptoProvider>);
+ /// }
+ /// }
+ /// ```
+ #[template]
+ #[export]
+ #[rstest]
+ #[case::hmac_sha256_test_vectors(hmac_sha256_test_vectors)]
+ #[case::hmac_sha512_test_vectors(hmac_sha512_test_vectors)]
+ fn hmac_test_cases<C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>) {}
+
+ /// Run wycheproof hmac sha256 test vectors on provided CryptoProvider
+ pub fn hmac_sha256_test_vectors<C: CryptoProvider>(_: PhantomData<C>) {
+ run_hmac_test_vectors::<32, C::HmacSha256>(HashAlg::Sha256)
+ }
+
+ /// Run wycheproof hmac sha512 test vectors on provided CryptoProvider
+ pub fn hmac_sha512_test_vectors<C: CryptoProvider>(_: PhantomData<C>) {
+ run_hmac_test_vectors::<64, C::HmacSha512>(HashAlg::Sha512)
+ }
+
+ enum HashAlg {
+ Sha256,
+ Sha512,
+ }
+
+ // Tests vectors from Project Wycheproof:
+ // https://github.com/google/wycheproof
+ fn run_hmac_test_vectors<const N: usize, H: Hmac<N>>(hash: HashAlg) {
+ let test_name = match hash {
+ HashAlg::Sha256 => wycheproof::mac::TestName::HmacSha256,
+ HashAlg::Sha512 => wycheproof::mac::TestName::HmacSha512,
+ };
+ let test_set =
+ wycheproof::mac::TestSet::load(test_name).expect("should be able to load test set");
+
+ for test_group in test_set.test_groups {
+ for test in test_group.tests {
+ let key = test.key;
+ let msg = test.msg;
+ let tag = test.tag;
+ let tc_id = test.tc_id;
+ let valid = match test.result {
+ TestResult::Valid | TestResult::Acceptable => true,
+ TestResult::Invalid => false,
+ };
+
+ if let Some(desc) =
+ run_test::<N, H>(key.as_slice(), msg.as_slice(), tag.as_slice(), valid)
+ {
+ panic!(
+ "\n\
+ Failed test {tc_id}: {desc}\n\
+ key:\t{key:?}\n\
+ msg:\t{msg:?}\n\
+ tag:\t{tag:?}\n",
+ );
+ }
+ }
+ }
+ }
+
+ fn run_test<const N: usize, H: Hmac<N>>(
+ key: &[u8],
+ input: &[u8],
+ tag: &[u8],
+ valid_data: bool,
+ ) -> Option<&'static str> {
+ let mut mac = H::new_from_slice(key).unwrap();
+ mac.update(input);
+ let result = mac.finalize();
+ let n = tag.len();
+ let result_bytes = &result[..n];
+
+ if valid_data {
+ if result_bytes != tag {
+ return Some("whole message");
+ }
+ } else {
+ return if result_bytes == tag {
+ Some("invalid should not match")
+ } else {
+ None
+ };
+ }
+
+ // test reading different chunk sizes
+ for chunk_size in 1..min(64, input.len()) {
+ let mut mac = H::new_from_slice(key).unwrap();
+ for chunk in input.chunks(chunk_size) {
+ mac.update(chunk);
+ }
+ let res = mac.verify_truncated_left(tag);
+ if res.is_err() {
+ return Some("chunked message");
+ }
+ }
+
+ None
+ }
+}
diff --git a/nearby/crypto/crypto_provider/src/lib.rs b/nearby/crypto/crypto_provider/src/lib.rs
index e9ce8b8..a61370c 100644
--- a/nearby/crypto/crypto_provider/src/lib.rs
+++ b/nearby/crypto/crypto_provider/src/lib.rs
@@ -46,11 +46,11 @@
/// Uber crypto trait which defines the traits for all crypto primitives as associated types
pub trait CryptoProvider: Clone + Debug + PartialEq + Eq + Send {
/// The Hkdf type which implements the hkdf trait
- type HkdfSha256: hkdf::Hkdf + Clone;
+ type HkdfSha256: hkdf::Hkdf;
/// The Hmac type which implements the hmac trait
type HmacSha256: hmac::Hmac<32>;
/// The Hkdf type which implements the hkdf trait
- type HkdfSha512: hkdf::Hkdf + Clone;
+ type HkdfSha512: hkdf::Hkdf;
/// The Hmac type which implements the hmac trait
type HmacSha512: hmac::Hmac<64>;
/// The AES-CBC-PKCS7 implementation to use
diff --git a/nearby/crypto/crypto_provider/tests/hkdf_tests.rs b/nearby/crypto/crypto_provider/tests/hkdf_tests.rs
deleted file mode 100644
index 72d8dcc..0000000
--- a/nearby/crypto/crypto_provider/tests/hkdf_tests.rs
+++ /dev/null
@@ -1,345 +0,0 @@
-// Copyright 2022 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-/// Tests for both openssl and rust-crypto crypto_provider impls
-use crypto_provider::hkdf::Hkdf as _;
-use crypto_provider::CryptoProvider;
-use crypto_provider_openssl::Openssl;
-use crypto_provider_rustcrypto::RustCrypto;
-use hex_literal::hex;
-use std::iter;
-
-struct Test<'a> {
- ikm: &'a [u8],
- salt: &'a [u8],
- info: &'a [u8],
- okm: &'a [u8],
-}
-
-#[test]
-fn basic_test_rc() {
- basic_test_hkdf::<RustCrypto>();
-}
-
-#[test]
-fn basic_test_openssl() {
- basic_test_hkdf::<Openssl>();
-}
-
-/// data taken from sample code in Readme of crates.io page
-fn basic_test_hkdf<C: CryptoProvider>() {
- let ikm = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
- let salt = hex!("000102030405060708090a0b0c");
- let info = hex!("f0f1f2f3f4f5f6f7f8f9");
-
- let hk = C::HkdfSha256::new(Some(&salt[..]), &ikm);
- let mut okm = [0u8; 42];
- hk.expand(&info, &mut okm)
- .expect("42 is a valid length for Sha256 to output");
-
- let expected = hex!(
- "
- 3cb25f25faacd57a90434f64d0362f2a
- 2d2d0a90cf1a5a4c5db02d56ecc4c5bf
- 34007208d5b887185865
- "
- );
- assert_eq!(okm, expected);
-}
-
-#[test]
-fn rfc5869_sha256_rc() {
- test_rfc5869_sha256::<RustCrypto>();
-}
-
-#[test]
-fn rfc5869_sha256_openssl() {
- test_rfc5869_sha256::<Openssl>();
-}
-
-// Test Vectors from https://tools.ietf.org/html/rfc5869.
-#[rustfmt::skip]
-fn test_rfc5869_sha256<C: CryptoProvider>() {
- let tests = [
- Test {
- // Test Case 1
- ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
- salt: &hex!("000102030405060708090a0b0c"),
- info: &hex!("f0f1f2f3f4f5f6f7f8f9"),
- okm: &hex!("
- 3cb25f25faacd57a90434f64d0362f2a
- 2d2d0a90cf1a5a4c5db02d56ecc4c5bf
- 34007208d5b887185865
- "),
- },
- Test {
- // Test Case 2
- ikm: &hex!("
- 000102030405060708090a0b0c0d0e0f
- 101112131415161718191a1b1c1d1e1f
- 202122232425262728292a2b2c2d2e2f
- 303132333435363738393a3b3c3d3e3f
- 404142434445464748494a4b4c4d4e4f
- "),
- salt: &hex!("
- 606162636465666768696a6b6c6d6e6f
- 707172737475767778797a7b7c7d7e7f
- 808182838485868788898a8b8c8d8e8f
- 909192939495969798999a9b9c9d9e9f
- a0a1a2a3a4a5a6a7a8a9aaabacadaeaf
- "),
- info: &hex!("
- b0b1b2b3b4b5b6b7b8b9babbbcbdbebf
- c0c1c2c3c4c5c6c7c8c9cacbcccdcecf
- d0d1d2d3d4d5d6d7d8d9dadbdcdddedf
- e0e1e2e3e4e5e6e7e8e9eaebecedeeef
- f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
- "),
- okm: &hex!("
- b11e398dc80327a1c8e7f78c596a4934
- 4f012eda2d4efad8a050cc4c19afa97c
- 59045a99cac7827271cb41c65e590e09
- da3275600c2f09b8367793a9aca3db71
- cc30c58179ec3e87c14c01d5c1f3434f
- 1d87
- "),
- },
- Test {
- // Test Case 3
- ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
- salt: &hex!(""),
- info: &hex!(""),
- okm: &hex!("
- 8da4e775a563c18f715f802a063c5a31
- b8a11f5c5ee1879ec3454e5f3c738d2d
- 9d201395faa4b61a96c8
- "),
- },
- ];
- for Test { ikm, salt, info, okm } in tests.iter() {
- let salt = if salt.is_empty() {
- None
- } else {
- Some(&salt[..])
- };
- let hkdf = C::HkdfSha256::new(salt, ikm);
- let mut okm2 = vec![0u8; okm.len()];
- assert!(hkdf.expand(&info[..], &mut okm2).is_ok());
- assert_eq!(okm2[..], okm[..]);
- }
-}
-
-const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160
-
-#[test]
-fn lengths_rc() {
- test_lengths::<RustCrypto>()
-}
-
-#[test]
-fn lengths_openssl() {
- test_lengths::<Openssl>()
-}
-
-fn test_lengths<C: CryptoProvider>() {
- let hkdf = C::HkdfSha256::new(None, &[]);
- let mut longest = vec![0u8; MAX_SHA256_LENGTH];
- assert!(hkdf.expand(&[], &mut longest).is_ok());
- // Runtime is O(length), so exhaustively testing all legal lengths
- // would take too long (at least without --release). Only test a
- // subset: the first 500, the last 10, and every 100th in between.
- // 0 is an invalid key length for openssl, so start at 1
- let lengths = (1..MAX_SHA256_LENGTH + 1)
- .filter(|&len| !(500..=MAX_SHA256_LENGTH - 10).contains(&len) || len % 100 == 0);
-
- for length in lengths {
- let mut okm = vec![0u8; length];
-
- assert!(hkdf.expand(&[], &mut okm).is_ok());
- assert_eq!(okm.len(), length);
- assert_eq!(okm[..], longest[..length]);
- }
-}
-
-#[test]
-fn max_length_rc() {
- test_max_length::<RustCrypto>();
-}
-
-#[test]
-fn max_length_openssl() {
- test_max_length::<Openssl>();
-}
-
-fn test_max_length<C: CryptoProvider>() {
- let hkdf = C::HkdfSha256::new(Some(&[]), &[]);
- let mut okm = vec![0u8; MAX_SHA256_LENGTH];
- assert!(hkdf.expand(&[], &mut okm).is_ok());
-}
-
-#[test]
-fn max_length_exceeded_rc() {
- test_max_length_exceeded::<RustCrypto>();
-}
-
-#[test]
-fn max_length_exceeded_openssl() {
- test_max_length_exceeded::<Openssl>();
-}
-
-fn test_max_length_exceeded<C: CryptoProvider>() {
- let hkdf = C::HkdfSha256::new(Some(&[]), &[]);
- let mut okm = vec![0u8; MAX_SHA256_LENGTH + 1];
- assert!(hkdf.expand(&[], &mut okm).is_err());
-}
-
-#[test]
-fn unsupported_length_rc() {
- test_unsupported_length::<RustCrypto>();
-}
-
-#[test]
-fn unsupported_length_openssl() {
- test_unsupported_length::<Openssl>();
-}
-
-fn test_unsupported_length<C: CryptoProvider>() {
- let hkdf = C::HkdfSha256::new(Some(&[]), &[]);
- let mut okm = vec![0u8; 90000];
- assert!(hkdf.expand(&[], &mut okm).is_err());
-}
-
-#[test]
-fn expand_multi_info_rc() {
- test_expand_multi_info::<RustCrypto>();
-}
-
-#[test]
-fn expand_multi_info_openssl() {
- test_expand_multi_info::<Openssl>();
-}
-
-fn test_expand_multi_info<C: CryptoProvider>() {
- let info_components = &[
- &b"09090909090909090909090909090909090909090909"[..],
- &b"8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a"[..],
- &b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"[..],
- &b"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4"[..],
- &b"1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d"[..],
- ];
-
- let hkdf = C::HkdfSha256::new(None, b"some ikm here");
-
- // Compute HKDF-Expand on the concatenation of all the info components
- let mut oneshot_res = [0u8; 16];
- hkdf.expand(&info_components.concat(), &mut oneshot_res)
- .unwrap();
-
- // Now iteratively join the components of info_components until it's all 1 component. The value
- // of HKDF-Expand should be the same throughout
- let mut num_concatted = 0;
- let mut info_head = Vec::new();
-
- while num_concatted < info_components.len() {
- info_head.extend(info_components[num_concatted]);
-
- // Build the new input to be the info head followed by the remaining components
- let input: Vec<&[u8]> = iter::once(info_head.as_slice())
- .chain(info_components.iter().cloned().skip(num_concatted + 1))
- .collect();
-
- // Compute and compare to the one-shot answer
- let mut multipart_res = [0u8; 16];
- hkdf.expand_multi_info(&input, &mut multipart_res).unwrap();
- assert_eq!(multipart_res, oneshot_res);
- num_concatted += 1;
- }
-}
-
-#[test]
-fn hkdf_sha_256_wycheproof_test_vectors_rc() {
- run_hkdf_test_vectors::<<RustCrypto as CryptoProvider>::HkdfSha256>(HashAlg::Sha256)
-}
-
-#[test]
-fn hkdf_sha_512_wycheproof_test_vectors_rc() {
- run_hkdf_test_vectors::<<RustCrypto as CryptoProvider>::HkdfSha512>(HashAlg::Sha512)
-}
-
-#[test]
-fn hkdf_sha_256_wycheproof_test_vectors_openssl() {
- run_hkdf_test_vectors::<<Openssl as CryptoProvider>::HkdfSha256>(HashAlg::Sha256)
-}
-
-#[test]
-fn hkdf_sha_512_wycheproof_test_vectors_openssl() {
- run_hkdf_test_vectors::<<Openssl as CryptoProvider>::HkdfSha512>(HashAlg::Sha512)
-}
-
-enum HashAlg {
- Sha256,
- Sha512,
-}
-
-fn run_hkdf_test_vectors<K: crypto_provider::hkdf::Hkdf>(hash: HashAlg) {
- let test_name = match hash {
- HashAlg::Sha256 => wycheproof::hkdf::TestName::HkdfSha256,
- HashAlg::Sha512 => wycheproof::hkdf::TestName::HkdfSha512,
- };
-
- let test_set =
- wycheproof::hkdf::TestSet::load(test_name).expect("should be able to load test set");
- for test_group in test_set.test_groups {
- for test in test_group.tests {
- let ikm = test.ikm;
- let salt = test.salt;
- let info = test.info;
- let okm = test.okm;
- let tc_id = test.tc_id;
- if let Some(desc) = run_test::<K>(
- ikm.as_slice(),
- salt.as_slice(),
- info.as_slice(),
- okm.as_slice(),
- ) {
- panic!(
- "\n\
- Failed test {tc_id}: {desc}\n\
- ikm:\t{ikm:?}\n\
- salt:\t{salt:?}\n\
- info:\t{info:?}\n\
- okm:\t{okm:?}\n"
- );
- }
- }
- }
-}
-
-fn run_test<K: crypto_provider::hkdf::Hkdf>(
- ikm: &[u8],
- salt: &[u8],
- info: &[u8],
- okm: &[u8],
-) -> Option<&'static str> {
- let prk = K::new(Some(salt), ikm);
- let mut got_okm = vec![0; okm.len()];
-
- if prk.expand(info, &mut got_okm).is_err() {
- return Some("prk expand");
- }
- if got_okm != okm {
- return Some("mismatch in okm");
- }
- None
-}
diff --git a/nearby/crypto/crypto_provider/tests/hmac_tests.rs b/nearby/crypto/crypto_provider/tests/hmac_tests.rs
deleted file mode 100644
index b7b64ee..0000000
--- a/nearby/crypto/crypto_provider/tests/hmac_tests.rs
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright 2023 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-use core::cmp::min;
-use crypto_provider::CryptoProvider;
-use crypto_provider_openssl::Openssl;
-use crypto_provider_rustcrypto::RustCrypto;
-use wycheproof::TestResult;
-
-#[test]
-fn hmac_sha_256_wycheproof_test_vectors_rustcrypto() {
- run_hmac_test_vectors::<32, <RustCrypto as CryptoProvider>::HmacSha256>(HashAlg::Sha256)
-}
-
-#[test]
-fn hmac_sha_256_wycheproof_test_vectors_openssl() {
- run_hmac_test_vectors::<32, <Openssl as CryptoProvider>::HmacSha256>(HashAlg::Sha256)
-}
-
-#[test]
-fn hmac_sha_512_wycheproof_test_vectors_rustcrypto() {
- run_hmac_test_vectors::<64, <RustCrypto as CryptoProvider>::HmacSha512>(HashAlg::Sha512)
-}
-
-#[test]
-fn hmac_sha_512_wycheproof_test_vectors_openssl() {
- run_hmac_test_vectors::<64, <Openssl as CryptoProvider>::HmacSha512>(HashAlg::Sha512)
-}
-
-enum HashAlg {
- Sha256,
- Sha512,
-}
-
-// Tests vectors from Project Wycheproof:
-// https://github.com/google/wycheproof
-fn run_hmac_test_vectors<const N: usize, H: crypto_provider::hmac::Hmac<N>>(hash: HashAlg) {
- let test_name = match hash {
- HashAlg::Sha256 => wycheproof::mac::TestName::HmacSha256,
- HashAlg::Sha512 => wycheproof::mac::TestName::HmacSha512,
- };
- let test_set =
- wycheproof::mac::TestSet::load(test_name).expect("should be able to load test set");
-
- for test_group in test_set.test_groups {
- for test in test_group.tests {
- let key = test.key;
- let msg = test.msg;
- let tag = test.tag;
- let tc_id = test.tc_id;
- let valid = match test.result {
- TestResult::Valid | TestResult::Acceptable => true,
- TestResult::Invalid => false,
- };
-
- if let Some(desc) =
- run_test::<N, H>(key.as_slice(), msg.as_slice(), tag.as_slice(), valid)
- {
- panic!(
- "\n\
- Failed test {tc_id}: {desc}\n\
- key:\t{key:?}\n\
- msg:\t{msg:?}\n\
- tag:\t{tag:?}\n",
- );
- }
- }
- }
-}
-
-fn run_test<const N: usize, H: crypto_provider::hmac::Hmac<N>>(
- key: &[u8],
- input: &[u8],
- tag: &[u8],
- valid_data: bool,
-) -> Option<&'static str> {
- let mut mac = H::new_from_slice(key).unwrap();
- mac.update(input);
- let result = mac.finalize();
- let n = tag.len();
- let result_bytes = &result[..n];
-
- if valid_data {
- if result_bytes != tag {
- return Some("whole message");
- }
- } else {
- return if result_bytes == tag {
- Some("invalid should not match")
- } else {
- None
- };
- }
-
- // test reading different chunk sizes
- for chunk_size in 1..min(64, input.len()) {
- let mut mac = H::new_from_slice(key).unwrap();
- for chunk in input.chunks(chunk_size) {
- mac.update(chunk);
- }
- let res = mac.verify_truncated_left(tag);
- if res.is_err() {
- return Some("chunked message");
- }
- }
-
- None
-}
diff --git a/nearby/crypto/crypto_provider_boringssl/src/aes.rs b/nearby/crypto/crypto_provider_boringssl/src/aes.rs
index a92f67e..a4f275e 100644
--- a/nearby/crypto/crypto_provider_boringssl/src/aes.rs
+++ b/nearby/crypto/crypto_provider_boringssl/src/aes.rs
@@ -12,8 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! Implementation of `crypto_provider::aes` types using BoringSSL.
-
use bssl_crypto::aes::{AesDecryptKey, AesEncryptKey};
use crypto_provider::aes::{
Aes, Aes128Key, Aes256Key, AesBlock, AesCipher, AesDecryptCipher, AesEncryptCipher, AesKey,
diff --git a/nearby/crypto/crypto_provider_boringssl/src/hkdf.rs b/nearby/crypto/crypto_provider_boringssl/src/hkdf.rs
new file mode 100644
index 0000000..4ab0ad4
--- /dev/null
+++ b/nearby/crypto/crypto_provider_boringssl/src/hkdf.rs
@@ -0,0 +1,63 @@
+// Copyright 2023 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! BoringSSL based HKDF implementation. Unfortunately, because the OpenSSL and BoringSSL APIs
+//! diverged for HKDF, we have to have separate implementations.
+//!
+//! See the _Using BoringSSL_ section in `nearby/scripts/prepare_boringssl.sh` for instructions on
+//! how to test against BoringSSL.
+
+use bssl_crypto::digest::Md;
+use crypto_provider::hkdf::InvalidLength;
+
+/// Struct providing BoringSSL implemented Hkdf operations.
+pub struct Hkdf<M: Md>(bssl_crypto::hkdf::Hkdf<M>);
+
+impl<M: Md> crypto_provider::hkdf::Hkdf for Hkdf<M> {
+ fn new(salt: Option<&[u8]>, ikm: &[u8]) -> Self {
+ Self(bssl_crypto::hkdf::Hkdf::<M>::new(salt, ikm))
+ }
+
+ fn expand_multi_info(
+ &self,
+ info_components: &[&[u8]],
+ okm: &mut [u8],
+ ) -> Result<(), InvalidLength> {
+ if okm.is_empty() {
+ return Ok(());
+ }
+ self.0
+ .expand_multi_info(info_components, okm)
+ .map_err(|_| InvalidLength)
+ }
+
+ fn expand(&self, info: &[u8], okm: &mut [u8]) -> Result<(), InvalidLength> {
+ if okm.is_empty() {
+ return Ok(());
+ }
+ self.0.expand(info, okm).map_err(|_| InvalidLength)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::Boringssl;
+ use core::marker::PhantomData;
+ use crypto_provider::hkdf::testing::*;
+
+ #[apply(hkdf_test_cases)]
+ fn hkdf_tests(testcase: CryptoProviderTestCase<Boringssl>) {
+ testcase(PhantomData);
+ }
+}
diff --git a/nearby/crypto/crypto_provider_boringssl/src/hmac.rs b/nearby/crypto/crypto_provider_boringssl/src/hmac.rs
new file mode 100644
index 0000000..3459c3b
--- /dev/null
+++ b/nearby/crypto/crypto_provider_boringssl/src/hmac.rs
@@ -0,0 +1,93 @@
+// Copyright 2023 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use crypto_provider::hmac::{InvalidLength, MacError};
+
+/// BoringSSL implemented Hmac Sha256 struct
+pub struct HmacSha256(bssl_crypto::hmac::HmacSha256);
+
+impl crypto_provider::hmac::Hmac<32> for HmacSha256 {
+ fn new_from_key(key: [u8; 32]) -> Self {
+ Self(bssl_crypto::hmac::HmacSha256::new(key))
+ }
+
+ fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
+ Ok(Self(bssl_crypto::hmac::HmacSha256::new_from_slice(key)))
+ }
+
+ fn update(&mut self, data: &[u8]) {
+ self.0.update(data)
+ }
+
+ fn finalize(self) -> [u8; 32] {
+ self.0.finalize()
+ }
+
+ fn verify_slice(self, tag: &[u8]) -> Result<(), MacError> {
+ self.0.verify_slice(tag).map_err(|_| MacError)
+ }
+
+ fn verify(self, tag: [u8; 32]) -> Result<(), MacError> {
+ self.0.verify(tag).map_err(|_| MacError)
+ }
+
+ fn verify_truncated_left(self, tag: &[u8]) -> Result<(), MacError> {
+ self.0.verify_truncated_left(tag).map_err(|_| MacError)
+ }
+}
+
+/// BoringSSL implemented Hmac Sha512 struct
+pub struct HmacSha512(bssl_crypto::hmac::HmacSha512);
+
+impl crypto_provider::hmac::Hmac<64> for HmacSha512 {
+ fn new_from_key(key: [u8; 64]) -> Self {
+ Self(bssl_crypto::hmac::HmacSha512::new(key))
+ }
+
+ fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
+ Ok(Self(bssl_crypto::hmac::HmacSha512::new_from_slice(key)))
+ }
+
+ fn update(&mut self, data: &[u8]) {
+ self.0.update(data)
+ }
+
+ fn finalize(self) -> [u8; 64] {
+ self.0.finalize()
+ }
+
+ fn verify_slice(self, tag: &[u8]) -> Result<(), MacError> {
+ self.0.verify_slice(tag).map_err(|_| MacError)
+ }
+
+ fn verify(self, tag: [u8; 64]) -> Result<(), MacError> {
+ self.0.verify(tag).map_err(|_| MacError)
+ }
+
+ fn verify_truncated_left(self, tag: &[u8]) -> Result<(), MacError> {
+ self.0.verify_truncated_left(tag).map_err(|_| MacError)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::Boringssl;
+ use core::marker::PhantomData;
+ use crypto_provider::hmac::testing::*;
+
+ #[apply(hmac_test_cases)]
+ fn hmac_tests(testcase: CryptoProviderTestCase<Boringssl>) {
+ testcase(PhantomData);
+ }
+}
diff --git a/nearby/crypto/crypto_provider_boringssl/src/lib.rs b/nearby/crypto/crypto_provider_boringssl/src/lib.rs
index 0775172..a7e78d0 100644
--- a/nearby/crypto/crypto_provider_boringssl/src/lib.rs
+++ b/nearby/crypto/crypto_provider_boringssl/src/lib.rs
@@ -23,20 +23,28 @@
//! Crate which provides impls for CryptoProvider backed by BoringSSL.
-use crypto_provider::CryptoProvider;
+use bssl_crypto::digest::{Sha256, Sha512};
+use crypto_provider::{CryptoProvider, CryptoRng};
use crypto_provider_stubs::*;
+/// Implementation of `crypto_provider::aes` types using BoringSSL.
pub mod aes;
+/// Implementations of crypto_provider::hkdf traits backed by BoringSSL
+pub mod hkdf;
+
+/// Implementations of crypto_provider::hmac traits backed by BoringSSL
+pub mod hmac;
+
/// The BoringSSL backed struct which implements CryptoProvider
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct Boringssl;
impl CryptoProvider for Boringssl {
- type HkdfSha256 = HkdfStubs;
- type HmacSha256 = HmacStubs;
- type HkdfSha512 = HkdfStubs;
- type HmacSha512 = HmacStubs;
+ type HkdfSha256 = hkdf::Hkdf<Sha256>;
+ type HmacSha256 = hmac::HmacSha256;
+ type HkdfSha512 = hkdf::Hkdf<Sha512>;
+ type HmacSha512 = hmac::HmacSha512;
type AesCbcPkcs7Padded = AesCbcPkcs7PaddedStubs;
type X25519 = X25519Stubs;
type P256 = P256Stubs;
@@ -47,9 +55,24 @@
type AesCtr128 = Aes128Stubs;
type AesCtr256 = Aes256Stubs;
type Ed25519 = Ed25519Stubs;
- type CryptoRng = ();
+ type CryptoRng = BoringSslRng;
fn constant_time_eq(_a: &[u8], _b: &[u8]) -> bool {
unimplemented!()
}
}
+
+/// OpenSSL implemented random number generator
+pub struct BoringSslRng;
+
+impl CryptoRng for BoringSslRng {
+ fn new() -> Self {
+ BoringSslRng {}
+ }
+
+ fn next_u64(&mut self) -> u64 {
+ let mut buf = [0; 8];
+ bssl_crypto::rand::rand_bytes(&mut buf);
+ u64::from_be_bytes(buf)
+ }
+}
diff --git a/nearby/crypto/crypto_provider_openssl/src/hkdf_boringssl.rs b/nearby/crypto/crypto_provider_openssl/src/hkdf_boringssl.rs
index 63e0ebc..f6c106d 100644
--- a/nearby/crypto/crypto_provider_openssl/src/hkdf_boringssl.rs
+++ b/nearby/crypto/crypto_provider_openssl/src/hkdf_boringssl.rs
@@ -23,7 +23,6 @@
use std::marker::PhantomData;
/// openssl based hkdf implementation
-#[derive(Clone)]
pub struct Hkdf<H: OpenSslHash> {
_marker: PhantomData<H>,
salt: Option<Vec<u8>>,
@@ -63,3 +62,15 @@
self.expand_multi_info(&[info], okm)
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::Openssl;
+ use core::marker::PhantomData;
+ use crypto_provider::hkdf::testing::*;
+
+ #[apply(hkdf_test_cases)]
+ fn hkdf_tests(testcase: CryptoProviderTestCase<Openssl>) {
+ testcase(PhantomData);
+ }
+}
diff --git a/nearby/crypto/crypto_provider_openssl/src/hkdf_openssl.rs b/nearby/crypto/crypto_provider_openssl/src/hkdf_openssl.rs
index b6885bc..605cff1 100644
--- a/nearby/crypto/crypto_provider_openssl/src/hkdf_openssl.rs
+++ b/nearby/crypto/crypto_provider_openssl/src/hkdf_openssl.rs
@@ -17,7 +17,6 @@
use std::marker::PhantomData;
/// openssl based hkdf implementation
-#[derive(Clone)]
pub struct Hkdf<H: OpenSslHash> {
_marker: PhantomData<H>,
salt: Option<Vec<u8>>,
@@ -61,3 +60,15 @@
self.expand_multi_info(&[info], okm)
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::Openssl;
+ use core::marker::PhantomData;
+ use crypto_provider::hkdf::testing::*;
+
+ #[apply(hkdf_test_cases)]
+ fn hkdf_tests(testcase: CryptoProviderTestCase<Openssl>) {
+ testcase(PhantomData);
+ }
+}
diff --git a/nearby/crypto/crypto_provider_openssl/src/hmac_boringssl.rs b/nearby/crypto/crypto_provider_openssl/src/hmac_boringssl.rs
index 82782b9..af728b3 100644
--- a/nearby/crypto/crypto_provider_openssl/src/hmac_boringssl.rs
+++ b/nearby/crypto/crypto_provider_openssl/src/hmac_boringssl.rs
@@ -97,3 +97,15 @@
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::Openssl;
+ use core::marker::PhantomData;
+ use crypto_provider::hmac::testing::*;
+
+ #[apply(hmac_test_cases)]
+ fn hmac_tests(testcase: CryptoProviderTestCase<Openssl>) {
+ testcase(PhantomData);
+ }
+}
diff --git a/nearby/crypto/crypto_provider_openssl/src/hmac_openssl.rs b/nearby/crypto/crypto_provider_openssl/src/hmac_openssl.rs
index 34a64c4..d99ee3e 100644
--- a/nearby/crypto/crypto_provider_openssl/src/hmac_openssl.rs
+++ b/nearby/crypto/crypto_provider_openssl/src/hmac_openssl.rs
@@ -175,3 +175,15 @@
Err(MacError)
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::Openssl;
+ use core::marker::PhantomData;
+ use crypto_provider::hmac::testing::*;
+
+ #[apply(hmac_test_cases)]
+ fn hmac_tests(testcase: CryptoProviderTestCase<Openssl>) {
+ testcase(PhantomData);
+ }
+}
diff --git a/nearby/crypto/crypto_provider_rustcrypto/Cargo.toml b/nearby/crypto/crypto_provider_rustcrypto/Cargo.toml
index ad5a4b8..2ab5354 100644
--- a/nearby/crypto/crypto_provider_rustcrypto/Cargo.toml
+++ b/nearby/crypto/crypto_provider_rustcrypto/Cargo.toml
@@ -14,9 +14,8 @@
x25519-dalek.workspace = true
p256 = { workspace = true, features = ["ecdh"], default-features = false }
sec1.workspace = true
-ed25519-dalek = { workspace = true, default-features = false }
+ed25519-dalek = { workspace = true, default-features = false, features = ["rand_core"] }
rand = { workspace = true, default-features = false }
-rand_core_05_adapter.workspace = true
rand_core.workspace = true
subtle.workspace = true
aes.workspace = true
diff --git a/nearby/crypto/crypto_provider_rustcrypto/src/ed25519.rs b/nearby/crypto/crypto_provider_rustcrypto/src/ed25519.rs
index 874aa82..df5c5de 100644
--- a/nearby/crypto/crypto_provider_rustcrypto/src/ed25519.rs
+++ b/nearby/crypto/crypto_provider_rustcrypto/src/ed25519.rs
@@ -12,30 +12,33 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use ed25519_dalek::Signer;
+
use crypto_provider::ed25519::{
InvalidBytes, InvalidSignature, Signature as _, SignatureError, KEY_LENGTH, KEY_PAIR_LENGTH,
SIGNATURE_LENGTH,
};
-use ed25519_dalek::Signer;
pub struct Ed25519;
+
impl crypto_provider::ed25519::Ed25519Provider for Ed25519 {
type KeyPair = KeyPair;
type PublicKey = PublicKey;
type Signature = Signature;
}
-pub struct KeyPair(ed25519_dalek::Keypair);
+pub struct KeyPair(ed25519_dalek::SigningKey);
+
impl crypto_provider::ed25519::KeyPair for KeyPair {
type PublicKey = PublicKey;
type Signature = Signature;
fn to_bytes(&self) -> [u8; KEY_PAIR_LENGTH] {
- self.0.to_bytes()
+ self.0.to_keypair_bytes()
}
fn from_bytes(bytes: [u8; KEY_PAIR_LENGTH]) -> Result<Self, InvalidBytes> {
- ed25519_dalek::Keypair::from_bytes(&bytes)
+ ed25519_dalek::SigningKey::from_keypair_bytes(&bytes)
.map(Self)
.map_err(|_| InvalidBytes)
}
@@ -51,23 +54,22 @@
#[cfg(feature = "std")]
fn generate() -> Self {
let mut csprng = rand::rngs::ThreadRng::default();
- Self(ed25519_dalek::Keypair::generate(
- &mut rand_core_05_adapter::RandWrapper::from(&mut csprng),
- ))
+ Self(ed25519_dalek::SigningKey::generate(&mut csprng))
}
fn public(&self) -> Self::PublicKey {
- PublicKey(self.0.public)
+ PublicKey(self.0.verifying_key())
}
}
pub struct Signature(ed25519_dalek::Signature);
+
impl crypto_provider::ed25519::Signature for Signature {
fn from_bytes(bytes: &[u8]) -> Result<Self, InvalidSignature> {
if bytes.len() != SIGNATURE_LENGTH {
return Err(InvalidSignature);
}
- ed25519_dalek::Signature::from_bytes(bytes)
+ ed25519_dalek::Signature::from_slice(bytes)
.map(Self)
.map_err(|_| InvalidSignature)
}
@@ -77,7 +79,8 @@
}
}
-pub struct PublicKey(ed25519_dalek::PublicKey);
+pub struct PublicKey(ed25519_dalek::VerifyingKey);
+
impl crypto_provider::ed25519::PublicKey for PublicKey {
type Signature = Signature;
@@ -85,7 +88,7 @@
where
Self: Sized,
{
- ed25519_dalek::PublicKey::from_bytes(&bytes)
+ ed25519_dalek::VerifyingKey::from_bytes(&bytes)
.map(PublicKey)
.map_err(|_| InvalidBytes)
}
@@ -107,9 +110,10 @@
#[cfg(test)]
mod tests {
- use crate::ed25519::Ed25519;
use crypto_provider::ed25519::testing::{run_rfc_test_vectors, run_wycheproof_test_vectors};
+ use crate::ed25519::Ed25519;
+
#[test]
fn wycheproof_test_ed25519_rustcrypto() {
run_wycheproof_test_vectors::<Ed25519>()
diff --git a/nearby/crypto/crypto_provider_rustcrypto/src/hkdf_rc.rs b/nearby/crypto/crypto_provider_rustcrypto/src/hkdf_rc.rs
index d6ca687..8ff5d7b 100644
--- a/nearby/crypto/crypto_provider_rustcrypto/src/hkdf_rc.rs
+++ b/nearby/crypto/crypto_provider_rustcrypto/src/hkdf_rc.rs
@@ -22,7 +22,6 @@
use hmac::digest::{HashMarker, OutputSizeUser};
/// RustCrypto based hkdf implementation
-#[derive(Clone)]
pub struct Hkdf<D>
where
D: OutputSizeUser,
@@ -72,3 +71,15 @@
self.hkdf_impl.expand(info, okm).map_err(|_| InvalidLength)
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::RustCrypto;
+ use core::marker::PhantomData;
+ use crypto_provider::hkdf::testing::*;
+
+ #[apply(hkdf_test_cases)]
+ fn hkdf_tests(testcase: CryptoProviderTestCase<RustCrypto>) {
+ testcase(PhantomData);
+ }
+}
diff --git a/nearby/crypto/crypto_provider_rustcrypto/src/hmac_rc.rs b/nearby/crypto/crypto_provider_rustcrypto/src/hmac_rc.rs
index e31b815..95254a5 100644
--- a/nearby/crypto/crypto_provider_rustcrypto/src/hmac_rc.rs
+++ b/nearby/crypto/crypto_provider_rustcrypto/src/hmac_rc.rs
@@ -112,3 +112,15 @@
.map_err(|_| MacError)
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::RustCrypto;
+ use core::marker::PhantomData;
+ use crypto_provider::hmac::testing::*;
+
+ #[apply(hmac_test_cases)]
+ fn hmac_tests(testcase: CryptoProviderTestCase<RustCrypto>) {
+ testcase(PhantomData);
+ }
+}
diff --git a/nearby/crypto/crypto_provider_rustcrypto/src/lib.rs b/nearby/crypto/crypto_provider_rustcrypto/src/lib.rs
index 9807f81..9145233 100644
--- a/nearby/crypto/crypto_provider_rustcrypto/src/lib.rs
+++ b/nearby/crypto/crypto_provider_rustcrypto/src/lib.rs
@@ -65,7 +65,7 @@
}
impl<R: CryptoRng + SeedableRng + RngCore> RustCryptoImpl<R> {
- ///
+ /// Create a new instance of RustCrypto
pub fn new() -> Self {
Self {
_marker: Default::default(),
diff --git a/nearby/crypto/crypto_provider_rustcrypto/src/x25519.rs b/nearby/crypto/crypto_provider_rustcrypto/src/x25519.rs
index a184d44..794d780 100644
--- a/nearby/crypto/crypto_provider_rustcrypto/src/x25519.rs
+++ b/nearby/crypto/crypto_provider_rustcrypto/src/x25519.rs
@@ -48,7 +48,7 @@
fn generate_random(rng: &mut Self::Rng) -> Self {
Self {
- secret: x25519_dalek::EphemeralSecret::new(&mut rng.0),
+ secret: x25519_dalek::EphemeralSecret::random_from_rng(&mut rng.0),
marker: Default::default(),
}
}
@@ -76,9 +76,11 @@
_public_key: &X25519PublicKey,
) -> Result<Self, Self::Error> {
Ok(Self {
- secret: x25519_dalek::EphemeralSecret::new(&mut crate::testing::MockCryptoRng {
- values: private_bytes.iter(),
- }),
+ secret: x25519_dalek::EphemeralSecret::random_from_rng(
+ &mut crate::testing::MockCryptoRng {
+ values: private_bytes.iter(),
+ },
+ ),
marker: Default::default(),
})
}