incorrect data when returning static array in place of dynamic
sigod via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jul 5 11:57:44 PDT 2015
Consider this code:
```
import std.digest.digest;
import std.stdio;
ubyte[] hmac_sha1(const(ubyte)[] key, const(ubyte)[] message)
{
import std.digest.sha;
enum block_size = 64;
if (key.length > block_size)
key = sha1Of(key);
if (key.length < block_size)
key.length = block_size;
ubyte[] o_key_pad = key.dup;
ubyte[] i_key_pad = key.dup;
o_key_pad[] ^= 0x5c;
i_key_pad[] ^= 0x36;
sha1Of(o_key_pad ~ sha1Of(i_key_pad ~
message)).toHexString.writeln; // prints correct string
return sha1Of(o_key_pad ~ sha1Of(i_key_pad ~ message));
}
void main()
{
hmac_sha1(cast(ubyte[])"", cast(ubyte[])"").toHexString.writeln;
// incorrect
"---".writeln;
hmac_sha1(cast(ubyte[])"key", cast(ubyte[])"The quick brown fox
jumps over the lazy dog").toHexString.writeln;
}
```
prints:
```
FBDB1D1B18AA6C08324B7D64B71FB76370690E1D
0000000018AA6C081400000038FD180010000000
---
DE7C9B85B8B78AA6BC8A7A36F70A90701C9DB4D9
00000000B8B78AA61400000038FD180010000000
```
Why does function return incorrect data? Using `.dup` in return
expression or using `ubyte[20]` as return type fixes problem, but
why?
More information about the Digitalmars-d-learn
mailing list