use solana_hmac_drbg::HmacDrbg; use core::cmp::Ordering; pub fn rfc6979_generate( x: &[u8;32], n: &[u8;32], h: &[u8;32] ) -> [u8;32] { let mut hmac_drbg = HmacDrbg::new(x, h); loop { let mut k = [0u8;32]; hmac_drbg.fill_bytes(&mut k); let k_is_zero = &k.eq(&[0u8;32]); if !k_is_zero & matches!(k.cmp(&n), Ordering::Less) { return k; } } } #[cfg(test)] mod test { use crate::rfc6979_generate; // P-256 Test vectors copied from `rfc6979` crate. Remaining vectors generated by `rfc6979` crate. // NIST P-256 field modulus const NIST_P256_MODULUS: [u8; 32] = [0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51]; // SECP256K1 field modulus const SECP256K1_MODULUS: [u8; 32] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41]; // Arbitrary small modulus to prove multiple-round hashing works const LOW_MODULUS: [u8; 32] = [0x10;32]; // Private key for RFC6979 NIST P256/SHA256 test case const RFC6979_KEY: [u8; 32] = [0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, 0x57, 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12, 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21]; // Test message hash sha256("sample") for RFC6979 NIST P256/SHA256 test case const RFC6979_MSG_HASH: [u8; 32] = [0xaf, 0x2b, 0xdb, 0xe1, 0xaa, 0x9b, 0x6e, 0xc1, 0xe2, 0xad, 0xe1, 0xd6, 0x94, 0xf4, 0x1f, 0xc7, 0x1a, 0x83, 0x1d, 0x02, 0x68, 0xe9, 0x89, 0x15, 0x62, 0x11, 0x3d, 0x8a, 0x62, 0xad, 0xd1, 0xbf]; // Expected K value for K256 and P256 const RFC6979_EXPECTED_K: [u8; 32] = [0xa6, 0xe3, 0xc5, 0x7d, 0xd0, 0x1a, 0xbe, 0x90, 0x08, 0x65, 0x38, 0x39, 0x83, 0x55, 0xdd, 0x4c, 0x3b, 0x17, 0xaa, 0x87, 0x33, 0x82, 0xb0, 0xf2, 0x4d, 0x61, 0x29, 0x49, 0x3d, 0x8a, 0xad, 0x60]; // Expected K value for low modulus const RFC6979_EXPECTED_K_LOW: [u8; 32] = [0x0c, 0x21, 0x61, 0x73, 0x0a, 0x70, 0x22, 0x7d, 0xa5, 0x5c, 0x7d, 0x16, 0xdf, 0x1b, 0x6e, 0x13, 0x02, 0xe7, 0x51, 0xba, 0xb0, 0xca, 0xf7, 0x23, 0xff, 0x83, 0x0f, 0x7b, 0xa6, 0x0a, 0x30, 0xad]; #[test] pub fn test_secp256r1() { let result = rfc6979_generate(&RFC6979_KEY, &NIST_P256_MODULUS, &RFC6979_MSG_HASH); assert_eq!(result, RFC6979_EXPECTED_K) } #[test] pub fn test_secp256k1() { let result = rfc6979_generate(&RFC6979_KEY, &SECP256K1_MODULUS, &RFC6979_MSG_HASH); assert_eq!(result, RFC6979_EXPECTED_K) } #[test] pub fn test_low_modulus() { let result = rfc6979_generate(&RFC6979_KEY, &LOW_MODULUS, &RFC6979_MSG_HASH); assert_eq!(result, RFC6979_EXPECTED_K_LOW) } }