I'm creating a PKCE Code Verifier (a random string).
Solution 1 from a StackOverflow answer. (You can copy/paste these code examples into a browser's inspector.)
(function generateCodeVerifier() {
function dec2hex(dec) {
return ("0" + dec.toString(16)).substr(-2);
}
const len = 128;
var array = new Uint32Array( len / 2);
window.crypto.getRandomValues(array);
return Array.from(array, dec2hex).join("");
})()
Question
Why only use the last two hex characters of the numbers?
The following uses the full numbers from the array. Is it weaker than the first solution?
I do notice that the result length of the second solution can vary depending on whether the random numbers generate leading zeros.
Question: can I pad the result for cases where the length must be exact?
(function generateCodeVerifier2() {
const len = 128;
var array = new Uint32Array( len / 8);
window.crypto.getRandomValues(array);
return Array.from(array, x => x.toString(16)).join("");
})()