crypto

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 21 Imported by: 0

README

crypto

Encryption, signing, and JWT utilities: AES (GCM/CBC/CFB), RSA, HMAC-SHA, RC4, and JSON Web Tokens.

Features

  • AES-GCM, AES-CBC (PKCS7), AES-CFB encryption/decryption
  • RSA key generation, encrypt/decrypt, sign/verify, PEM serialization
  • HMAC-SHA256 / HMAC-SHA512 signing and constant-time verification
  • RC4 (legacy) stream cipher
  • JWT create and parse (HS256, HS512, RS256)
  • Base64-encoded convenience variants for AES-GCM

Key types

  • JWTAlgorithm -- JWTAlgHS256, JWTAlgHS512, JWTAlgRS256
  • JWTConfig -- JWT signer configuration (algorithm, secret/keys, issuer, TTL)
  • JWTClaims -- standard JWT claims plus arbitrary Extra map
  • JWT -- JWT token signer/verifier

Key functions

  • RandomKey(n) / MustRandomKey(n) -- cryptographically secure random bytes
  • AESGCMEncrypt / AESGCMDecrypt (+ Base64 variants)
  • AESCBCEncrypt / AESCBCDecrypt, AESCFBEncrypt / AESCFBDecrypt
  • GenerateRSAKeyPair(bits), RSAEncrypt, RSADecrypt, RSASign, RSAVerify
  • MarshalRSAPrivateKeyPEM, ParseRSAPrivateKeyPEM, ParseRSAPublicKeyPEM
  • SignSHA256 / VerifySHA256, SignSHA512 / VerifySHA512
  • NewJWT(cfg), JWT.Sign(claims), JWT.Verify(token)

Quick start

import "github.com/LingByte/ling-base/common/crypto"

// AES-GCM
key, _ := crypto.RandomKey(32) // AES-256
ciphertext, _ := crypto.AESGCMEncrypt(key, []byte("secret"))
plaintext, _ := crypto.AESGCMDecrypt(key, ciphertext)

// JWT
jwt := crypto.NewJWT(crypto.JWTConfig{
    Secret:    []byte("my-32-byte-secret-1234567890123456"),
    ExpiresIn: 15 * time.Minute,
})
token, _ := jwt.Sign(crypto.JWTClaims{Subject: "user-123"})
claims, err := jwt.Verify(token)

License

MIT

Documentation

Overview

Package crypto provides encryption and signing utilities:

  • AES: GCM and CBC modes with padding
  • RSA: key generation, encryption/decryption, signing/verification
  • HMAC-SHA signatures
  • JWT: create and parse JSON Web Tokens (HS256/RS256)

Quick start

// AES-GCM
key := crypto.RandomKey(32) // AES-256
ciphertext, _ := crypto.AESGCMEncrypt(key, []byte("secret"))
plaintext, _ := crypto.AESGCMDecrypt(key, ciphertext)

// RSA
priv, pub, _ := crypto.GenerateRSAKeyPair(2048)
enc, _ := crypto.RSAEncrypt(pub, []byte("data"))
dec, _ := crypto.RSADecrypt(priv, enc)

// JWT
token, _ := crypto.NewJWT(crypto.JWTConfig{Secret: []byte("key")}).Sign(claims)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AESCBCDecrypt

func AESCBCDecrypt(key, data []byte) ([]byte, error)

AESCBCDecrypt decrypts data produced by AESCBCEncrypt.

func AESCBCEncrypt

func AESCBCEncrypt(key, plaintext []byte) ([]byte, error)

AESCBCEncrypt encrypts plaintext using AES-CBC with PKCS7 padding. The key must be 16, 24, or 32 bytes. A random IV is prepended to the output.

func AESCFBDecrypt

func AESCFBDecrypt(key, ciphertext []byte) ([]byte, error)

AESCFBDecrypt decrypts AES-CFB ciphertext (IV prepended).

func AESCFBEncrypt

