crypto

package
v0.0.34 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2025 License: BSD-2-Clause Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrEmptyKeyID        = "EMPTY_KEY_ID"
	ErrAccessKeyNotFound = "ACCESS_KEY_NOT_FOUND"
	ErrInvalidSignature  = "SIGNATURE_MISMATCH"
	ErrMissingHeaders    = "MISSING_REQUIRED_HEADERS"
)

Add constants for error messages

View Source
const ALGORITHM_KEY = "HMAC-SHA256"
View Source
const CREDENTIAL_KEY = "creds"
View Source
const SIGNATURE_KEY = "sign"
View Source
const SIGNED_HEADERS_KEY = "x-kplex-si"
View Source
const TERMINATOR = "@@"

Variables

This section is empty.

Functions

func ComputeSignature

func ComputeSignature(accessSecretKey, payloadHash string, headers map[string]string) (string, error)

ComputeSignature generates a cryptographic signature for API request validation. It uses HMAC-SHA256 algorithm to create a signature based on the provided secret key, payload, and headers.

Parameters:

  • accessSecretKey: The secret key used for signature generation
  • payloadHash: The SHA256 hash of the request body or payload in hexadecimal format
  • headers: A map containing required headers:
  • "ts": Timestamp
  • "api": API name
  • "ver": API version
  • "chnl": Channel identifier
  • "usrid": User ID

Returns:

  • string: The computed signature as a hexadecimal string

The signature is computed using the following steps:

  1. Generate a signing key using the secret key and header information
  2. Combine channel, userId, and payload hash
  3. Create final signature using algorithm, timestamp, and request hash

func DecryptWithKey added in v0.0.23

func DecryptWithKey(ctx context.Context, key, cipeherText string) ([]byte, error)

DecryptWithKey decrypts the given cipher text with the given key. It returns the decrypted value of the cipher text.

func EncryptWithKey added in v0.0.23

func EncryptWithKey(ctx context.Context, key, plainText string) (string, error)

EncryptWithKey encrypts the given plain text with the given key. It returns the encrypted value of the plain text.

func GenerateAesKey added in v0.0.23

func GenerateAesKey(ctx context.Context, key string) (string, error)

GenerateAesKey generates an AES key. It returns the AES key.

func ParseAuthorizationHeader added in v0.0.29

func ParseAuthorizationHeader(authorizationHeaderValue string) (algorithm, credentials, signedHeaders, signature string, err error)

ParseAuthorizationHeader parses the authorization header value and returns its components. Format: "alg=HMAC-SHA256,creds=access-key,signed-headers=header1=value1/header2=value2/,sign=signature" Sample header value alg=HMAC-SHA256,creds=test-key-id,signed-headers=chnl=web/usrid=test-user/ts=2025-01-05T21:00:02+05:30/api=test-api/ver=v1/,sign=5b15ecf0a5a6cc14c12651f628a9bbc8958dcd8edc9bbe8e9970481bb72668af Returns:

  • algorithm: The algorithm used for signature computation
  • credentials: The access key ID
  • signedHeaders: The headers used in signature computation
  • signature: The computed signature
  • err: Error if parsing fails

func SignPayload added in v0.0.29

func SignPayload(apiName, apiVersion, channel, userId, payload, accessKeyId, accessSecret string) (signature, authHeader, signedHeader string, err error)

SignPayload generates a signature and required headers for API request authentication.

Parameters:

  • apiName: Name of the API being called
  • apiVersion: Version of the API
  • channel: Channel identifier for the request
  • userId: User ID making the request
  • payload: Request body or payload to be signed
  • accessKeyId: Access key identifier for authentication
  • accessSecret: Access secret for signature computation

Returns:

  • signature: The computed signature for the request
  • authHeader: Complete authorization header string
  • signedHeader: String containing all signed headers
  • err: Error if signature generation fails

The function performs the following steps:

  1. Generates current timestamp in RFC3339 format
  2. Validates required parameters
  3. Computes payload hash and signature
  4. Builds authorization header with all required components

Possible errors:

  • MISSING_REQUIRED_HEADERS: If any required header is empty
  • INVALID_ACCESS_SECRET: If access secret cannot be retrieved

func VerifySignature

func VerifySignature(signedHeadersValue, payloadHash, providedSignature, accessSecret string) (bool, error)

VerifySignature validates the authenticity of a request by comparing the provided signature with a computed signature using the request payload and headers.

Parameters:

  • signedHeadersValue: The signed headers value in the format "header1=value1/header2=value2/"
  • payloadHash: The SHA256 hash of the request body or payload in hexadecimal format
  • signedHeadersValue: The signed headers value in the format "header1=value1/header2=value2/"
  • providedSignature: The provided signature to be verified, in hexadecimal format
  • accessSecret: The access secret key for signature computation and validation

Use ParseAuthorizationHeader to extract the values and pass it here. Returns:

  • bool: true if signature is valid, false otherwise
  • error: Error if validation fails or if required parameters are missing/invalid

