How to calculate PCKE's code_verifier?

前端 未结 2 1734
栀梦
栀梦 2021-01-19 23:14

I\'m going through Okta\'s PCKE Flow demo to get a better understanding of how it works, and I\'m having trouble reproducing the same code_challenge hash that\'

2条回答
  •  礼貌的吻别
    2021-01-19 23:38

    Based on Aaron's example and hacking the pkce-challenge node package, here's what I use:

    class PkceChallenge {
        random(length, mask) {
            let result = "";
            let randomIndices = new Int8Array(length);
            window.crypto.getRandomValues(randomIndices);
            const byteLength = 256
            const maskLength = Math.min(mask.length, byteLength);
            const scalingFactor = byteLength / maskLength;
    
            for (var i = 0; i < length; i++) {
                result += mask[Math.floor(Math.abs(randomIndices[i]) / scalingFactor)];
            }
            return result;
        }
    
        base64UrlEncode(array) {
            return btoa(String.fromCharCode.apply(null, new Uint8Array(array)))
                .replace(/\+/g, '-')
                .replace(/\//g, '_')
                .replace(/=+$/, '');
        }
    
        generateVerifier(length) {
            const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
            return this.random(length, mask);
        }
    
        generateChallenge(length = 43) {
            this.verifier = this.generateVerifier(length);
    
            const encoder = new TextEncoder();
            const data = encoder.encode(this.verifier);
            return window.crypto.subtle.digest('SHA-256', data).then(array => { return { code_challenge: this.base64UrlEncode(array), code_verifier: this.verifier }; });
        }
    }
    

提交回复
热议问题