func AESCFBEncrypt(key, plaintext []byte) ([]byte, error)

AESCFBEncrypt encrypts plaintext using AES in CFB mode. The returned ciphertext includes a random IV prepended to the encrypted data.

func AESGCMDecrypt

func AESGCMDecrypt(key, data []byte) ([]byte, error)

AESGCMDecrypt decrypts data produced by AESGCMEncrypt.

func AESGCMDecryptBase64

func AESGCMDecryptBase64(key []byte, encoded string) ([]byte, error)

AESGCMDecryptBase64 decrypts a base64-encoded ciphertext.

func AESGCMEncrypt

func AESGCMEncrypt(key, plaintext []byte) ([]byte, error)

AESGCMEncrypt encrypts plaintext using AES-GCM with the given key. The key must be 16, 24, or 32 bytes (AES-128/192/256). Returns nonce + ciphertext concatenated.

func AESGCMEncryptBase64

func AESGCMEncryptBase64(key, plaintext []byte) (string, error)

AESGCMEncryptBase64 encrypts and returns base64-encoded result.

func Base64Decode

func Base64Decode(s string) ([]byte, error)

Base64Decode decodes a standard base64 string.

func Base64Encode

func Base64Encode(data []byte) string

Base64Encode returns standard base64 encoding.

func Base64URLDecode

func Base64URLDecode(s string) ([]byte, error)

Base64URLDecode decodes a URL-safe base64 string (no padding).

func Base64URLEncode

func Base64URLEncode(data []byte) string

Base64URLEncode returns URL-safe base64 encoding (no padding).

func ECDSASign added in v0.2.1

func ECDSASign(priv *ecdsa.PrivateKey, data []byte) ([]byte, error)

ECDSASign signs data using ECDSA with SHA-256. The returned signature is ASN.1-encoded (DER format), compatible with most verification libraries.

func ECDSAVerify added in v0.2.1

func ECDSAVerify(pub *ecdsa.PublicKey, data, sig []byte) error

ECDSAVerify verifies an ECDSA signature (ASN.1/DER-encoded) against the given data using the public key.

func Ed25519Sign added in v0.2.1

func Ed25519Sign(priv ed25519.PrivateKey, data []byte) ([]byte, error)

Ed25519Sign signs data using the Ed25519 private key. The returned signature is 64 bytes.

func Ed25519Verify added in v0.2.1

func Ed25519Verify(pub ed25519.PublicKey, data, sig []byte) error

Ed25519Verify verifies an Ed25519 signature against the given data using the public key.

func ExportECDSAPrivateKeyPEM added in v0.2.1

func ExportECDSAPrivateKeyPEM(priv *ecdsa.PrivateKey) (string, error)

ExportECDSAPrivateKeyPEM exports an ECDSA private key as a PEM-encoded string (SEC1 / EC PRIVATE KEY format).

func ExportECDSAPublicKeyPEM added in v0.2.1

func ExportECDSAPublicKeyPEM(pub *ecdsa.PublicKey) (string, error)

ExportECDSAPublicKeyPEM exports an ECDSA public key as a PEM-encoded string (PKIX format).

func ExportEd25519PrivateKeyPEM added in v0.2.1

func ExportEd25519PrivateKeyPEM(priv ed25519.PrivateKey) (string, error)

ExportEd25519PrivateKeyPEM exports an Ed25519 private key as a PEM-encoded string (PKCS8 format).

func ExportEd25519PublicKeyPEM added in v0.2.1

func ExportEd25519PublicKeyPEM(pub ed25519.PublicKey) (string, error)

ExportEd25519PublicKeyPEM exports an Ed25519 public key as a PEM-encoded string (PKIX format).

func ExportRSAPrivateKeyPEM

func ExportRSAPrivateKeyPEM(priv *rsa.PrivateKey) (string, error)

ExportRSAPrivateKeyPEM exports a private key as PEM-encoded string.

