go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/encryptedcookies/internal/pkce.go (about) 1 // Copyright 2021 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package internal 16 17 import ( 18 "crypto/rand" 19 "crypto/sha256" 20 "encoding/base64" 21 "fmt" 22 ) 23 24 // GenerateCodeVerifier generates a random string used as a code_verifier in 25 // the PKCE protocol. 26 // 27 // See https://tools.ietf.org/html/rfc7636. 28 func GenerateCodeVerifier() string { 29 blob := make([]byte, 50) 30 if _, err := rand.Read(blob); err != nil { 31 panic(fmt.Sprintf("failed to generate code verifier: %s", err)) 32 } 33 // Note: there are exactly 64 symbols here. We exclude technically allowed '_' 34 // and '~' to simplify random number processing below needed to get fair 35 // distribution of probabilities. 36 const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-." 37 for i := range blob { 38 blob[i] = alphabet[blob[i]&63] 39 } 40 return string(blob) 41 } 42 43 // DeriveCodeChallenge derives code_challenge from the code_verifier. 44 func DeriveCodeChallenge(codeVerifier string) string { 45 codeVerifierS256 := sha256.Sum256([]byte(codeVerifier)) 46 return base64.RawURLEncoding.EncodeToString(codeVerifierS256[:]) 47 }