Refactored XOR.js to call replace once (#221)

* Refactored to make 1 call to `replace`

Now it's optimized and refactored to replace the same chars as before and leave other chars intact. The `s` (dot-all) flag is used to reduce conditional branching

* Fixed syntax error
This commit is contained in:
Ricardo Fernández Serrata 2022-05-07 21:10:43 -04:00 committed by GitHub
parent b2320d3c9c
commit 862f9d7e11
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,5 +1,5 @@
module.exports = class XOR {
xor(str, key) { return String.fromCodePoint(...str.split('').map((char, i) => char.charCodeAt(0) ^ key.toString().charCodeAt(i % key.toString().length))) }
encrypt(str, key = 37526) { return Buffer.from(this.xor(str, key)).toString('base64').replace(/\//g, '_').replace(/\+/g, '-'); }
decrypt(str, key = 37526) { return this.xor(Buffer.from(str.replace(/\//g, '_').replace(/\+/g, '-'), 'base64').toString(), key) }
}
encrypt(str, key = 37526) { return Buffer.from(this.xor(str, key)).toString('base64').replace(/./gs, c => ({'/': '_', '+': '-'}[c] || c)); }
decrypt(str, key = 37526) { return this.xor(Buffer.from(str.replace(/./gs, c => ({'/': '_', '+': '-'}[c] || c)), 'base64').toString(), key) }
}