Skip to content

Disallow non-hex characters in fromHex #1975

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

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Prev Previous commit
Next Next commit
consistency with ../Base64.mjs
removeNonAlphChars and strictMode params
wjaaaaaaat authored Feb 17, 2025
commit d9fb3e28dd9226cd8fada435667c794f0eff7e7f
7 changes: 5 additions & 2 deletions src/core/lib/Hex.mjs
Original file line number Diff line number Diff line change
@@ -100,10 +100,13 @@
* // returns [10,20,30]
* fromHex("0a:14:1e", "Colon");
*/
export function fromHex(data, delim="Auto", byteLen=2, strict=False) {
export function fromHex(data, delim="Auto", byteLen=2, removeNonAlphChars=false, strictMode=false) {
if (byteLen < 1 || Math.round(byteLen) !== byteLen)
throw new OperationError("Byte length must be a positive integer");

if (removeNonAlphChars)
data = data.replace(/[^\da-fA-F]/g, '');

Check failure on line 108 in src/core/lib/Hex.mjs

GitHub Actions / main

Strings must use doublequote

Check warning on line 109 in src/core/lib/Hex.mjs

GitHub Actions / main

Trailing spaces not allowed
if (delim !== "None") {
const delimRegex = delim === "Auto" ? /\s+|0x/gi : Utils.regexRep(delim);
data = data.split(delimRegex);
@@ -113,7 +116,7 @@

const output = [];
for (let i = 0; i < data.length; i++) {
if (/[^a-f\d\s]/.test(data[i]) && strict)
if (/[^a-f\d\s]/.test(data[i]) && strictMode)
throw new OperationError("Hex input must only contain hex digits");
for (let j = 0; j < data[i].length; j += byteLen) {
output.push(parseInt(data[i].substr(j, byteLen), 16));