func ExportRSAPublicKeyPEM

func ExportRSAPublicKeyPEM(pub *rsa.PublicKey) (string, error)

ExportRSAPublicKeyPEM exports a public key as PEM-encoded string.

func GenerateECDSAKeyPair added in v0.2.1

func GenerateECDSAKeyPair() (*ecdsa.PrivateKey, *ecdsa.PublicKey, error)

GenerateECDSAKeyPair generates an ECDSA key pair on the P-256 curve (secp256r1 / NIST P-256). This curve provides 128-bit security and is widely supported.

func GenerateEd25519KeyPair added in v0.2.1

func GenerateEd25519KeyPair() (ed25519.PrivateKey, ed25519.PublicKey, error)

GenerateEd25519KeyPair generates an Ed25519 key pair. Ed25519 provides fast signing and verification with 128-bit security and 64-byte signatures.

func GenerateRSAKeyPair

func GenerateRSAKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error)

GenerateRSAKeyPair generates an RSA key pair of the given bit size.

func HKDF added in v0.2.1

func HKDF(secret, salt, info []byte, length int) ([]byte, error)

HKDF derives a key of the given length from the input secret using HMAC-based Key Derivation (RFC 5869) with SHA-256.

  • secret: the input keying material (IKM)
  • salt: optional salt (use nil or empty for no salt)
  • info: optional context/application-specific information
  • length: desired output length in bytes (must be > 0 and <= 255*32)

The derivation follows the two-step HKDF process: extract (PRK) then expand (OKM).

func MustRandomKey

func MustRandomKey(n int) []byte

MustRandomKey is like RandomKey but panics on error.

func PBKDF2 added in v0.2.1

func PBKDF2(password, salt []byte, iterations, length int) ([]byte, error)

PBKDF2 derives a key from a password using PBKDF2 with HMAC-SHA256 (RFC 2898).

  • password: the password/passphrase
  • salt: the salt value
  • iterations: number of iterations (use >= 100000 for security)
  • length: desired output length in bytes

func ParseECDSAPrivateKeyPEM added in v0.2.1

func ParseECDSAPrivateKeyPEM(pemStr string) (*ecdsa.PrivateKey, error)

ParseECDSAPrivateKeyPEM parses a PEM-encoded ECDSA private key (SEC1 or PKCS8 format).

func ParseECDSAPublicKeyPEM added in v0.2.1

func ParseECDSAPublicKeyPEM(pemStr string) (*ecdsa.PublicKey, error)

ParseECDSAPublicKeyPEM parses a PEM-encoded ECDSA public key (PKIX format).

func ParseEd25519PrivateKeyPEM added in v0.2.1

func ParseEd25519PrivateKeyPEM(pemStr string) (ed25519.PrivateKey, error)

ParseEd25519PrivateKeyPEM parses a PEM-encoded Ed25519 private key (PKCS8 format).

func ParseEd25519PublicKeyPEM added in v0.2.1

func ParseEd25519PublicKeyPEM(pemStr string) (ed25519.PublicKey, error)

ParseEd25519PublicKeyPEM parses a PEM-encoded Ed25519 public key (PKIX format).

func ParseRSAPrivateKeyPEM

func ParseRSAPrivateKeyPEM(pemStr string) (*rsa.PrivateKey, error)

ParseRSAPrivateKeyPEM parses a PEM-encoded RSA private key.

func ParseRSAPublicKeyPEM

func ParseRSAPublicKeyPEM(pemStr string) (*rsa.PublicKey, error)

ParseRSAPublicKeyPEM parses a PEM-encoded RSA public key.

func RC4Decrypt

func RC4Decrypt(str string, key []byte) string

RC4Decrypt decrypts a hex-encoded RC4 ciphertext.

func RC4Encrypt

func RC4Encrypt(str string, key []byte) string

RC4Encrypt encrypts str with RC4 and returns hex-encoded result. RC4 is considered insecure; prefer AES for new code.

