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

RangeError: Input buffers must have the same byte length #5

Open
alex996 opened this issue Feb 13, 2023 · 1 comment
Open

RangeError: Input buffers must have the same byte length #5

alex996 opened this issue Feb 13, 2023 · 1 comment

Comments

@alex996
Copy link

alex996 commented Feb 13, 2023

This library doesn't work with non-ASCII characters. Here's example code:

const tsse = require("tsse");

console.log("a".length, "ä".length); // 1 1
console.log(Buffer.from("a").length, Buffer.from("ä").length); // 1 2
console.log(tsse("a", "ä")); // RangeError

The problem is on this line:

if (hiddenStr.length !== inputStr.length) {

and these two lines:

const hiddenBuff = Buffer.from(hiddenStr);
const inputBuff = Buffer.from(inputStr);

This code works if both arguments are Buffers, because their length is the same as their byteLength, and Buffer.from simply creates a copy.

However, it doesn't work if the arguments are Strings. A string in JavaScript is encoded in UTF-16, so its length is the number of UTF-16 code units, rather than bytes. However, when you call Buffer.from(hiddenStr), the encoding defaults to utf8.

I think something like this would work better (I renamed hiddenStr and inputStr to hidden and input):

const hiddenLen = typeof hidden === "string" ? Buffer.byteLength(hidden) : hidden.length;
const inputLen = typeof input === "string" ? Buffer.byteLength(input) : input.length;

if (hiddenLen !== inputLen) {

Note how Buffer.byteLength(string) also defaults to utf8 encoding.

@simonepri
Copy link
Owner

Hi @alex996, thanks for opening an issue.

Could you please send a PR to fix this?
Thanks!

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