signature

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

README

go-signature

GitHub tag (latest SemVer) Go Reference License

Tests CodeQL Analysis GolangCI Lint Go Report Card

Just a small library to get a signed string with a payload. It helps me to create confirmation tokens without using database.

Don't use this library to protect sensitive data!

Features

  • Data Integrity: Ensures that the data remains unchanged and secure during transit.
  • Simplified Token Structure: Generates tokens without the overhead of JWT headers, focusing solely on payload and signature.
  • Flexibility and Ease of Use: Provides a straightforward API to work with, requiring minimal setup to sign and verify data.

Usage

Installation:
go get -u github.com/dmitrymomot/go-signature/v2
Example:

Use the Signer to sign some predefined data type and parse the token back to the original data.

package main

import (
	"fmt"

	"github.com/dmitrymomot/go-signature/v2"
)

// Define a struct to sign. Or use any other data type you want.
type example struct {
	ID    uint64
	Email string
}

func main() {
	// Create a new signer
	s := signature.NewSigner[example]([]byte("signing-key"))

	// Sign and parse a token
	token, err := s.Sign(example{ID: 123, Email: "test123"})
	if err != nil {
		panic(err)
	}
	fmt.Println(token)

	// Parse a token and print the data
	data, err := s.Parse(token)
	if err != nil {
		panic(err)
	}
	fmt.Println(data)
}

Output:

eyJwIjp7IklEIjoxMjMsIkVtYWlsIjoidGVzdDEyMyJ9fQ.Mjg1MDVkOTNjNTdkNDhjMjk2NWQxOWZhNGY3ZDU2ZjQ3NWFlNWUxYw

{123 test123}

You can find this example in the example/main.go file.

Using of functions directly

You can use the NewToken and ParseToken functions directly without creating a new signer.

package main

import (
    "fmt"

    "github.com/dmitrymomot/go-signature/v2"
)

func main() {
    signingKey := []byte("signing-key")
    someData := "some data"

    token, err := signature.NewToken(signingKey, someData, 0, signature.CalculateHmac)
    if err != nil {
        panic(err)
    }
    fmt.Println(token)

    // Parse a token and print the data. You need to know the type of the data to parse it.
    data, err := signature.ParseToken[string](signingKey, token, signature.CalculateHmac, signature.ValidateHmac)
    if err != nil {
        panic(err)
    }
    fmt.Println(data)
}

License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidSignature           = errors.New("invalid signature")
	ErrorCalculatingHmac          = errors.New("error calculating hmac")
	ErrFailedToMarshalTokenClaims = errors.New("failed to marshal token claims")
	ErrInvalidToken               = errors.New("invalid token")
	ErrTokenExpired               = errors.New("token expired")
	ErrInvalidTokenFormat         = errors.New("invalid token format")
)

Predefined errors

Functions

func CalculateHmac

func CalculateHmac(securedInput, key []byte) (string, error)

func CalculateHmac256

func CalculateHmac256(securedInput, key []byte) (string, error)

func NewToken

func NewToken[Payload any](signingKey []byte, data Payload, ttl time.Duration, fn hmacFunc) (string, error)

NewToken generates a new token with the provided signing key, payload data, time-to-live (ttl), and HMAC function. It returns the generated token as a string and an error if any. The payload can be of any type, specified by the `Payload` type parameter. If the ttl is greater than zero, the token will have an expiration time set to the current time plus the ttl duration. The `fn` parameter is the HMAC function used to sign the token. It takes the token claims as a JSON byte array and the signing key as input, and returns the signed string and an error if any. The generated token is a combination of the base64-encoded token claims and the base64-encoded signed string, separated by a dot ('.').

func ParseToken

func ParseToken[Payload any](signingKey []byte, token string, fn hmacFunc, vfn validateFunc) (p Payload, err error)

ParseToken parses a token and returns the payload contained within it. It takes a signing key, a token string, a HMAC function, and a validation function as input parameters. The signing key is used to verify the token's signature. The token string is expected to be in the format "payload.signature". The HMAC function is used to calculate the signature of the token. The validation function is used to validate the payload and signature against the signing key and HMAC function. The payload is decoded from base64 and unmarshaled into a tokenClaims struct. If the token is invalid or expired, an error is returned. Otherwise, the payload is returned.

func ValidateHmac

func ValidateHmac(securedInput, sign, key []byte, fn hmacFunc) error

Types

type Signer

type Signer[Payload any] interface {
	// Sign generates a signature for the given data.
	// It returns the generated signature as a string and any error encountered.
	Sign(data Payload) (string, error)

	// SignTemporary generates a temporary signature for the given data with a specified time-to-live (TTL).
	// It returns the generated signature as a string and any error encountered.
	SignTemporary(data Payload, ttl time.Duration) (string, error)

	// Parse parses the given token and returns the payload associated with it.
	// It returns the parsed payload and any error encountered.
	Parse(token string) (Payload, error)
}

Signer is an interface that defines the methods for signing and parsing data.

func NewSigner

func NewSigner[Payload any](signingKey []byte) Signer[Payload]

NewSigner creates a new instance of the Signer type with the specified signing key. The signing key is used to generate and validate HMAC signatures. The generic type parameter `Payload` represents the type of the payload that will be signed. The function returns a pointer to the created Signer instance.

func NewSigner256

func NewSigner256[Payload any](signingKey []byte) Signer[Payload]

NewSigner256 creates a new instance of the Signer interface that uses HMAC-SHA256 for signing. It takes a signingKey as input, which is the secret key used for generating the HMAC signature. The generic type parameter `Payload` represents the type of the payload that will be signed. The function returns a pointer to the Signer implementation.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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