use base64::{engine::general_purpose::STANDARD, Engine};
use ethers::core::k256::sha2::Sha256;
use hmac::{self, Hmac, Mac};
pub fn encrypt_prehash(
api_secret: &str,
timestamp: &str,
method: &str,
endpoint: &str,
body: &str,
) -> String {
let mut mac = Hmac::<Sha256>::new_from_slice(api_secret.as_bytes())
.expect("Use API-Secret to encrypt the prehash");
let prehash = format!("{}{}{}{}", timestamp, method, endpoint, body);
mac.update(prehash.as_bytes());
let result = mac.finalize();
let sign = result.into_bytes();
STANDARD.encode(sign)
}
pub fn encrypt_pass(api_secret: String, passphrase: String) -> String {
let mut mac = Hmac::<Sha256>::new_from_slice(api_secret.as_bytes())
.expect("Use API-Secret to encrypt the passphrase");
mac.update(passphrase.as_bytes());
let result = mac.finalize();
let sign = result.into_bytes();
STANDARD.encode(sign)
}
#[cfg(test)]
mod test {
use super::*;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
#[test]
fn test_hmac() {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Clock may have gone backwards")
.as_millis()
.to_string();
let payload = r#"{"clientOid": "235b7471-0190-4e10-a4cf-953c83a06af5", "side": "sell", "symbol": "ETH-USDT", "type": "market", "isIsolated": false, "funds": "1"}"#;
let en64_sign = encrypt_prehash(
"1a422807-19f5-4e8f-9135-b89707845621",
×tamp,
"POST",
"/api/v3/hf/margin/order",
payload,
);
println!("{}", en64_sign);
}
#[test]
fn test_passphrase() {
let _passphrase = "910988".to_string();
let en64_pass = encrypt_pass(
"1a922807-19f5-4e6c-9135-b89707845621".to_string(),
_passphrase,
);
println!("{}", en64_pass);
}
}