Search code examples
oauth-2.0pkce

How the code is computed in PKCE with S256


In the PKCE flow, a pseudorandom code is generated and encoded:

B90Xq7Y6UhxU0SC9VyS1jZOC24S-H0fg6ScxriFboubD5mu-

And then for S256 it is hashed and encoded via base64url(sha256(code)). This gives the result of:

G0rGJ_-MUvTJ0-qvJxBqRULT2unY5V8_hqvnMpDRbEA

How is this computed?

I am missing a step since the SHA256 of B90Xq7Y6UhxU0SC9VyS1jZOC24S-H0fg6ScxriFboubD5mu- is 1b4ac627ff8c52f4c9d3eaaf27106a4542d3dae9d8e55f3f86abe73290d16c40. And it can be already seen that the base64 of this string will not match: MWI0YWM2MjdmZjhjNTJmNGM5ZDNlYWFmMjcxMDZhNDU0MmQzZGFlOWQ4ZTU1ZjNmODZhYmU3MzI5MGQxNmM0MA.

See also: RFC 7636


For the record, this can get the correct value:

$ echo -n B90Xq7Y6UhxU0SC9VyS1jZOC24S-H0fg6ScxriFboubD5mu- | sha256sum | xxd -r -p | base64 | tr '/+' '_-' | tr -d '='
G0rGJ_-MUvTJ0-qvJxBqRULT2unY5V8_hqvnMpDRbEA

Solution

  • You're presenting 1b4ac627ff8c52f4c9d3eaaf27106a4542d3dae9d8e55f3f86abe73290d16c40 as the result of the SHA256 hash, but that is actually a hexadecimal encoding of the binary value of that hash. The binary value should be taken as input to the base64url encoding routine, not the hexadecimal encoding of it.