func RSADecrypt

func RSADecrypt(priv *rsa.PrivateKey, ciphertext []byte) ([]byte, error)

RSADecrypt decrypts ciphertext using RSA-OAEP with SHA-256.

func RSAEncrypt

func RSAEncrypt(pub *rsa.PublicKey, plaintext []byte) ([]byte, error)

RSAEncrypt encrypts plaintext using RSA-OAEP with SHA-256.

func RSASign

func RSASign(priv *rsa.PrivateKey, data []byte) ([]byte, error)

RSASign signs data using RSASSA-PKCS1-v1.5 with SHA-256.

func RSAVerify

func RSAVerify(pub *rsa.PublicKey, data, sig []byte) error

RSAVerify verifies an RSASSA-PKCS1-v1.5 signature.

func RandomBase64

func RandomBase64(n int) (string, error)

RandomBase64 returns n cryptographically secure random bytes as base64.

func RandomHex

func RandomHex(n int) (string, error)

RandomHex returns n cryptographically secure random bytes as a hex string.

func RandomKey

func RandomKey(n int) ([]byte, error)

RandomKey returns n cryptographically secure random bytes.

func RandomReader

func RandomReader() io.Reader

RandomReader returns the crypto/rand reader for io.Copy usage.

func SignSHA256

func SignSHA256(data, key []byte) []byte

SignSHA256 signs data using HMAC-SHA256.

func SignSHA512

func SignSHA512(data, key []byte) []byte

SignSHA512 signs data using HMAC-SHA512.

func VerifySHA256

func VerifySHA256(data, key, sig []byte) bool

VerifySHA256 verifies an HMAC-SHA256 signature in constant time.

func VerifySHA512

func VerifySHA512(data, key, sig []byte) bool

VerifySHA512 verifies an HMAC-SHA512 signature in constant time.

Types

type JWT

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

JWT is a JWT token signer/verifier.

func NewJWT

func NewJWT(cfg JWTConfig) *JWT

NewJWT creates a new JWT signer with the given config.

func (*JWT) Parse

func (j *JWT) Parse(token string) (*JWTClaims, error)

Parse parses and verifies a JWT token, returning the claims. Does not check expiration; use Verify for full validation.

func (*JWT) Sign

func (j *JWT) Sign(claims JWTClaims) (string, error)

Sign creates a signed JWT token from the given claims.

func (*JWT) Verify

func (j *JWT) Verify(token string) (*JWTClaims, error)

Verify parses, verifies, and checks expiration of a JWT token.

type JWTAlgorithm

type JWTAlgorithm string

JWTAlgorithm represents a JWT signing algorithm.

const (
	JWTAlgHS256 JWTAlgorithm = "HS256"
	JWTAlgHS512 JWTAlgorithm = "HS512"
	JWTAlgRS256 JWTAlgorithm = "RS256"
)

type JWTClaims

type JWTClaims struct {
	Issuer    string                 `json:"iss,omitempty"`
	Subject   string                 `json:"sub,omitempty"`
	Audience  string                 `json:"aud,omitempty"`
	ExpiresAt int64                  `json:"exp,omitempty"`
	NotBefore int64                  `json:"nbf,omitempty"`
	IssuedAt  int64                  `json:"iat,omitempty"`
	ID        string                 `json:"jti,omitempty"`
	Extra     map[string]interface{} `json:"-"`
}

JWTClaims represents JWT claims.

type JWTConfig

type JWTConfig struct {
	Algorithm JWTAlgorithm    // default HS256
	Secret    []byte          // for HS256/HS512
	RSAPriv   *rsa.PrivateKey // for RS256 signing
	RSAPub    *rsa.PublicKey  // for RS256 verification
	Issuer    string          // iss claim
	Audience  string          // aud claim
	ExpiresIn time.Duration   // exp claim
}

JWTConfig configures the JWT signer.

Jump to

Keyboard shortcuts

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