Possible errors:

  • SIGNATURE_MISSING: If signature is not provided
  • INVALID_SIGNED_HEADERS: If required headers are missing
  • SIGNATURE_MISMATCH: If computed signature doesn't match provided signature

Types

type APIAccessKey added in v0.0.30

type APIAccessKey struct {
	KeyID           string         `db:"key_id" json:"keyId"`
	Secret          string         `db:"secret" json:"secret"`
	InstitutionID   string         `db:"institution_id" json:"institutionId"`
	ApplicationName string         `db:"application_name" json:"applicationName"`
	Enabled         string         `db:"enabled" json:"enabled"`
	TestEnabled     string         `db:"test_enabled" json:"testEnabled"`
	Version         int16          `db:"version" json:"version"`
	ActiveFrom      time.Time      `db:"active_from" json:"activeFrom"`
	ActiveUntil     *time.Time     `db:"active_until" json:"activeUntil,omitempty"`
	CreatedAt       time.Time      `db:"created_at" json:"createdAt"`
	UpdatedAt       *time.Time     `db:"updated_at" json:"updatedAt,omitempty"`
	DiscardedAt     gorm.DeletedAt `db:"discarded_at" json:"discardedAt,omitempty"`
}

func (*APIAccessKey) BeforeCreate added in v0.0.30

func (a *APIAccessKey) BeforeCreate(tx *gorm.DB) error

func (*APIAccessKey) BeforeUpdate added in v0.0.30

func (a *APIAccessKey) BeforeUpdate(tx *gorm.DB) error

func (*APIAccessKey) IsValid added in v0.0.33

func (a *APIAccessKey) IsValid() bool

Add validation for time-based operations

func (*APIAccessKey) TableName added in v0.0.30

func (a *APIAccessKey) TableName() string

type AccessSecretProvider

type AccessSecretProvider[T any] interface {
	GetAccessSecret(accessKeyId string) (T, error)
}

AccessSecretProvider is an interface for retrieving access secrets. T represents the type of the secret being returned

type CryptoConfig

type CryptoConfig struct {
	KmsUri       string
	KmsUriPrefix string
	KeysetData   string
	HmacKey      string
	KekAd        []byte
}

type CryptoUtil

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

func NewCryptoUtil

func NewCryptoUtil(cfg *CryptoConfig) (*CryptoUtil, error)

func (*CryptoUtil) CompareHash

func (u *CryptoUtil) CompareHash(ctx context.Context, plainName, storedHash []byte) (bool, error)

CompareHash compares the plain text with the stored hash. It returns true if the plain text is the same as the stored hash.

func (*CryptoUtil) CreateAlias

func (u *CryptoUtil) CreateAlias(ctx context.Context, plain []byte) ([]byte, error)

CreateAlias creates an alias for the given plain text. It returns the hashed value of the plain text.

func (*CryptoUtil) Decrypt

func (u *CryptoUtil) Decrypt(ctx context.Context, cipeherText string, ad []byte) ([]byte, error)

Decrypt decrypts the given cipher text. It returns the decrypted value of the cipher text.

func (*CryptoUtil) Encrypt

func (u *CryptoUtil) Encrypt(ctx context.Context, plainText, ad []byte) (string, error)

Encrypt encrypts the given plain text. It returns the encrypted value of the plain text.

type DbAccessSecretProvider

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

func NewDbAccessSecretProvider

func NewDbAccessSecretProvider(db *gorm.DB) *DbAccessSecretProvider

func (*DbAccessSecretProvider) CreateAccessKey added in v0.0.30

func (r *DbAccessSecretProvider) CreateAccessKey(accessKey *APIAccessKey) error

func (*DbAccessSecretProvider) DeleteAccessKey added in v0.0.30

func (r *DbAccessSecretProvider) DeleteAccessKey(keyID string) error

func (*DbAccessSecretProvider) GetAccessSecret

func (r *DbAccessSecretProvider) GetAccessSecret(ctx context.Context, keyID string) (*APIAccessKey, error)

func (*DbAccessSecretProvider) UpdateAccessKey added in v0.0.30

func (r *DbAccessSecretProvider) UpdateAccessKey(accessKey *APIAccessKey) error

type SignatureError added in v0.0.34

type SignatureError string

Define custom error types

const (
	ErrMissingRequiredHeaders SignatureError = "MISSING_REQUIRED_HEADERS"
	ErrInvalidAlgorithm       SignatureError = "INVALID_ALGORITHM"
	ErrInvalidAccessKeyID     SignatureError = "INVALID_ACCESS_KEY_ID"
	ErrSignatureMissing       SignatureError = "SIGNATURE_MISSING"
	ErrInvalidSignedHeaders   SignatureError = "INVALID_SIGNED_HEADERS"
	ErrSignatureMismatch      SignatureError = "SIGNATURE_MISMATCH"
	ErrInvalidAccessSecret    SignatureError = "INVALID_ACCESS_SECRET"
	ErrInvalidAuthHeader      SignatureError = "INVALID_AUTHORIZATION_HEADER"
)

func (SignatureError) Error added in v0.0.34

func (e SignatureError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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