jwesigner

package module
v0.0.0-...-4d93695 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2024 License: MIT Imports: 14 Imported by: 0

README

jwesigner

Package will securely Encrypt/Sign / Decrypt/Verify a req payload using RSA certificates

  • Prerequisite must have a valid RSA private/public certificates

Badge

build

Workflow

RSA Key Pairs ( at least 2048 bits )
        RSA (Rivest–Shamir–Adleman) encryption is one of the most widely used
        algorithms for secure data encryption.
RSA PublicKey
		remote public key ( client )
		
		used for verifying, the signature of the remote client
		
		shared by client to us
		
		is the public key pair of the remote client
RSA PrivateKey
		own local private key ( SELF )
		
		used for signing
		
		the remote client will verify it using the public key of this private key
		
		we will share the public key pair to the remote client
Self sign RSA certificates

# init vars
PREFIX=$(date '+%Y-%m-%d-%H%M%S')-$(printf "%04x-%04x" ${RANDOM} ${RANDOM})
PRIVKEY=/tmp/${PREFIX}-priv.pem
CACERT=/tmp/${PREFIX}-cacert.pem
DERCERT=/tmp/${PREFIX}-dercert.cer
PUBKEY=/tmp/${PREFIX}-pub.txt

# generate
openssl genrsa -out $PRIVKEY 4096
openssl req -new -x509 -key $PRIVKEY -out $CACERT -days 3650 -subj "/C=SG/ST='Singapore'/L='Singapore/O=Bayugismo/OU='Engineering'/CN=*.bayugismo.sYOUR-API"
openssl x509 -inform PEM -in $CACERT -outform DER -out $DERCERT
openssl x509 -inform der -in $DERCERT -noout -pubkey > $PUBKEY

# PUBLIC KEY must be in S3 bucket config
openssl rsa -pubin -in $PUBKEY | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\n/g'

# PRIVATE KEY must be in S3 bucket config
cat $PRIVKEY | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\\n/g'

How-To use the module/package

import (
	"context"
	"fmt"
	"github.com/bayugyug/jwesigner"
	"github.com/bayugyug/jwesigner/mock"
	"github.com/icrowley/fake"
	log "github.com/sirupsen/logrus"
	"strings"
)




    var (
        opts = jwesigner.Options{
            PublicKey:  mock.DummyPublicKey,
            PrivateKey: mock.DummyPrivateKey,
        }
        payload = fmt.Sprintf("test message: %s", fake.SentencesN(10))
    )
    
    // init
    svc := jwesigner.New(&opts)
    
    
    // Encrypt payload
    enc, err := svc.Encrypt(context.Background(), []byte(payload))
    log.Println("encrypted: ", len(enc))
    
    // sanity check
    if err != nil{
        log.Errorln("failed:", err)
        return
    }

    // Sign the payload and return the signature
    sig, err := svc.Sign(context.Background(), []byte(payload))
    log.Println("sign: ", len(sig), "signature:", sig)
   
    // sanity check
    if err != nil{
        log.Errorln("failed:", err)
        return
    }

    // Decrypt the encrypted payload
    plain, err := svc.Decrypt(context.Background(), enc)
    log.Println("decrypted: ", len(plain), string(plain))

    // sanity check
    if err != nil{
        log.Errorln("failed:", err)
        return
    }

    // Verify check the authenticity of the decrypted payload and signature
    err = svc.Verify(context.Background(), sig)
    
    // dump
    log.WithFields(
                log.Fields{
                    "\npayload":   payload,
                    "\ndecrypted": string(plain),
                    "\nsignature": sig,
                    "\nverified":  err == nil,
                "\nerr":       err,
                }).Println("details")

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// CaretB ...
	CaretB = "�"
)
View Source
var (
	// ErrMissingParams ...
	ErrMissingParams = errors.New("missing required parameters")
)

Functions

func FormatPayloadToSign

func FormatPayloadToSign(opts *FormOpts) string
auth-key | sign-uuid | timestamp | URI | payload

FormatPayloadToSign ...

Types

type Creator

type Creator interface {
	Encrypt(ctx context.Context, message []byte) ([]byte, error)
	Decrypt(ctx context.Context, message []byte) ([]byte, error)
	Sign(ctx context.Context, message []byte) (string, error)
	Verify(ctx context.Context, signature string) (*Verified, error)

	SetOption(opts *Options)
	GetOption() *Options
	GetRSAPublicKey() *rsa.PublicKey
	GetRSAPrivateKey() *rsa.PrivateKey
}

Creator ...

func New

func New(opts *Options) Creator

New create a service

type FormOpts

type FormOpts struct {
	Auth      string
	SignUUID  string
	Timestamp int64
	Method    string
	Link      string
	Payload   []byte
	Sep       string
}

FormOpts ...

func NewOpts

func NewOpts() *FormOpts

NewOpts ...

type OptArgs

type OptArgs func(*Options)

OptArgs options ...

func WithPrivateKey

func WithPrivateKey(param string) OptArgs

WithPrivateKey ...

func WithPublicKey

func WithPublicKey(param string) OptArgs

WithPublicKey ...

type Options

type Options struct {
	PrivateKey string
	PublicKey  string
}

Options ...

func (*Options) GetPublicKeyPKCS

func (k *Options) GetPublicKeyPKCS() (*rsa.PublicKey, error)

GetPublicKeyPKCS ...

func (*Options) GetRSAPrivateKey

func (k *Options) GetRSAPrivateKey() (*rsa.PrivateKey, error)

GetRSAPrivateKey ...

func (*Options) GetRSAPublicKey

func (k *Options) GetRSAPublicKey() (*rsa.PublicKey, error)

GetRSAPublicKey ...

type Service

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

Service ...

func (*Service) Decrypt

func (s *Service) Decrypt(ctx context.Context, message []byte) ([]byte, error)

Decrypt ... decrypt with our private-key

func (*Service) Encrypt

func (s *Service) Encrypt(ctx context.Context, message []byte) ([]byte, error)

Encrypt ... encrypt with their public-key

func (*Service) GetOption

func (s *Service) GetOption() *Options

GetOption ...

func (*Service) GetRSAPrivateKey

func (s *Service) GetRSAPrivateKey() *rsa.PrivateKey

GetRSAPrivateKey ...

func (*Service) GetRSAPublicKey

func (s *Service) GetRSAPublicKey() *rsa.PublicKey

GetRSAPublicKey ...

func (*Service) SetOption

func (s *Service) SetOption(opts *Options)

SetOption ...

func (*Service) Sign

func (s *Service) Sign(ctx context.Context, message []byte) (string, error)

Sign ... sign with our private key

func (*Service) Verify

func (s *Service) Verify(ctx context.Context, signature string) (*Verified, error)

Verify ... decrypt with our private key & verify it with their public key

type Verified

type Verified struct {
	Payload   string `json:"payload,omitempty"`
	Protected string `json:"protected,omitempty"`
	Signature string `json:"signature,omitempty"`
	Full      string `json:"full,omitempty"`
	Compact   string `json:"compact,omitempty"`
	Data      string `json:"data,omitempty"`
}

Verified ...

Directories

Path Synopsis
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

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