Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement