Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Created December 4, 2021 19:28
Show Gist options
  • Save salrashid123/1c436f7895d103873eedfe914590ee99 to your computer and use it in GitHub Desktop.
Save salrashid123/1c436f7895d103873eedfe914590ee99 to your computer and use it in GitHub Desktop.
golang-jwt-tpm
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/golang-jwt/jwt"
tpmjwt "github.com/salrashid123/golang-jwt-tpm"
)
var ()
func main() {
ctx := context.Background()
var keyctx interface{}
claims := &jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Minute * 1).Unix(),
Issuer: "test",
}
// set override
tpmjwt.SigningMethodTPMRS256.Override()
token := jwt.NewWithClaims(tpmjwt.SigningMethodTPMRS256, claims)
config := &tpmjwt.TPMConfig{
TPMDevice: "/dev/tpm0",
KeyHandleFile: "key.bin",
KeyTemplate: tpmjwt.AttestationKeyParametersRSA256,
//KeyTemplate: tpmjwt.UnrestrictedKeyParametersRSA256,
}
keyctx, err := tpmjwt.NewTPMContext(ctx, config)
if err != nil {
log.Fatalf("Unable to initialize tpmJWT: %v", err)
}
token.Header["kid"] = config.GetKeyID()
tokenString, err := token.SignedString(keyctx)
if err != nil {
log.Fatalf("Error signing %v", err)
}
fmt.Printf("TOKEN: %s\n", tokenString)
// verify with TPM based publicKey
keyFunc, err := tpmjwt.TPMVerfiyKeyfunc(ctx, config)
if err != nil {
log.Fatalf("could not get keyFunc: %v", err)
}
vtoken, err := jwt.Parse(tokenString, keyFunc)
if err != nil {
log.Fatalf("Error verifying token %v", err)
}
if vtoken.Valid {
log.Println(" verified with TPM PublicKey")
}
// verify with provided RSAPublic key
pubKey := config.GetPublicKey()
v, err := jwt.Parse(vtoken.Raw, func(token *jwt.Token) (interface{}, error) {
return pubKey, nil
})
if v.Valid {
log.Println(" verified with exported PubicKey")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment