Skip to content

Instantly share code, notes, and snippets.

@fat4lix
Last active September 9, 2019 17:43
Show Gist options
  • Select an option

  • Save fat4lix/b99b0ed71317828bbe755adf927a9212 to your computer and use it in GitHub Desktop.

Select an option

Save fat4lix/b99b0ed71317828bbe755adf927a9212 to your computer and use it in GitHub Desktop.
package auth
import (
"crypto/rsa"
"errors"
"fmt"
"golang.org/x/crypto/ssh"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
"io/ioutil"
"log"
"os"
"path"
"time"
)
type JwtPayload = struct {
ID string
Role string
Permission []string
}
type JwtClaims = struct {
jwt.Claims
JwtPayload
}
func parseKey(rsaKeyLocation string) (*rsa.PrivateKey, error) {
key, err := ioutil.ReadFile(rsaKeyLocation)
if err != nil {
log.Print("No RSA private Key found")
return nil, errors.New("No RSA private Key found")
}
parseResult, err := ssh.ParseRawPrivateKey(key)
if err != nil{
log.Print(err)
return nil, errors.New("Error while parsing pem file")
}
privateKey := parseResult.(*rsa.PrivateKey)
return privateKey, nil
}
func makeKeyPath(name string) (string, error) {
currentDir, err := os.Getwd()
if err != nil {
return "", err
}
return path.Join(currentDir, name), nil
}
type Hour = int32
func Encrypt(payload JwtPayload, expiresIn Hour) (string, error) {
keyPath, _ := makeKeyPath("auth.pem")
privateKey, err := parseKey(keyPath)
if err != nil {
panic(err)
}
encrypter, err := jose.NewEncrypter(
jose.A128GCM,
jose.Recipient{Algorithm: jose.RSA_OAEP, Key: &privateKey.PublicKey},
(&jose.EncrypterOptions{}).WithType("JWT"),
)
if err != nil {
panic(err)
}
claims := JwtClaims{
Claims: jwt.Claims{
Subject: "DOQA",
Issuer: "DOQA",
Expiry: jwt.NewNumericDate(time.Now().Add(time.Hour * time.Duration(expiresIn))),
},
JwtPayload: payload,
}
token, err := jwt.Encrypted(encrypter).Claims(claims).CompactSerialize()
if err != nil {
panic(err)
}
return token, nil
}
func Decrypt(token string) *JwtPayload {
keyPath, _ := makeKeyPath("auth.pem")
privateKey, err := parseKey(keyPath)
if err != nil {
panic(err)
}
object, err := jwt.ParseEncrypted(token)
if err != nil {
panic(err)
}
decoded := &JwtPayload{}
_ = object.Claims(privateKey, decoded)
return decoded
}
func Test() {
payloadIn := JwtPayload{
ID: "1",
Role: "test",
Permission: []string{"Penn", "Teller"},
}
token, _ := Encrypt(payloadIn, 5)
fmt.Printf("Token: %s\n\n", token)
object, err := jwt.ParseEncrypted(token)
if err != nil {
fmt.Println(err)
}
encClaims := JwtPayload{}
_ = object.Claims(&encClaims)
fmt.Printf("Parse ecnrypted: %+v\n\n", encClaims)
payload := Decrypt(token)
fmt.Printf("%+v\n\n", payload)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment