From 5bcbbb75e9df029299647bf5c84f58b7317a5c1d Mon Sep 17 00:00:00 2001 From: Divy Srivastava Date: Thu, 8 Jul 2021 00:04:02 +0530 Subject: [PATCH] refactor(extensions/crypto): use key::CryptoHash with digest (#11309) --- extensions/crypto/00_crypto.js | 16 +--------------- extensions/crypto/key.rs | 12 ++++++++++++ extensions/crypto/lib.rs | 15 +++++---------- 3 files changed, 18 insertions(+), 25 deletions(-) diff --git a/extensions/crypto/00_crypto.js b/extensions/crypto/00_crypto.js index a6c6c07225..09ac76e4d5 100644 --- a/extensions/crypto/00_crypto.js +++ b/extensions/crypto/00_crypto.js @@ -109,20 +109,6 @@ return normalizedAlgorithm; } - // Should match op_crypto_subtle_digest() in extensions/crypto/lib.rs - function digestToId(name) { - switch (name) { - case "SHA-1": - return 0; - case "SHA-256": - return 1; - case "SHA-384": - return 2; - case "SHA-512": - return 3; - } - } - const _handle = Symbol("[[handle]]"); const _algorithm = Symbol("[[algorithm]]"); const _extractable = Symbol("[[extractable]]"); @@ -256,7 +242,7 @@ const result = await core.opAsync( "op_crypto_subtle_digest", - digestToId(algorithm.name), + algorithm.name, data, ); diff --git a/extensions/crypto/key.rs b/extensions/crypto/key.rs index d5801635e0..cb44812fd5 100644 --- a/extensions/crypto/key.rs +++ b/extensions/crypto/key.rs @@ -1,6 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use ring::agreement::Algorithm as RingAlgorithm; +use ring::digest; use ring::hmac::Algorithm as HmacAlgorithm; use ring::signature::EcdsaSigningAlgorithm; use serde::Deserialize; @@ -67,6 +68,17 @@ impl From for HmacAlgorithm { } } +impl From for &'static digest::Algorithm { + fn from(hash: CryptoHash) -> &'static digest::Algorithm { + match hash { + CryptoHash::Sha1 => &digest::SHA1_FOR_LEGACY_USE_ONLY, + CryptoHash::Sha256 => &digest::SHA256, + CryptoHash::Sha384 => &digest::SHA384, + CryptoHash::Sha512 => &digest::SHA512, + } + } +} + #[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub enum KeyUsage { diff --git a/extensions/crypto/lib.rs b/extensions/crypto/lib.rs index 348983deab..66e576c6a7 100644 --- a/extensions/crypto/lib.rs +++ b/extensions/crypto/lib.rs @@ -399,20 +399,15 @@ pub fn op_crypto_random_uuid( pub async fn op_crypto_subtle_digest( _state: Rc>, - algorithm_id: i8, + algorithm: CryptoHash, data: Option, ) -> Result { - let algorithm = match algorithm_id { - 0 => &digest::SHA1_FOR_LEGACY_USE_ONLY, - 1 => &digest::SHA256, - 2 => &digest::SHA384, - 3 => &digest::SHA512, - _ => panic!("Invalid algorithm id"), - }; - let input = data.ok_or_else(null_opbuf)?; let output = tokio::task::spawn_blocking(move || { - digest::digest(algorithm, &input).as_ref().to_vec().into() + digest::digest(algorithm.into(), &input) + .as_ref() + .to_vec() + .into() }) .await?;