Skip to content

Commit

Permalink
perf: reduce allocation
Browse files Browse the repository at this point in the history
  • Loading branch information
ken0x0a committed Mar 19, 2024
1 parent fdc8cd2 commit 135550d
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions core/lib/src/parser/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ use sha2::Sha256;
/// // NG
/// }
/// ```
pub fn validate_signature(channel_secret: String, signature: String, body: String) -> bool {
pub fn validate_signature(channel_secret: &str, signature: &str, body: &str) -> bool {
type HmacSha256 = Hmac<Sha256>;

let mut mac = HmacSha256::new_from_slice(channel_secret.as_bytes())
.expect("HMAC can take key of any size");
mac.update(body.as_bytes());
let mut buf = String::new();
general_purpose::STANDARD.encode_string(&mac.finalize().into_bytes().to_vec(), &mut buf);
general_purpose::STANDARD.encode_string(mac.finalize().into_bytes(), &mut buf);
buf == signature
}
2 changes: 1 addition & 1 deletion examples/actix_web_example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async fn callback(signature: Signature, bytes: web::Bytes) -> Result<HttpRespons

let body: &str = &String::from_utf8(bytes.to_vec()).unwrap();

if !validate_signature(channel_secret.to_string(), signature.key, body.to_string()) {
if !validate_signature(channel_secret, &signature.key, body) {
return Err(ErrorBadRequest("x-line-signature is invalid."));
}

Expand Down
2 changes: 1 addition & 1 deletion examples/rocket_example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async fn world(signature: Signature, body: String) -> (Status, &'static str) {
println!("{signature:#?}");
println!("{body:#?}");

if !validate_signature(channel_secret.to_string(), signature.key, body.clone()) {
if !validate_signature(channel_secret, &signature.key, &body) {
return (Status::BadRequest, "x-line-signature is invalid.");
}

Expand Down

0 comments on commit 135550d

Please sign in to comment.