Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sha256 not working for national characters #300

Closed
beastybeast opened this issue Sep 26, 2015 · 2 comments
Closed

sha256 not working for national characters #300

beastybeast opened this issue Sep 26, 2015 · 2 comments

Comments

@beastybeast
Copy link

Hi

The example for sha256 does not work with for example Danish characters as 'æøå'

function sha256(text)
{
var md = forge.md.sha256.create();
md.update(text);
return md.digest().toHex();
}

It produce the wrong hash compared to online sources and the PHP hash function.

This may be related to some UTF-8 issues as

function sha256(text)
{
var md = forge.md.sha256.create();
md.update(forge.util.encodeUtf8(text));
return md.digest().toHex();
}

Works fine!

Just think that this is relevant for a lot of people ;-)

@dlongley
Copy link
Member

Forge 0.6.x was written prior to TypedArray support in browsers, so its buffers use a string to internally represent arrays of bytes (this is the same format that node.js uses with its binary string encoding). Note that this has nothing to do with representing characters. This is a common misunderstanding with forge -- one that we're aiming to entirely avoid in forge 0.7.x (WIP) by requiring the use of forge buffers to work with binary data. Unfortunately, this binary string abstraction is too leaky in forge 0.6.x and you sometimes have to unnecessarily understand how it works.

So, md.update accepts a string, but, by default, it assumes the encoding of that string is binary aka raw. In order to treat it like a regular string of characters, you must pass the encoding as utf8 which will cause forge to convert the string of characters to a UTF-8 binary representation instead. You can do this by calling:

md.update(msg, 'utf8');

You can get the exact same effect by doing what you did above:

md.update(forge.util.encodeUtf8(text));

In forge 0.7.x, you will have to use a forge buffer in order to work with binary data, which should help avoid a lot of the confusion.

@dlongley
Copy link
Member

See #203.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants