Created
April 25, 2023 23:20
-
-
Save john-yuan/17fb050526e6c49739f87971894be8de to your computer and use it in GitHub Desktop.
Golang HS256. An example to encode jwt with HS256 in golang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/hmac" | |
"crypto/sha256" | |
"encoding/base64" | |
"encoding/hex" | |
"fmt" | |
) | |
func HS256(data, key []byte) []byte { | |
h := hmac.New(sha256.New, key) | |
h.Write(data) | |
return h.Sum(nil) | |
} | |
func main() { | |
key, _ := hex.DecodeString("412b0d8f10fb2bb46ae06e869caf2c90") | |
data := []byte("the message to sign") | |
bytes := HS256(data, key) | |
fmt.Println(base64.RawURLEncoding.EncodeToString(bytes)) | |
// gkb5qQ5MyYhNEyfUIsk0PquMRQz7h_wd4u4jpyBoSfg | |
// JWT | |
rawHeader := `{"alg":"HS256","typ":"JWT"}` | |
rawPayload := `{"sub":"1234567890","name":"John Doe","iat":1516239022}` | |
textSecret := "your-256-bit-secret" | |
header := base64.RawURLEncoding.EncodeToString([]byte(rawHeader)) | |
payload := base64.RawURLEncoding.EncodeToString([]byte(rawPayload)) | |
signature := HS256( | |
[]byte(fmt.Sprintf("%v.%v", header, payload)), | |
[]byte(textSecret), | |
) | |
jwt := fmt.Sprintf( | |
"%v.%v.%v", | |
header, | |
payload, | |
base64.RawURLEncoding.EncodeToString(signature), | |
) | |
fmt.Println(jwt) | |
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment