signature

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 17, 2023 License: MIT Imports: 11 Imported by: 1

README

Signature

Golang helper library to create JSON Web Signatures (JWS) for whatever use case you may think off. Some of the potential use cases are

  • Authorization tokens using public/private key.
  • File integrity checking for each individual.
  • Creating revision information and signing them to prevent tampering.
  • and so many other ideas ...

JWS is the basis for JWT and others that are derived from JWT. This libary ONLY generates and verifies the signature portion, not the payload. The payload checking is left to the application using this library, allowing it to offer more control on the payload validation.

Note on JWT or Oauth2

To generate a general JWT, create an instance of Signature and add the following fields

  • iss - issuer of the token.
  • iat - Unix timestamp (preferably in UTC) when this token was issued (OPTIONAL).
  • nbf - Unix timestamp (preferably in UTC) when this token can be used, should be equivalent or greater than iat (OPTIONAL).
  • exp - Unix timestamp (preferably in UTC) when this token expires.
  • sub - subject of the token.
  • aud - who is this token targetted to. jti - Unique identifier of THIS JWT (OPTIONAL).

To generate an Oauth2 token, create an instance of Signature and add the following fields

  • Use the above JWT as the base with iss, iat, exp, aud, sub and jti being REQUIRED.
  • client_id - public identifier of the application, unique in the scope of the application using it.
  • scope - space separated values indicating what the permission scope of this token is.

Usage

Generating signature

Generating a signature requires either an RSA, ECDSA or ED25519 private key.


// `RSA`, `ECDSA` or `ED25519` raw private key already exists
sig, err := signature.New(privateKey)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}

sig.Set("iss", "issuer")
sig.Set("clientId", "randomid")

hashed := sha256.Sum256([]byte("hello world"))
sig.Set("hash", hex.EncodeToString(hashed[:]))

type example struct {
    Key   string `json:"key"`
    Value string `json:"value"`
}

var e example
e.Key = "bingo"
e.Value = "book"

sig.Set("myvalue", e)

signed, err := sig.Generate()
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}
fmt.Println(string(signed))

Verifying signature

Generating a signature requires either an RSA, ECDSA or ED25519 public key.


// `RSA`, `ECDSA` or `ED25519` public key already exists

sig, err := signature.New(publicKey)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}

// the signed value in bytes
payload, err := sig.Verify(signed)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}
fmt.Println(string(payload))

Generating JWT
// `RSA`, `ECDSA` or `ED25519` keys already exists
myjwt, err := NewTokenJWT(privateKey)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}

myjwt.SetIssuedAt(time.Now().Add(time.Hour))
myjwt.SetExpiry(time.Hour * 2)

myjwt.SetIssuer("jwt-memyselfi")
myjwt.SetTokenIdentifier("jwt-1234567890")
myjwt.SetAudience("jwt-coolremoteserver")
myjwt.SetSubject("jwt-iamtheissuer")

sig, err := myjwt.Generate()
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}
fmt.Println(string(sig))

s, err := New(publicKey)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}

payload, err := s.Verify(sig)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}
fmt.Println(string(payload))

Generating Oauth2
// `RSA`, `ECDSA` or `ED25519` keys already exists

oa, err := NewTokenOAuth2(privateKey)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}

oa.SetIssuedAt(time.Now().Add(time.Hour))
oa.SetExpiry(time.Hour * 2)

oa.SetIssuer("memyselfi")
oa.SetTokenIdentifier("1234567890")
oa.SetAudience("coolremoteserver")
oa.SetSubject("iamtheissuer")
oa.SetClientID("thematrix")

sig, err := oa.Generate()
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}
fmt.Println(string(sig))

s, err := New(publicKey)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}

payload, err := s.Verify(sig)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}
fmt.Println(string(payload))

Reading PEM encoded public/private keys into Signature instance

Helper function to read a public/private key encoded in PEM format into Signature instance. Supports both PKCS#1 or PKCS#8 format


// keyBytes are the bytes of PEM contents
sig, err := signature.ParsePEM(keyBytes, nil)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}

// returns an instance of Signature for use in the application

Reading JWK JSON encoded public/private keys into Signature instance

Helper function to read a public/private key encoded in JWK JSON string format into Signature instance.


// keyBytes are the bytes of the JSON string
key, err := signature.ParseJWK(keyBytes, nil)
if nil != err {
    fmt.Println(err)
    os.Exit(1)
}

// returns an instance of Signature for use in the application

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Key added in v1.2.0

type Key shared.Key

type Signature

type Signature struct {
	// contains filtered or unexported fields
}

Signature - structure for managing singing information

func New

func New(rawkey interface{}) (s *Signature, err error)

New - creates new instance of signature for generation or verification

func ParseJWK

func ParseJWK(jsonBytes []byte) (signature *Signature, err error)

ParseJWK - parses JWK JSON encoded bytes into a key

func ParsePEM

func ParsePEM(pemBytes, password []byte) (signature *Signature, err error)

ParsePEM - parses PEM encoded bytes into a key

func (*Signature) Generate

func (s *Signature) Generate() (signed []byte, err error)

Generate - generates a signature

func (*Signature) Set

func (s *Signature) Set(key string, value interface{})

Set - sets a key for signing

func (*Signature) Verify

func (s *Signature) Verify(signed []byte) (payload []byte, err error)

Verify - verifies a signature

type TokenJWT added in v1.2.0

type TokenJWT struct {
	// contains filtered or unexported fields
}

func NewTokenJWT added in v1.2.0

func NewTokenJWT(rawkey interface{}) (tokenJWT *TokenJWT, err error)

NewTokenJWT - creates a token in JWT format

func (*TokenJWT) Generate added in v1.2.0

func (tokenJWT *TokenJWT) Generate() (sig []byte, err error)

Generate - generates a usable JWT token, for verifying load the accompanying public key into Signature and use the Verify function

func (*TokenJWT) Set added in v1.2.0

func (tokenJWT *TokenJWT) Set(key string, value interface{})

func (*TokenJWT) SetAudience added in v1.2.0

func (tokenJWT *TokenJWT) SetAudience(aud string)

func (*TokenJWT) SetExpiry added in v1.2.0

func (tokenJWT *TokenJWT) SetExpiry(exp time.Duration)

func (*TokenJWT) SetIssuedAt added in v1.2.0

func (tokenJWT *TokenJWT) SetIssuedAt(iat time.Time)

SetIssuedAt - set the issued at field, by default the not before will batch iat. if replacing nbf with a newer value, call SetNotBefore after this function

func (*TokenJWT) SetIssuer added in v1.2.0

func (tokenJWT *TokenJWT) SetIssuer(iss string)

func (*TokenJWT) SetNotBefore added in v1.2.0

func (tokenJWT *TokenJWT) SetNotBefore(nbf time.Time)

func (*TokenJWT) SetScope added in v1.2.0

func (tokenJWT *TokenJWT) SetScope(scope string)

func (*TokenJWT) SetSubject added in v1.2.0

func (tokenJWT *TokenJWT) SetSubject(sub string)

func (*TokenJWT) SetTokenIdentifier added in v1.2.0

func (tokenJWT *TokenJWT) SetTokenIdentifier(tokenid string)

type TokenOAuth2

type TokenOAuth2 struct {
	// contains filtered or unexported fields
}

func NewTokenOAuth2 added in v1.2.0

func NewTokenOAuth2(rawkey interface{}) (tokenOAuth2 *TokenOAuth2, err error)

NewTokenOAuth2 - creates a token in OAuth2 format

func (*TokenOAuth2) Generate added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) Generate() (sig []byte, err error)

Generate - generates a usable OAuth2 token, for verifying load the accompanying public key into Signature and use the Verify function

func (*TokenOAuth2) Set added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) Set(key string, value interface{})

func (*TokenOAuth2) SetAudience added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) SetAudience(aud string)

func (*TokenOAuth2) SetClientID added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) SetClientID(clientid string)

func (*TokenOAuth2) SetExpiry added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) SetExpiry(exp time.Duration)

func (*TokenOAuth2) SetIssuedAt added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) SetIssuedAt(iat time.Time)

SetIssuedAt - set the issued at field, by default the not before will batch iat. if replacing nbf with a newer value, call SetNotBefore after this function

func (*TokenOAuth2) SetIssuer added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) SetIssuer(iss string)

func (*TokenOAuth2) SetNotBefore added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) SetNotBefore(nbf time.Time)

func (*TokenOAuth2) SetScope added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) SetScope(scope string)

func (*TokenOAuth2) SetSubject added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) SetSubject(sub string)

func (*TokenOAuth2) SetTokenIdentifier added in v1.2.0

func (tokenOAuth2 *TokenOAuth2) SetTokenIdentifier(tokenid string)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL