rustls/
prf.rs

1use ring::digest;
2use ring::hmac;
3
4use std::io::Write;
5
6fn convert_digest_to_hmac_alg(hash: &'static digest::Algorithm) -> hmac::Algorithm {
7    if hash == &digest::SHA256 {
8        hmac::HMAC_SHA256
9    } else if hash == &digest::SHA384 {
10        hmac::HMAC_SHA384
11    } else if hash == &digest::SHA512 {
12        hmac::HMAC_SHA512
13    } else {
14        panic!("bad digest for prf");
15    }
16}
17
18fn concat_sign(key: &hmac::Key, a: &[u8], b: &[u8]) -> hmac::Tag {
19    let mut ctx = hmac::Context::with_key(key);
20    ctx.update(a);
21    ctx.update(b);
22    ctx.sign()
23}
24
25fn p(out: &mut [u8], hashalg: &'static digest::Algorithm, secret: &[u8], seed: &[u8]) {
26    let hmac_key = hmac::Key::new(convert_digest_to_hmac_alg(hashalg), secret);
27
28    // A(1)
29    let mut current_a = hmac::sign(&hmac_key, seed);
30
31    let mut offs = 0;
32
33    while offs < out.len() {
34        // P_hash[i] = HMAC_hash(secret, A(i) + seed)
35        let p_term = concat_sign(&hmac_key, current_a.as_ref(), seed);
36        offs += out[offs..]
37            .as_mut()
38            .write(p_term.as_ref())
39            .unwrap();
40
41        // A(i+1) = HMAC_hash(secret, A(i))
42        current_a = hmac::sign(&hmac_key, current_a.as_ref());
43    }
44}
45
46fn concat(a: &[u8], b: &[u8]) -> Vec<u8> {
47    let mut ret = Vec::new();
48    ret.extend_from_slice(a);
49    ret.extend_from_slice(b);
50    ret
51}
52
53pub fn prf(
54    out: &mut [u8],
55    hashalg: &'static digest::Algorithm,
56    secret: &[u8],
57    label: &[u8],
58    seed: &[u8],
59) {
60    let joined_seed = concat(label, seed);
61    p(out, hashalg, secret, &joined_seed);
62}
63
64#[cfg(test)]
65mod tests {
66    use ring::digest::{SHA256, SHA512};
67
68    #[test]
69    fn check_sha256() {
70        let secret = b"\x9b\xbe\x43\x6b\xa9\x40\xf0\x17\xb1\x76\x52\x84\x9a\x71\xdb\x35";
71        let seed = b"\xa0\xba\x9f\x93\x6c\xda\x31\x18\x27\xa6\xf7\x96\xff\xd5\x19\x8c";
72        let label = b"test label";
73        let expect = include_bytes!("testdata/prf-result.1.bin");
74        let mut output = [0u8; 100];
75
76        super::prf(&mut output, &SHA256, secret, label, seed);
77        assert_eq!(expect.len(), output.len());
78        assert_eq!(expect.to_vec(), output.to_vec());
79    }
80
81    #[test]
82    fn check_sha512() {
83        let secret = b"\xb0\x32\x35\x23\xc1\x85\x35\x99\x58\x4d\x88\x56\x8b\xbb\x05\xeb";
84        let seed = b"\xd4\x64\x0e\x12\xe4\xbc\xdb\xfb\x43\x7f\x03\xe6\xae\x41\x8e\xe5";
85        let label = b"test label";
86        let expect = include_bytes!("testdata/prf-result.2.bin");
87        let mut output = [0u8; 196];
88
89        super::prf(&mut output, &SHA512, secret, label, seed);
90        assert_eq!(expect.len(), output.len());
91        assert_eq!(expect.to_vec(), output.to_vec());
92    }
93}