bitcoinjs-lib
bitcoinjs-lib copied to clipboard
Crypto module behavior changed when switching to noble for people using incorrect types like string.
Hello,
Was running into an issue where the use of the sha256 method coming from bitcoinjs.crypto.sha256, where a hash for the same data is different when the expected behavior was to get a consistent result, here is a simple snippet code to reproduce:
(async () => {
let data = "hello";
let hashed = bitcoinjs.crypto.sha256(data);
console.log(hashed.toString("hex"));
})();
Video demonstrating the behavior:
https://github.com/bitcoinjs/bitcoinjs-lib/assets/25140579/cf3bbce6-a51d-4b5f-ad42-fe03e767ca49
tried reflecting generating the hash on totally another programming language to see which is the correct, which was the one generated in version 6.1.0, and so version 6.1.5 generates an incorrect or miscalculated hash.
I don't know what is the exact version where this start to happen, However, I am pretty sure that this is unexpected behavior that deserves a look.
The interface provided expects a Buffer for input (as shown by the TypeScript and its type definitions).
This change is caused by the internal usage of Uint8Array.from(data) which will change the behavior when data is a string.
> Buffer.from("hello")
<Buffer 68 65 6c 6c 6f>
> Uint8Array.from("hello")
Uint8Array(5) [ 0, 0, 0, 0, 0 ]
If you make sure to use Buffer.from before passing in a string you will be fine.
...
Add a runtime check and throw if not Buffer. OR add an extra Buffer.from inside the function to maintain backwards compatibility with the unintended usage...
What do you think is better?
@junderw This sounds good. "add an extra Buffer.from inside the function to maintain backwards compatibility with the unintended usage"