Skip to main content

windjammer_runtime/
crypto.rs

1//! Cryptographic functions
2//!
3//! Windjammer's `std::crypto` module maps to these functions.
4
5use sha2::{Digest, Sha256};
6
7/// SHA-256 hash
8pub fn sha256(data: &[u8]) -> String {
9    let mut hasher = Sha256::new();
10    hasher.update(data);
11    format!("{:x}", hasher.finalize())
12}
13
14/// SHA-256 hash of string
15pub fn sha256_string(s: &str) -> String {
16    sha256(s.as_bytes())
17}
18
19/// Hash password with bcrypt
20pub fn hash_password(password: &str) -> Result<String, String> {
21    bcrypt::hash(password, bcrypt::DEFAULT_COST).map_err(|e| e.to_string())
22}
23
24/// Verify password against bcrypt hash
25pub fn verify_password(password: &str, hash: &str) -> Result<bool, String> {
26    bcrypt::verify(password, hash).map_err(|e| e.to_string())
27}
28
29/// Base64 encode
30pub fn base64_encode(data: &[u8]) -> String {
31    use base64::{engine::general_purpose, Engine as _};
32    general_purpose::STANDARD.encode(data)
33}
34
35/// Base64 decode
36pub fn base64_decode(s: &str) -> Result<Vec<u8>, String> {
37    use base64::{engine::general_purpose, Engine as _};
38    general_purpose::STANDARD
39        .decode(s)
40        .map_err(|e| e.to_string())
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn test_sha256() {
49        let hash = sha256_string("hello");
50        assert_eq!(hash.len(), 64); // SHA-256 produces 64 hex characters
51        assert_eq!(
52            hash,
53            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
54        );
55    }
56
57    #[test]
58    fn test_password_hashing() {
59        let password = "secret123";
60        let hash = hash_password(password).unwrap();
61
62        assert!(verify_password(password, &hash).unwrap());
63        assert!(!verify_password("wrong", &hash).unwrap());
64    }
65
66    #[test]
67    fn test_base64() {
68        let data = b"hello world";
69        let encoded = base64_encode(data);
70        let decoded = base64_decode(&encoded).unwrap();
71        assert_eq!(decoded, data);
72    }
73}