77 lines
2.7 KiB
Python
77 lines
2.7 KiB
Python
"""真实系统随机源生成密钥,两次 HMAC 比较后校验所有输入;不输出 Secret。"""
|
|
|
|
|
|
def source(language):
|
|
if language == 'dever':
|
|
return '''flow roundtrip(value: Int) (out: Int)
|
|
| step | kind | do |
|
|
| key | flow | dever.crypto.token(32) |
|
|
| message | calc | dever.bytes.fromText(int.toText(value)) |
|
|
| first | calc | dever.crypto.hmacSha256(key, message) |
|
|
| second | calc | dever.crypto.hmacSha256(key, message) |
|
|
| - | check | dever.crypto.constantTimeEq(first, second) else Invalid |
|
|
| out | calc | value |
|
|
loop measure(n: Int) (out: Int)
|
|
| each value in range(0, n) | result |
|
|
| out | sum roundtrip(value) |
|
|
cmd bench = measure
|
|
'''
|
|
if language == 'rust':
|
|
return '''use bytes::Bytes;
|
|
use hmac::{Hmac, Mac};
|
|
use sha2::Sha256;
|
|
use subtle::ConstantTimeEq;
|
|
use zeroize::Zeroizing;
|
|
fn token(length: i64) -> Result<Zeroizing<Vec<u8>>, String> {
|
|
if !(16..=1024).contains(&length) { return Err("token length must be between 16 and 1024 bytes".into()); }
|
|
let mut key = Zeroizing::new(vec![0; length as usize]);
|
|
getrandom::getrandom(&mut key).map_err(|e| format!("secure random source unavailable: {e}"))?;
|
|
Ok(key)
|
|
}
|
|
fn sign(key: &[u8], message: &[u8]) -> Bytes {
|
|
let mut mac = Hmac::<Sha256>::new_from_slice(key).unwrap();
|
|
mac.update(message);
|
|
Bytes::copy_from_slice(&mac.finalize().into_bytes())
|
|
}
|
|
fn main() {
|
|
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
|
let mut out = 0i64;
|
|
for value in 0..n {
|
|
let key = token(32).unwrap();
|
|
let message = Bytes::from(value.to_string());
|
|
let first = sign(&key, &message);
|
|
let second = sign(&key, &message);
|
|
assert!(bool::from(first.ct_eq(&second)));
|
|
out = out.checked_add(value).unwrap();
|
|
}
|
|
println!("{out}");
|
|
}
|
|
'''
|
|
return '''package main
|
|
import ("crypto/rand"; "crypto/hmac"; "crypto/sha256"; "fmt"; "os"; "strconv")
|
|
func token(length int) []byte {
|
|
if length < 16 || length > 1024 { panic("invalid token length") }
|
|
key := make([]byte, length)
|
|
if _, err := rand.Read(key); err != nil { panic(err) }
|
|
return key
|
|
}
|
|
func sign(key, message []byte) []byte {
|
|
mac := hmac.New(sha256.New, key)
|
|
mac.Write(message)
|
|
return mac.Sum(nil)
|
|
}
|
|
func main() {
|
|
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
|
out := int64(0)
|
|
for value := int64(0); value < n; value++ {
|
|
key := token(32)
|
|
message := []byte(strconv.FormatInt(value, 10))
|
|
first, second := sign(key, message), sign(key, message)
|
|
if !hmac.Equal(first, second) { panic("HMAC mismatch") }
|
|
clear(key)
|
|
next := out + value; if next < out { panic("overflow") }; out = next
|
|
}
|
|
fmt.Println(out)
|
|
}
|
|
'''
|