feat: bootstrap moon-i2p core protocol foundation
This commit is contained in:
commit
e527b84bc3
47 files changed
+5350
No files matched your search
@@ -0,0 +1,80 @@
|
||||
///|
|
||||
/// Computes HMAC-SHA256 (RFC 2104 / RFC 4231).
|
||||
pub fn hmac_sha256(key : Bytes, data : Bytes) -> Bytes {
|
||||
let block_key = FixedArray::make(64, b'\x00')
|
||||
let effective_key = if key.length() > 64 { sha256(key) } else { key }
|
||||
for i = 0; i < effective_key.length(); i = i + 1 {
|
||||
block_key[i] = effective_key[i]
|
||||
}
|
||||
let ipad = FixedArray::make(64, b'\x00')
|
||||
let opad = FixedArray::make(64, b'\x00')
|
||||
for i = 0; i < 64; i = i + 1 {
|
||||
ipad[i] = (block_key[i].to_int() ^ 0x36).to_byte()
|
||||
opad[i] = (block_key[i].to_int() ^ 0x5c).to_byte()
|
||||
}
|
||||
let inner = Sha256::new()
|
||||
inner.update(Bytes::from_array(ipad))
|
||||
inner.update(data)
|
||||
let inner_digest = inner.finalize()
|
||||
|
||||
let outer = Sha256::new()
|
||||
outer.update(Bytes::from_array(opad))
|
||||
outer.update(inner_digest)
|
||||
outer.finalize()
|
||||
}
|
||||
|
||||
///|
|
||||
/// HKDF-Extract (RFC 5869) using SHA-256.
|
||||
pub fn hkdf_extract(salt : Bytes, ikm : Bytes) -> Bytes {
|
||||
let actual_salt = if salt.length() == 0 {
|
||||
Bytes::make(32, b'\x00')
|
||||
} else {
|
||||
salt
|
||||
}
|
||||
hmac_sha256(actual_salt, ikm)
|
||||
}
|
||||
|
||||
///|
|
||||
/// HKDF-Expand (RFC 5869) using SHA-256.
|
||||
pub fn hkdf_expand(
|
||||
prk : Bytes,
|
||||
info : Bytes,
|
||||
length : Int32,
|
||||
) -> Bytes raise CryptoError {
|
||||
if length < 0 || length > 255 * 32 {
|
||||
raise InvalidLength("HKDF-Expand output length out of range: \{length}")
|
||||
}
|
||||
if length == 0 {
|
||||
return b""
|
||||
}
|
||||
let n = (length + 31) / 32
|
||||
let out : Array[Byte] = Array(capacity=length)
|
||||
let mut prev : Bytes = b""
|
||||
for i = 1; i <= n; i = i + 1 {
|
||||
let msg : Array[Byte] = Array(capacity=prev.length() + info.length() + 1)
|
||||
for j = 0; j < prev.length(); j = j + 1 {
|
||||
msg.push(prev[j])
|
||||
}
|
||||
for j = 0; j < info.length(); j = j + 1 {
|
||||
msg.push(info[j])
|
||||
}
|
||||
msg.push(i.to_byte())
|
||||
prev = hmac_sha256(prk, Bytes::from_array(msg))
|
||||
for j = 0; j < prev.length() && out.length() < length; j = j + 1 {
|
||||
out.push(prev[j])
|
||||
}
|
||||
}
|
||||
Bytes::from_array(out)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Full HKDF-SHA256 (Extract + Expand, RFC 5869).
|
||||
pub fn hkdf(
|
||||
salt : Bytes,
|
||||
ikm : Bytes,
|
||||
info : Bytes,
|
||||
length : Int32,
|
||||
) -> Bytes raise CryptoError {
|
||||
let prk = hkdf_extract(salt, ikm)
|
||||
hkdf_expand(prk, info, length)
|
||||
}
|
||||
Reference in new issue
Block a user