Skip to content

Commit aa8aaf2

Browse files
committed
Fix encoding of surrogate pairs to UTF-8
1 parent cab27b2 commit aa8aaf2

File tree

2 files changed

+36
-14
lines changed

2 files changed

+36
-14
lines changed

scrypt-async.js

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -297,21 +297,34 @@ function scrypt(password, salt, logN, r, dkLen, interruptStep, callback, encodin
297297
}
298298

299299
function stringToUTF8Bytes(s) {
300-
var arr = [];
301-
for (var i = 0; i < s.length; i++) {
302-
var c = s.charCodeAt(i);
303-
if (c < 128) {
304-
arr.push(c);
305-
} else if (c > 127 && c < 2048) {
306-
arr.push((c>>6) | 192);
307-
arr.push((c & 63) | 128);
308-
} else {
309-
arr.push((c>>12) | 224);
310-
arr.push(((c>>6) & 63) | 128);
311-
arr.push((c & 63) | 128);
312-
}
300+
var arr = [];
301+
for (var i = 0; i < s.length; i++) {
302+
var c = s.charCodeAt(i);
303+
if (c < 0x80) {
304+
arr.push(c);
305+
} else if (c < 0x800) {
306+
arr.push(0xc0 | c >> 6);
307+
arr.push(0x80 | c & 0x3f);
308+
} else if (c < 0xd800) {
309+
arr.push(0xe0 | c >> 12);
310+
arr.push(0x80 | (c >> 6) & 0x3f);
311+
arr.push(0x80 | c & 0x3f);
312+
} else {
313+
if (i >= s.length - 1) {
314+
throw new Error('invalid string');
315+
}
316+
i++; // get one more character
317+
c = (c & 0x3ff) << 10;
318+
c |= s.charCodeAt(i) & 0x3ff;
319+
c += 0x10000;
320+
321+
arr.push(0xf0 | c >> 18);
322+
arr.push(0x80 | (c >> 12) & 0x3f);
323+
arr.push(0x80 | (c >> 6) & 0x3f);
324+
arr.push(0x80 | c & 0x3f);
313325
}
314-
return arr;
326+
}
327+
return arr;
315328
}
316329

317330
function bytesToHex(p) {

test/unittests.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,15 @@ var inputs = [
5656
encoding: 'base64',
5757
result: 'FYjFuH0fb+qfG0Q0n5WFVQ=='
5858
},
59+
{
60+
password: '☺☻☹ abc 𝟘𝟙𝟚𝟛𝟜𝟝𝟞𝟟𝟠𝟡',
61+
salt: [1, 2, 3],
62+
logN: 10,
63+
r: 8,
64+
dkLen: 10,
65+
encoding: 'hex',
66+
result: 'd64f593e6c4e7a39913d'
67+
},
5968
{
6069
password: [104, 101, 108, 108, 111], // "hello"
6170
salt: [208, 188, 208, 184, 209, 128], // "мир"

0 commit comments

Comments
 (0)