Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add crypto hmac sha 256 #685

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ bitflags! {
const JAVY_STREAM_IO = 1 << 2;
const REDIRECT_STDOUT_TO_STDERR = 1 << 3;
const TEXT_ENCODING = 1 << 4;
const CRYPTO = 1 << 5;
}
}

Expand All @@ -44,5 +45,6 @@ mod tests {
assert!(Config::JAVY_STREAM_IO == Config::from_bits(1 << 2).unwrap());
assert!(Config::REDIRECT_STDOUT_TO_STDERR == Config::from_bits(1 << 3).unwrap());
assert!(Config::TEXT_ENCODING == Config::from_bits(1 << 4).unwrap());
assert!(Config::CRYPTO == Config::from_bits(1 << 5).unwrap());
}
}
3 changes: 2 additions & 1 deletion crates/core/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ pub(crate) fn new(shared_config: SharedConfig) -> Result<Runtime> {
// we're disabling this temporarily. It will be enabled once we have a
// fix forward.
.override_json_parse_and_stringify(false)
.javy_json(false);
.javy_json(false)
.crypto(shared_config.contains(SharedConfig::CRYPTO));

Runtime::new(std::mem::take(config))
}
2 changes: 2 additions & 0 deletions crates/javy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ quickcheck = "1"
bitflags = { workspace = true }
fastrand = "2.1.0"
simd-json = { version = "0.13.10", optional = true, default-features = false, features = ["big-int-as-float", "serde_impl"] }
sha2 = "0.10.8"
hmac = "0.12.1"

[dev-dependencies]
javy-test-macros = { path = "../test-macros/" }
Expand Down
88 changes: 88 additions & 0 deletions crates/javy/src/apis/crypto/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use crate::quickjs::{context::Intrinsic, qjs, Ctx, Function, Object, String as JSString, Value};
use crate::{hold, hold_and_release, to_js_error, val_to_string, Args};
use anyhow::{bail, Error, Result};

use hmac::{Hmac, Mac};
use sha2::Sha256;

/// An implemetation of crypto APIs to optimize fuel.
/// Currently, hmacSHA256 is the only function implemented.
pub struct Crypto;

impl Intrinsic for Crypto {
unsafe fn add_intrinsic(ctx: std::ptr::NonNull<qjs::JSContext>) {
register(Ctx::from_raw(ctx)).expect("`Crypto` APIs to succeed")
}
}
fn register(this: Ctx<'_>) -> Result<()> {
let globals = this.globals();

// let crypto_obj = Object::new(cx)?;
let crypto_obj = Object::new(this.clone())?;

crypto_obj.set(
"hmacSHA256",
Function::new(this.clone(), |this, args| {
let (this, args) = hold_and_release!(this, args);
hmac_sha256(hold!(this.clone(), args)).map_err(|e| to_js_error(this, e))
}),
)?;

globals.set("crypto", crypto_obj)?;

Ok::<_, Error>(())
}
/// hmac_sha256 applies the HMAC algorithm using sha256 for hashing.
/// Arg[0] - secret
/// Arg[1] - message
/// returns - hex encoded string of hmac.
fn hmac_sha256(args: Args<'_>) -> Result<Value<'_>> {
let (cx, args) = args.release();

if args.len() != 2 {
bail!("Wrong number of arguments. Expected 2. Got {}", args.len());
}

let js_string_secret = val_to_string(&cx, args[0].clone())?;
let js_string_message = val_to_string(&cx, args[1].clone())?;

/// Create alias for HMAC-SHA256
type HmacSha256 = Hmac<Sha256>;

let mut mac = HmacSha256::new_from_slice(js_string_secret.as_bytes())
.expect("HMAC can take key of any size");
mac.update(js_string_message.as_bytes());

let result = mac.finalize();
let code_bytes = result.into_bytes();
let code: String = format!("{code_bytes:x}");
let js_string = JSString::from_str(cx, &code);
Ok(Value::from_string(js_string?))
}

#[cfg(test)]
mod tests {
use crate::{quickjs::Value, Config, Runtime};
use anyhow::{Error, Result};

#[test]
fn test_text_encoder_decoder() -> Result<()> {
let mut config = Config::default();
config.crypto(true);
let runtime = Runtime::new(config)?;

runtime.context().with(|this| {
let result: Value<'_> = this.eval(
r#"
let expectedHex = "97d2a569059bbcd8ead4444ff99071f4c01d005bcefe0d3567e1be628e5fdcd9";
let result = crypto.hmacSHA256("my secret and secure key", "input message");
expectedHex === result;
"#,
)?;

assert!(result.as_bool().unwrap());
Ok::<_, Error>(())
})?;
Ok(())
}
}
2 changes: 2 additions & 0 deletions crates/javy/src/apis/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,15 @@
//!
//! Disabled by default.
pub(crate) mod console;
pub(crate) mod crypto;
#[cfg(feature = "json")]
pub(crate) mod json;
pub(crate) mod random;
pub(crate) mod stream_io;
pub(crate) mod text_encoding;

pub(crate) use console::*;
pub(crate) use crypto::*;
#[cfg(feature = "json")]
pub(crate) use json::*;
pub(crate) use random::*;
Expand Down
9 changes: 9 additions & 0 deletions crates/javy/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ bitflags! {
const OPERATORS = 1 << 12;
const BIGNUM_EXTENSION = 1 << 13;
const TEXT_ENCODING = 1 << 14;
const CRYPTO = 1 << 15;
}
}

Expand Down Expand Up @@ -179,6 +180,14 @@ impl Config {
self
}

/// Whether the `crypto` intrinsic will be available.
/// Enabled by default.
// #[cfg(feature = "crypto")]
pub fn crypto(&mut self, enable: bool) -> &mut Self {
self.intrinsics.set(JSIntrinsics::CRYPTO, enable);
self
}

/// Enables whether the output of console.log will be redirected to
/// `stderr`.
pub fn redirect_stdout_to_stderr(&mut self, enable: bool) -> &mut Self {
Expand Down
7 changes: 6 additions & 1 deletion crates/javy/src/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// use crate::quickjs::JSContextRef;
use super::from_js_error;
use crate::{
apis::{Console, NonStandardConsole, Random, StreamIO, TextEncoding},
apis::{Console, Crypto, NonStandardConsole, Random, StreamIO, TextEncoding},
config::{JSIntrinsics, JavyIntrinsics},
Config,
};
Expand Down Expand Up @@ -144,6 +144,11 @@ impl Runtime {
JavyJson::add_intrinsic(ctx.as_raw())
}
}

if intrinsics.contains(JSIntrinsics::CRYPTO) {
// #[cfg(feature = "crypto")]
unsafe { Crypto::add_intrinsic(ctx.as_raw()) }
}
});

Ok(ManuallyDrop::new(context))
Expand Down
Loading