Rust 相当于 Python 中的 hmac 摘要

Rust equivalent of hmac digest in Python

我正在尝试在 Python 中找到与以下函数等效的 Rust。我查看了 hmac 箱子,但不清楚如何获得相同的摘要。

import base64
import hashlib
import hmac


def hmac_signature(key, msg):
    hmac_buffer = hmac.new(
        key=bytes(key, 'utf-8'),
        msg=bytes(msg, 'utf-8'),
        digestmod=hashlib.sha256
    )
    return base64.b64encode(hmac_buffer.digest()).decode('utf-8')

尝试

use base64;
use sha2::Sha256;
use hmac::{Hmac, Mac};
use ring::{digest};


fn main() {
    let key = "secret";
    let msg = "message";

    let signature = hmac_signature(key, msg);

    let expected = "i19IcCmVwVmMVz2x4hhmqbgl1KeU0WnXBgoDYFeWNgs=";

    assert_eq!(signature, expected);
}

fn hmac_signature(key: &str, msg: &str) -> String {
    type HmacSha256 = Hmac<Sha256>;
    
    let mut mac = HmacSha256::new_from_slice(key.as_bytes()).unwrap();
    mac.update(&msg.as_bytes());

    let code_bytes = mac.finalize().into_bytes();

    let hash = |v| digest::digest(&digest::SHA256, v);
    let digest = hash(&code_bytes);

    return base64::encode(&digest);
}
use base64;
use sha2::Sha256;
use hmac::{Hmac, Mac};


fn main() {
    let key = "secret";
    let msg = "message";

    let signature = hmac_signature(key, msg);

    let expected = "i19IcCmVwVmMVz2x4hhmqbgl1KeU0WnXBgoDYFeWNgs=";

    assert_eq!(signature, expected);
}

fn hmac_signature(key: &str, msg: &str) -> String {
    type HmacSha256 = Hmac<Sha256>;
    
    let mut mac = HmacSha256::new_from_slice(key.as_bytes()).unwrap();
    mac.update(&msg.as_bytes());

    let code_bytes = mac.finalize().into_bytes();

    return base64::encode(&code_bytes.to_vec());
}