dchest / scrypt-async-js

Fast "async" scrypt implementation in JavaScript
http://dchest.github.io/scrypt-async-js/
BSD 2-Clause "Simplified" License
140 stars 26 forks source link

base64url encoding (url safe base64) #45

Closed wbartels closed 3 years ago

wbartels commented 3 years ago

It would be nice if base64url encoding can be added. Reference: https://www.ietf.org/rfc/rfc4648.txt

Encoding Replace + with - Replace / with _

var enc = ('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' +
    '0123456789-_').split('');

Delete the padding section:

if (len % 3 > 0) {
  arr[arr.length-1] = '=';
  if (len % 3 === 1) arr[arr.length-2] = '=';
}

Decoding: The padding can be reconstructed with the modulus 4 from the data length. Here is a PHP example:

function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
dchest commented 3 years ago

Base64 can be easily converted to Base64-URL with just derivedKey.replace(/\+/g, '-').replace(/\//g, '_') so I don't think this feature is worth it. (And padding can be stripped with .replace(/=/g, ''))

dchest commented 3 years ago

For better results, check out my @stablelib packages which have a better base64 encoder (including base64url) and an improved scrypt implementation.

wbartels commented 3 years ago

Thanks for the quick response and the suggested workaround! For my alternative login system I needs to send the result to the server. Then base64url encoding would be a good solution. But it is not big problem to use a hex output instead.