How to hash SHA256 from string?
user1234
user1234 at 12.de
Sat Dec 2 16:17:08 UTC 2023
On Saturday, 2 December 2023 at 15:30:39 UTC, zoujiaqing wrote:
> ```D
> import std.stdio;
> import std.digest.sha;
>
> void main()
> {
>
> SHA256 sha256;
> sha256.start();
> string appKey =
> "11111111111111111111111111111111111111111111111111111";
> ubyte[1024] data = cast(ubyte[])(appKey.dup[0..$]);
> sha256.put(data);
> ubyte[32] sign = sha256.finish();
>
> string sign1 = cast(string) sign[0..$];
> writeln("sign: %s", sign1);
> }
> ```
>
> The result varies when you run the code repeatedly and the
> display is garbled:
> ```
> zoujiaqing at mac test % ./test
> Getui access sign: %s>tM?a?j,???ߥm?8l~??uzU?|9?~ˡ
> zoujiaqing at mac test % ./test
> Getui access sign: %s1-??U?
> ?d<3^3??נ? ??P%u/Iv
> zoujiaqing at mac test % ./test
> Getui access sign: %s1?ϻN?????ށ?`O?p!?O?4U
> :8J~%ʬ
> zoujiaqing at mac test % ./test
> Getui access sign: %s??????k#O?;?ڋ?5T?"=??;???e
> ```
sign is binary, you have to use the toHexString utility :
```d
import std.stdio;
import std.digest.sha;
void main()
{
SHA256 sha256;
sha256.start();
string appKey =
"11111111111111111111111111111111111111111111111111111";
sha256.put(cast(ubyte[])appKey);
ubyte[32] sign = sha256.finish();
writeln("sign: %s", toHexString(sign));
}
```
also you add a range error on data assignment.
More information about the Digitalmars-d-learn
mailing list