pub mod ed25519;
pub mod hmac;
pub mod rsa;
use secrecy::{ExposeSecret, SecretString};
use crate::error::OkxError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SigningAlgorithm {
HmacSha256,
RsaPkcs1v15,
Ed25519,
}
pub fn detect_signing_algorithm(secret: &str) -> SigningAlgorithm {
if secret.contains("PRIVATE KEY") {
if secret.contains("RSA PRIVATE KEY") {
return SigningAlgorithm::RsaPkcs1v15;
}
if secret.len() <= 150 {
return SigningAlgorithm::Ed25519;
}
return SigningAlgorithm::RsaPkcs1v15;
}
SigningAlgorithm::HmacSha256
}
pub fn sign_message(message: &str, secret: &SecretString) -> Result<String, OkxError> {
let algo = detect_signing_algorithm(secret.expose_secret());
match algo {
SigningAlgorithm::HmacSha256 => hmac::sign_hmac_sha256(message, secret),
SigningAlgorithm::RsaPkcs1v15 => rsa::sign_rsa(message, secret),
SigningAlgorithm::Ed25519 => ed25519::sign_ed25519(message, secret),
}
}
pub fn sign_rest(
timestamp: &str,
method: &str,
endpoint: &str,
body: &str,
secret: &SecretString,
) -> Result<String, OkxError> {
let message = format!("{timestamp}{method}{endpoint}{body}");
sign_message(&message, secret)
}
pub fn sign_ws(timestamp: &str, secret: &SecretString) -> Result<String, OkxError> {
let message = format!("{timestamp}GET/users/self/verify");
sign_message(&message, secret)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_detect_hmac() {
assert_eq!(
detect_signing_algorithm("some-api-secret-key"),
SigningAlgorithm::HmacSha256
);
}
#[test]
fn test_detect_rsa() {
let key =
"-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----";
assert_eq!(detect_signing_algorithm(key), SigningAlgorithm::RsaPkcs1v15);
}
#[test]
fn test_detect_ed25519() {
let key =
"-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIDk=\n-----END PRIVATE KEY-----";
assert_eq!(detect_signing_algorithm(key), SigningAlgorithm::Ed25519);
}
#[test]
fn test_sign_rest() {
let secret = SecretString::from("test-secret".to_string());
let result = sign_rest(
"2024-01-15T12:30:45.123Z",
"GET",
"/api/v5/account/balance",
"",
&secret,
);
assert!(result.is_ok());
}
#[test]
fn test_sign_ws() {
let secret = SecretString::from("test-secret".to_string());
let result = sign_ws("1705312245", &secret);
assert!(result.is_ok());
}
}