Category talk:Wren-crypto: Difference between revisions
Content added Content deleted
(→Source code: Bug fix.) |
(→Source code: Added Hmac class and Bytes.fromHexString method.) |
||
Line 45: | Line 45: | ||
static toIntLE(bytes) { bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24 } |
static toIntLE(bytes) { bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24 } |
||
// Converts a list of |
// Converts a list of an even number of bytes or the 4 bytes of a 32-bit unsigned integer |
||
// into |
// in big-endian format into a lower case hexadecimal string. |
||
static toHexString(bytes) { |
static toHexString(bytes) { |
||
if (bytes is Num) bytes = fromIntBE(bytes) |
if (bytes is Num) bytes = fromIntBE(bytes) |
||
Line 61: | Line 61: | ||
} |
} |
||
return res.join() |
return res.join() |
||
} |
|||
// Converts a lower case hexadecimal string into a byte list. |
|||
static fromHexString(hs) { |
|||
var digits = "0123456789abcdef" |
|||
var bytes = List.filled(hs.count/2, 0) |
|||
var i = 0 |
|||
while (i < hs.count-1) { |
|||
bytes[i/2] = digits.indexOf(hs[i]) * 16 + digits.indexOf(hs[i+1]) |
|||
i = i + 2 |
|||
} |
|||
return bytes |
|||
} |
} |
||
} |
} |
||
Line 540: | Line 552: | ||
return h0 + h1 + h2 + h3 + h4 |
return h0 + h1 + h2 + h3 + h4 |
||
} |
} |
||
} |
|||
/* Hmac implements the HMAC ('keyed-hash message authentication code') algorithm. */ |
|||
class Hmac { |
|||
// Computes the HMAC message digest of a byte sequence or string for a given key and class |
|||
// of cryptographic hashing algorithm with a specified block-size in bytes provided such class |
|||
// has a static digest(initBytes) method. |
|||
static digest(key, message, hashClass, blockSize) { |
|||
if (key is String) key = key.bytes.toList |
|||
if (message is String) message = message.bytes.toList |
|||
if (key.count > blockSize) key = Bytes.fromHexString(hashClass.digest(key)) |
|||
if (key.count < blockSize) key = key + [0] * (blockSize - key.count) |
|||
var outerKeyPad = key.map { |b| b ^ 0x5c }.toList |
|||
var innerKeyPad = key.map { |b| b ^ 0x36 }.toList |
|||
var innerHash = Bytes.fromHexString(hashClass.digest(innerKeyPad + message)) |
|||
return hashClass.digest(outerKeyPad + innerHash) |
|||
} |
|||
// Convenience version of the above method which assumes a block-size of 64 bytes |
|||
// and is true for all cryptographic hashing algorithms supported by this module. |
|||
static digest(key, message, hashClass) { digest(key, message, hashClass, 64) } |
|||
}</lang> |
}</lang> |