Documentation
¶
Index ¶
- Constants
- Variables
- func AESCTR256DecryptFile(inputPath, outputPath, passphrase string) error
- func AESCTR256EncryptFile(inputPath, outputPath, passphrase string) error
- func AESCTRDecryptFile(inputPath, outputPath, passphrase string, encType EncryptionType) error
- func AESCTREncryptFile(inputPath, outputPath, passphrase string, encType EncryptionType) error
- func AESGCM256Decrypt(ciphertext []byte, passphrase string) ([]byte, error)
- func AESGCM256Encrypt(data []byte, passphrase string) ([]byte, error)
- func AESGCMDecrypt(ciphertext []byte, passphrase string, encType EncryptionType) ([]byte, error)
- func AESGCMEncrypt(data []byte, passphrase string, encType EncryptionType) ([]byte, error)
- func AsymmetricSign(priv interface{}, data []byte, sigType SigningType) ([]byte, error)
- func AsymmetricVerify(pub interface{}, data, sig []byte, sigType SigningType) (bool, error)
- func ComputeSigningCertFingerprint(certPEM string) (string, error)
- func ComputeSigningCertFingerprintDER(certDER []byte) (string, error)
- func DecodeBase36(s string) (int, error)
- func DecodePrefixedBase64(s string) ([]byte, error)
- func DecodeSecretKey(encodedKey string) ([]byte, error)
- func DecryptWithRSAOAEP(priv *rsa.PrivateKey, ciphertext []byte) ([]byte, error)
- func DefaultIsFIPSMode() bool
- func EncodeBase36(n int) string
- func EncodeJWTSecretKey(jwtDecodedKey []byte) (string, error)
- func EncodePrivateKeyToPEM(priv interface{}) ([]byte, error)
- func EncodeSecretKey(jwtDecodedKey []byte) (string, error)
- func EncodeToBase64(b []byte) string
- func EncryptWithRSAOAEP(pub *rsa.PublicKey, data []byte) ([]byte, error)
- func GenerateECDSA256Key() (*ecdsa.PrivateKey, error)
- func GenerateECDSA384Key() (*ecdsa.PrivateKey, error)
- func GenerateECDSAKey(curve elliptic.Curve) (*ecdsa.PrivateKey, error)
- func GenerateEncryptionKeyWithLength(selectedLen int) ([]byte, error)
- func GenerateEncryptionKeyWithLengthBase64(selectedLen int) (string, error)
- func GenerateIDBase36Caps(length int) string
- func GenerateMiniRandomCodes(count, length int) ([]string, error)
- func GenerateRSA2048Key() (*rsa.PrivateKey, error)
- func GenerateRSA3072Key() (*rsa.PrivateKey, error)
- func GenerateRSAKey(bits int) (*rsa.PrivateKey, error)
- func GenerateRandomInt100KTo1B() int
- func GenerateRandomInt100KTo1M() int
- func GenerateRandomIntWithOptions(min int, max int) int
- func GetInitialSecretsFromEnv(specs []EnvSecretSpec) map[SecretsKey]string
- func HandleError(err error)
- func HashArgon2id(unencryptedTarget string, presets *Argon2Presets) (string, error)
- func HashBCrypt(target string, cost int) (string, error)
- func HashPBKDF2(target string, presets *PBKDF2Presets) (string, error)
- func HashPassword(password string, presets interface{}) (string, error)
- func HashSCrypt(unencryptedTarget string, presets *ScryptPresets) (string, error)
- func HashSHA256Bytes(b []byte) []byte
- func HashSHA256File(filepath string) ([]byte, error)
- func HashSHA256String(s string) []byte
- func HashSHA384Bytes(b []byte) []byte
- func HashSHA384File(filepath string) ([]byte, error)
- func HashSHA384String(s string) []byte
- func HashSHA512Bytes(b []byte) []byte
- func HashSHA512File(filepath string) ([]byte, error)
- func HashSHA512String(s string) []byte
- func InitializeJWTSecretKey(encodedKey string) ([]byte, error)
- func InitializeSecretKey(encodedKey string) ([]byte, error)
- func IsArgon2idHash(hash string) bool
- func IsBCryptHash(hash string) bool
- func IsBase64Encoded(data []byte) bool
- func IsPBKDF2Hash(hash string) bool
- func IsSCryptHash(hash string) bool
- func IsValidChecksumFingerprint(alg string, s string) bool
- func JWTSECRETKEY() []byte
- func MatchPassword(hashed string, password string) (bool, error)
- func MustRandGenerate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) string
- func MustRandGenerate4Digits() string
- func MustRandGenerate16() string
- func MustRandGenerate20() string
- func MustRandGenerate32() string
- func MustRandGenerate64() string
- func NewIdGenReadableLong(prefix string, date time.Time) string
- func NewIdGenReadableShort(prefix string, date time.Time) string
- func NewIdGenReadableWithOptions(format string, prefix string, date time.Time, length int) string
- func ParseChecksum(d string) (alg string, rawBytes []byte, err error)
- func ParsePEMPrivateKey(pemBytes []byte) (interface{}, error)
- func RandGenerate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) (string, error)
- func RandGenerate4Digits() (string, error)
- func RandGenerate16() (string, error)
- func RandGenerate20() (string, error)
- func RandGenerate32() (string, error)
- func RandGenerate64() (string, error)
- func RandomStrongOneWayByVariableLength(low, high int) (string, error)
- func RandomStrongOneWaySecret() (string, error)
- func ResolveFromEnv(valVar, fileVar string) (string, bool)
- func SHA256FingerprintHex(certPEM string) (string, error)
- func SaveSecretsManagerToFile(filePath, password string, mgr ISecretsManager) error
- func SetAppSecretsManager(target ISecretsManager, force bool) error
- func SignWithECDSA(priv *ecdsa.PrivateKey, data []byte) ([]byte, error)
- func SignWithRSAPSS(priv *rsa.PrivateKey, data []byte, hashID crypto.Hash) ([]byte, error)
- func Sum256ToSlice(b []byte) []byte
- func Sum384ToSlice(b []byte) []byte
- func Sum512ToSlice(b []byte) []byte
- func TOTPValidate(submittedSecret string, systemSecret string) bool
- func ToBase64SHA256(b []byte) string
- func ToBase64SHA256File(filepath string) (string, error)
- func ToBase64SHA256FileWithFormat(filepath string, prependFormat bool) (string, error)
- func ToBase64SHA256String(s string) string
- func ToBase64SHA256WithFormat(s string, prependFormat bool) string
- func ToBase64SHA384(b []byte) string
- func ToBase64SHA384File(filepath string) (string, error)
- func ToBase64SHA384FileWithFormat(filepath string, prependFormat bool) (string, error)
- func ToBase64SHA384String(s string) string
- func ToBase64SHA384WithFormat(s string, prependFormat bool) string
- func ToBase64SHA512(b []byte) string
- func ToBase64SHA512File(filepath string) (string, error)
- func ToBase64SHA512FileWithFormat(filepath string, prependFormat bool) (string, error)
- func ToBase64SHA512String(s string) string
- func ToBase64SHA512WithFormat(s string, prependFormat bool) string
- func ToHexSHA256(b []byte) string
- func ToHexSHA256File(filepath string) (string, error)
- func ToHexSHA256String(s string) string
- func ToHexSHA384(b []byte) string
- func ToHexSHA384File(filepath string) (string, error)
- func ToHexSHA384String(s string) string
- func ToHexSHA512(b []byte) string
- func ToHexSHA512File(filepath string) (string, error)
- func ToHexSHA512String(s string) string
- func TryRandGenerate4Digits() string
- func ValidatePasswordComplex(password string) error
- func ValidatePasswordComplexWithOptions(password string, customValidator FNValidatePassword) error
- func ValidatePasswordWithOptions(password string, customValidator FNValidatePassword) (int, error)
- func ValidatePasswordWithScore(password string) (int, error)
- func VerifyArgon2id(hashed string, plain string) (bool, error)
- func VerifyBCrypt(hashed string, plain string) (bool, error)
- func VerifyECDSASignature(pub *ecdsa.PublicKey, data, sig []byte) (bool, error)
- func VerifyPBKDF2(hashed string, plain string) (bool, error)
- func VerifyRSAPSSSignature(pub *rsa.PublicKey, data, sig []byte, hashID crypto.Hash) error
- func VerifySCrypt(hashed string, plain string) (bool, error)
- type Argon2Presets
- type CryptKeyBase64
- type CryptMode
- type CryptValue
- type CryptValueMap
- func (cvm CryptValueMap) Delete(key SecretsKey)
- func (cvm CryptValueMap) GetDecoded(key SecretsKey) ([]byte, error)
- func (cvm CryptValueMap) HasAnyExpired(requiredKeys []SecretsKey) bool
- func (cvm CryptValueMap) Initialize(requiredKeys []SecretsKey) error
- func (cvm CryptValueMap) Rotate(requiredKeys []SecretsKey, graceDuration time.Duration) error
- func (cvm CryptValueMap) Set(key SecretsKey, value string) error
- func (cvm CryptValueMap) SetCryptValueClearBytes(key SecretsKey, clearBytes []byte) error
- func (cvm CryptValueMap) Validate(requiredKeys []SecretsKey) error
- type DecodedSecretsMap
- type EncodingType
- type EncryptionType
- type EnvSecretSpec
- type FNValidatePassword
- type HashValueMap
- type ISecretsManager
- type IdBrief
- type IsFIPSModeFunc
- type MiniRandomCodes
- func (codes *MiniRandomCodes) Generate(count int, length int, divider string) error
- func (codes *MiniRandomCodes) GenerateWithCharSet(count int, length int, divider string, charset string) error
- func (codes *MiniRandomCodes) MatchAndRemove(target string) bool
- func (codes MiniRandomCodes) ToStringArray() []string
- type NonceStore
- type PBKDF2Presets
- type PasswordRequirements
- type RandomTextGenerator
- type ScryptPresets
- type SecretsItem
- func (si *SecretsItem) Decode(password string, cacheDecoded bool) ([]byte, error)
- func (si *SecretsItem) GetDecodedValue(password string) ([]byte, error)
- func (si *SecretsItem) GetKey() SecretsKey
- func (si *SecretsItem) IsExpired() bool
- func (si *SecretsItem) SetKey(key SecretsKey)
- func (si *SecretsItem) SetValueDecrypted(value string, encoding EncodingType, encryption EncryptionType)
- type SecretsItems
- type SecretsItemsMap
- type SecretsKey
- type SecretsKeys
- type SecretsManager
- func (sm *SecretsManager) EnsureCryptMode(targetMode CryptMode, password string) error
- func (sm *SecretsManager) FindSecret(key SecretsKey) *SecretsItem
- func (sm *SecretsManager) GetMasterPassword() string
- func (sm *SecretsManager) GetSecret(key SecretsKey) []byte
- func (sm *SecretsManager) HasSecret(key SecretsKey) bool
- func (sm *SecretsManager) RemoveSecret(key SecretsKey)
- func (sm *SecretsManager) SetMasterPassword(oldPassword, newPassword string) error
- func (sm *SecretsManager) SetSecret(item *SecretsItem) error
- func (sm *SecretsManager) Validate() error
- type SecretsValue
- func (s *SecretsValue) Decode(password string, cacheDecoded bool) ([]byte, error)
- func (s *SecretsValue) EnsureCryptMode(password string, targetMode CryptMode) error
- func (s *SecretsValue) GetDecoded() []byte
- func (s *SecretsValue) HasExpired() bool
- func (s *SecretsValue) HasValue() bool
- func (s *SecretsValue) IsDecoded() bool
- func (s *SecretsValue) IsValidParsedValue() bool
- func (s *SecretsValue) NewJWTSecretKey() error
- func (s *SecretsValue) NewRandomSecret() error
- func (s *SecretsValue) Rotate(newValue string, duration time.Duration)
- type SecretsValueRaw
- func (s SecretsValueRaw) Decode(password string) ([]byte, error)
- func (s *SecretsValueRaw) Encode(rawValue []byte, masterPassword string) error
- func (s SecretsValueRaw) IsEmpty() bool
- func (s SecretsValueRaw) Parse() (CryptMode, EncodingType, EncryptionType, string, error)
- func (s *SecretsValueRaw) Validate(value string)
- type SignedPayload
- func (sp *SignedPayload) GenerateNonce() string
- func (sp *SignedPayload) Sign(payload string, privKey ed25519.PrivateKey) (SignedPayload, error)
- func (sp *SignedPayload) ValidateTimestamp(maxAge time.Duration) error
- func (sp *SignedPayload) Verify(payload string, pubKey ed25519.PublicKey) (bool, error)
- type SigningType
- type TOTP
Constants ¶
const ( RSAKeySizeMin = 256 // Example: Minimum size for RSA public keys Ed25519KeySize = 32 // Size for Ed25519 public keys ECDSAP256KeySize = 64 // Size for P-256 ECDSA public keys )
const DefaultTimeFormat = "060102"
DefaultTimeFormat is the default format for time-based IdBriefs.
Variables ¶
var GenerateSecretKey = func() ([]byte, error) { key := make([]byte, 32) _, err := rand.Read(key) if err != nil { return nil, fmt.Errorf("failed to generate secret key: %v", err) } return key, nil }
GenerateSecretKey generates a secure 256-bit (32-byte) random key suitable for FIPS-approved cryptographic uses, such as HMAC-SHA256 for JWT signing. It uses crypto/rand for high-entropy generation.
Compatibility note:
- In Go 1.23 and earlier, this function may return an error if randomness generation fails.
- In Go 1.24 and later, crypto/rand.Read is guaranteed to succeed or panic (it never returns a non-nil error). Thus, the error return is always nil in Go 1.24+, and the error-handling branch is dead code but harmless.
- For FIPS 140-3 compliance, build with appropriate flags (e.g., GOEXPERIMENT=systemcrypto) to use certified modules.
Functions ¶
func AESCTR256DecryptFile ¶ added in v0.9.7
AESCTR256DecryptFile is a wrapper for AESCTRDecryptFile using AES-256.
func AESCTR256EncryptFile ¶ added in v0.9.7
AESCTR256EncryptFile is a wrapper for AESCTREncryptFile using AES-256.
func AESCTRDecryptFile ¶ added in v0.9.8
func AESCTRDecryptFile(inputPath, outputPath, passphrase string, encType EncryptionType) error
AESCTRDecryptFile decrypts a file using AES-CTR + HMAC-SHA256 with the specified EncryptionType. HMAC key fixed at 32 bytes.
func AESCTREncryptFile ¶ added in v0.9.8
func AESCTREncryptFile(inputPath, outputPath, passphrase string, encType EncryptionType) error
AESCTREncryptFile encrypts a file using AES-CTR + HMAC-SHA256 with the specified EncryptionType. Defaults to ENCRYPTIONTYPE_AES256 if invalid/unspecified. HMAC key fixed at 32 bytes.
func AESGCM256Decrypt ¶
AESGCM256Decrypt is a wrapper for AESGCMDecrypt using AES-256.
func AESGCM256Encrypt ¶
AESGCM256Encrypt is a wrapper for AESGCMEncrypt using AES-256.
func AESGCMDecrypt ¶ added in v0.9.8
func AESGCMDecrypt(ciphertext []byte, passphrase string, encType EncryptionType) ([]byte, error)
AESGCMDecrypt decrypts ciphertext using AES-GCM with the specified EncryptionType.
func AESGCMEncrypt ¶ added in v0.9.8
func AESGCMEncrypt(data []byte, passphrase string, encType EncryptionType) ([]byte, error)
AESGCMEncrypt encrypts data using AES-GCM with the specified EncryptionType. Defaults to ENCRYPTIONTYPE_AES256 if invalid/unspecified.
func AsymmetricSign ¶ added in v0.9.8
func AsymmetricSign(priv interface{}, data []byte, sigType SigningType) ([]byte, error)
AsymmetricSign signs data using the specified SigningType. priv must match the type (ECDSA or RSA PrivateKey).
func AsymmetricVerify ¶ added in v0.9.8
func AsymmetricVerify(pub interface{}, data, sig []byte, sigType SigningType) (bool, error)
AsymmetricVerify verifies a signature using the specified SigningType. pub must match the type (ECDSA or RSA PublicKey).
func ComputeSigningCertFingerprint ¶ added in v0.9.8
ComputeSigningCertFingerprint computes the SHA-256 fingerprint of a PEM-encoded certificate. Input: PEM string (e.g., from CertChain[0]). Output: Lowercase hex string (64 chars). Errors if PEM invalid or not a cert.
func ComputeSigningCertFingerprintDER ¶ added in v0.9.8
ComputeSigningCertFingerprintDER computes the SHA-256 fingerprint of a PEM-encoded certificate passed in DER bytes. Input: DER bytes (e.g., from x509.ParseCertificate). Output: Lowercase hex string (64 chars). Errors if PEM invalid or not a cert.
func DecodeBase36 ¶
DecodeBase36 converts a base36 string to an integer
func DecodePrefixedBase64 ¶ added in v0.9.12
DecodePrefixedBase64 decodes a base64-encoded string that may be prefixed with "base64:". It strips the prefix if present and decodes the remaining string using standard base64 encoding. Returns the decoded bytes or an error if decoding fails.
func DecodeSecretKey ¶ added in v0.9.8
func DecryptWithRSAOAEP ¶ added in v0.9.8
func DecryptWithRSAOAEP(priv *rsa.PrivateKey, ciphertext []byte) ([]byte, error)
DecryptWithRSAOAEP decrypts data using RSA-OAEP with SHA-256.
func DefaultIsFIPSMode ¶ added in v0.9.8
func DefaultIsFIPSMode() bool
DefaultIsFIPSMode is the default implementation.
func EncodeBase36 ¶
EncodeBase36 converts an integer to a base36 string
func EncodeJWTSecretKey ¶
EncodeJWTSecretKey takes a decoded JWT secret key and returns its base64-encoded string representation.
func EncodePrivateKeyToPEM ¶ added in v0.9.8
EncodePrivateKeyToPEM encodes a private key (ECDSA or RSA) to PEM format.
func EncodeSecretKey ¶ added in v0.9.8
func EncodeToBase64 ¶
EncodeToBase64 encodes the given bytes to a base64-encoded string using raw standard encoding (URL-safe, no padding).
func EncryptWithRSAOAEP ¶ added in v0.9.8
EncryptWithRSAOAEP encrypts data using RSA-OAEP with SHA-256.
func GenerateECDSA256Key ¶ added in v0.9.8
func GenerateECDSA256Key() (*ecdsa.PrivateKey, error)
GenerateECDSA256Key is a wrapper for P-256.
func GenerateECDSA384Key ¶ added in v0.9.8
func GenerateECDSA384Key() (*ecdsa.PrivateKey, error)
GenerateECDSA384Key is a wrapper for P-384.
func GenerateECDSAKey ¶ added in v0.9.8
func GenerateECDSAKey(curve elliptic.Curve) (*ecdsa.PrivateKey, error)
GenerateECDSAKey generates an ECDSA private key for the specified curve.
func GenerateEncryptionKeyWithLength ¶ added in v0.9.12
GenerateEncryptionKeyWithLength generates a secure random encryption key of the specified length in bytes. The length must be 16, 24, or 32 (for AES-128, AES-192, or AES-256); otherwise, it defaults to 32. It fills the key with high-entropy bytes from crypto/rand. For FIPS compliance, build with appropriate flags (e.g., GOEXPERIMENT=systemcrypto).
func GenerateEncryptionKeyWithLengthBase64 ¶ added in v0.9.12
GenerateEncryptionKeyWithLengthBase64 generates a secure random encryption key of the specified length in bytes (16, 24, or 32), base64-encodes it, and prefixes the result with "base64:". Defaults to 32 bytes if invalid length. This format is suitable for direct use in configurations that expect prefixed base64 keys.
func GenerateIDBase36Caps ¶
GenerateIDBase36Caps generates a random Base36 string of the specified length that are all capitals and no "0" and "O" characters.
func GenerateMiniRandomCodes ¶
GenerateMiniRandomCodes generates a specified number of random codes with a given length.
func GenerateRSA2048Key ¶ added in v0.9.8
func GenerateRSA2048Key() (*rsa.PrivateKey, error)
GenerateRSA2048Key is a wrapper for 2048-bit RSA.
func GenerateRSA3072Key ¶ added in v0.9.8
func GenerateRSA3072Key() (*rsa.PrivateKey, error)
GenerateRSA3072Key is a wrapper for 3072-bit RSA.
func GenerateRSAKey ¶ added in v0.9.8
func GenerateRSAKey(bits int) (*rsa.PrivateKey, error)
GenerateRSAKey generates an RSA private key with the specified bit size (2048 or 3072 recommended).
func GenerateRandomInt100KTo1B ¶
func GenerateRandomInt100KTo1B() int
GenerateRandomInt100KTo1B generates a random integer between 100,000 and 999,999,999.
func GenerateRandomInt100KTo1M ¶
func GenerateRandomInt100KTo1M() int
GenerateRandomInt100KTo1M generates a random integer between 100,000 and 999,999.
func GenerateRandomIntWithOptions ¶
GenerateRandomIntWithOptions generates a random integer between min and max.
func GetInitialSecretsFromEnv ¶ added in v0.9.11
func GetInitialSecretsFromEnv(specs []EnvSecretSpec) map[SecretsKey]string
GetInitialSecretsFromEnv loads secrets based on provided specs. Customize specs for your app's needs.
func HandleError ¶
func HandleError(err error)
HandleError is a helper function to handle errors in a user-defined way.
func HashArgon2id ¶ added in v0.9.7
func HashArgon2id(unencryptedTarget string, presets *Argon2Presets) (string, error)
HashArgon2id hashes a string using Argon2id and returns the hash in PHC format. It returns an error if the input string is empty or if the hashing fails.
func HashBCrypt ¶ added in v0.9.7
HashBCrypt hashes a string using bcrypt and returns the hash. It returns an error if the input string is empty or if the hashing fails.
func HashPBKDF2 ¶ added in v0.9.8
func HashPBKDF2(target string, presets *PBKDF2Presets) (string, error)
HashPBKDF2 hashes a string using PBKDF2 and returns the hash in PHC format. It returns an error if the input string is empty or if hashing fails.
func HashPassword ¶ added in v0.9.8
HashPassword hashes the password using Argon2id (default) or PBKDF2 (if FIPS mode). Optionally accepts presets; uses defaults if nil.
func HashSCrypt ¶ added in v0.9.7
func HashSCrypt(unencryptedTarget string, presets *ScryptPresets) (string, error)
HashSCrypt hashes a string using scrypt and returns the hash in PHC format. It returns an error if the input string is empty or if the hashing fails.
func HashSHA256Bytes ¶ added in v0.9.8
HashSHA256Bytes computes the SHA-256 hash of the input bytes.
func HashSHA256File ¶ added in v0.9.8
HashSHA256File computes the SHA-256 hash of the file at the given filepath.
func HashSHA256String ¶ added in v0.9.8
HashSHA256String computes the SHA-256 hash of the input string.
func HashSHA384Bytes ¶ added in v0.9.8
HashSHA384Bytes computes the SHA-384 hash of the input bytes.
func HashSHA384File ¶ added in v0.9.8
HashSHA384File computes the SHA-384 hash of the file at the given filepath.
func HashSHA384String ¶ added in v0.9.8
HashSHA384String computes the SHA-384 hash of the input string.
func HashSHA512Bytes ¶ added in v0.9.8
HashSHA512Bytes computes the SHA-512 hash of the input bytes.
func HashSHA512File ¶ added in v0.9.8
HashSHA512File computes the SHA-512 hash of the file at the given filepath.
func HashSHA512String ¶ added in v0.9.8
HashSHA512String computes the SHA-512 hash of the input string.
func InitializeJWTSecretKey ¶
InitializeJWTSecretKey initializes or returns a decoded JWT secret key. If encodedKey is empty, it generates a new key; otherwise, it decodes the provided base64 string.
func InitializeSecretKey ¶ added in v0.9.8
InitializeSecretKey initializes or returns a decoded secret key. If encodedKey is empty, it generates a new key; otherwise, it decodes the provided base64 string.
func IsArgon2idHash ¶
IsArgon2idHash checks if a given hash is an Argon2id hash.
func IsBCryptHash ¶ added in v0.9.7
IsBCryptHash checks if a given hash is a bcrypt hash.
func IsBase64Encoded ¶
IsBase64Encoded checks if the given byte slice is valid base64-encoded data.
func IsPBKDF2Hash ¶ added in v0.9.8
IsPBKDF2Hash checks if a given hash is a PBKDF2 hash.
func IsSCryptHash ¶ added in v0.9.7
IsSCryptHash checks if a given hash is a scrypt hash.
func IsValidChecksumFingerprint ¶ added in v0.9.8
IsValidChecksumFingerprint checks if the given hex string is a valid representation for the specified algorithm. Supports sha256 (64 chars), sha384 (96 chars), sha512 (128 chars) for FIPS/OCI compliance. Verifies length and ensures only hex characters (0-9, a-f, A-F) are present. Case-insensitive for hex digits.
func JWTSECRETKEY ¶
func JWTSECRETKEY() []byte
func MatchPassword ¶ added in v0.9.8
MatchPassword verifies if the password matches the stored hash. Automatically detects and routes to PBKDF2 or Argon2id verifier based on hash format.
func MustRandGenerate ¶
MustRandGenerate generates a random string of specified length and panics with a descriptive error message if there's an error.
func MustRandGenerate4Digits ¶
func MustRandGenerate4Digits() string
MustRandGenerate4Digits generates a 4-digit random string and panics with a descriptive error message if there's an error.
func MustRandGenerate16 ¶
func MustRandGenerate16() string
MustRandGenerate16 generates a 16-character random string and panics with a descriptive error message if there's an error.
func MustRandGenerate20 ¶
func MustRandGenerate20() string
MustRandGenerate20 generates a 20-character random string and panics with a descriptive error message if there's an error.
func MustRandGenerate32 ¶
func MustRandGenerate32() string
MustRandGenerate32 generates a 32-character random string and panics with a descriptive error message if there's an error.
func MustRandGenerate64 ¶
func MustRandGenerate64() string
MustRandGenerate64 generates a 64-character random string and panics with a descriptive error message if there's an error.
func NewIdGenReadableWithOptions ¶
NewIdGenReadableWithOptions generates human-readable numbers, such as for invoice, purchase orders, quotes or other identifiers. If running 100,000 of these within a second, there can be a few collisions. When using in your own app, double-check uniqueness prior to saving, such as to a database.
func ParseChecksum ¶ added in v0.9.8
ParseChecksum parses a checksum string (e.g., "sha256:abcdef...") into the algorithm (lowercase) and raw hash bytes. It uses go-digest for OCI-compliant validation and extraction. Only FIPS 140-3 compliant algorithms are allowed: sha256, sha384, sha512. Returns an error for invalid format, unsupported algorithm, or decoding issues.
func ParsePEMPrivateKey ¶ added in v0.9.8
ParsePEMPrivateKey parses a PEM-encoded private key (ECDSA or RSA).
func RandGenerate ¶
RandGenerate generates a random string of specified length.
func RandGenerate4Digits ¶
RandGenerate4Digits generates a 4-digit random numbers.
func RandGenerate16 ¶
RandGenerate16 generates a 16-character random string.
func RandGenerate20 ¶
RandGenerate20 generates a 20-character random string.
func RandGenerate32 ¶
RandGenerate32 generates a 32-character random string.
func RandGenerate64 ¶
RandGenerate64 generates a 64-character random string.
func RandomStrongOneWayByVariableLength ¶ added in v0.9.11
RandomStrongOneWayByVariableLength generates a secure random key of variable length between low and high (inclusive). It first generates a fixed 32-byte random key, base64-encodes it (producing 44 characters), then trims to a random length in [low, high]. Defaults to low=25, high=37 if low > high or invalid. For FIPS compliance, build with appropriate flags (e.g., GOEXPERIMENT=systemcrypto).
func RandomStrongOneWaySecret ¶ added in v0.9.11
RandomStrongOneWaySecret generates a secure random secret.
func ResolveFromEnv ¶ added in v0.9.11
ResolveFromEnv resolves a value from env vars with file support. Precedence: explicit *_FILE > inline var (which may itself reference a file with @/file:/~/). Returns (value, ok); ok is false if no value found. Uses fmt.Printf for warnings since logging may not be initialized yet.
func SHA256FingerprintHex ¶ added in v0.9.8
SHA256FingerprintHex computes the SHA-256 fingerprint of a PEM-encoded certificate. Input: PEM string (e.g., from CertChain[0]). Output: Lowercase hex string (64 chars). Errors if PEM invalid or not a cert.
func SaveSecretsManagerToFile ¶
func SaveSecretsManagerToFile(filePath, password string, mgr ISecretsManager) error
SaveSecretsManagerToFile saves the given SecretsManager to a file, optionally encrypting it with a password.
func SetAppSecretsManager ¶
func SetAppSecretsManager(target ISecretsManager, force bool) error
SetAppSecretsManager sets or updates the global instance of ISecretsManager. Use force=true to overwrite an existing instance.
func SignWithECDSA ¶ added in v0.9.8
func SignWithECDSA(priv *ecdsa.PrivateKey, data []byte) ([]byte, error)
SignWithECDSA signs data using ECDSA with SHA-256.
func SignWithRSAPSS ¶ added in v0.9.8
SignWithRSAPSS signs data using RSA-PSS with the specified hash (defaults to SHA-256).
func Sum256ToSlice ¶ added in v0.9.8
Sum256ToSlice computes the SHA-256 hash of the input bytes and returns it as a slice.
func Sum384ToSlice ¶ added in v0.9.8
Sum384ToSlice computes the SHA-384 hash of the input bytes and returns it as a slice.
func Sum512ToSlice ¶ added in v0.9.8
Sum512ToSlice computes the SHA-512 hash of the input bytes and returns it as a slice.
func TOTPValidate ¶
TOTPValidate validates a submitted TOTP against the system's secret.
func ToBase64SHA256 ¶ added in v0.9.8
ToBase64SHA256 computes the SHA-256 hash of the input bytes and returns it as a base64-encoded string.
func ToBase64SHA256File ¶ added in v0.9.8
ToBase64SHA256File computes the SHA-256 hash of the file and returns it as a base64-encoded string.
func ToBase64SHA256FileWithFormat ¶ added in v0.9.8
ToBase64SHA256FileWithFormat computes the SHA-256 hash of the file and returns it as a base64-encoded string, optionally prepending a "{sha256}" format label.
func ToBase64SHA256String ¶ added in v0.9.8
ToBase64SHA256String computes the SHA-256 hash of the input string and returns it as a base64-encoded string.
func ToBase64SHA256WithFormat ¶ added in v0.9.8
ToBase64SHA256WithFormat computes the SHA-256 hash of the input string and returns it as a base64-encoded string, optionally prepending a "{sha256}" format label.
func ToBase64SHA384 ¶ added in v0.9.8
ToBase64SHA384 computes the SHA-384 hash of the input bytes and returns it as a base64-encoded string.
func ToBase64SHA384File ¶ added in v0.9.8
ToBase64SHA384File computes the SHA-384 hash of the file and returns it as a base64-encoded string.
func ToBase64SHA384FileWithFormat ¶ added in v0.9.8
ToBase64SHA384FileWithFormat computes the SHA-384 hash of the file and returns it as a base64-encoded string, optionally prepending a "{sha384}" format label.
func ToBase64SHA384String ¶ added in v0.9.8
ToBase64SHA384String computes the SHA-384 hash of the input string and returns it as a base64-encoded string.
func ToBase64SHA384WithFormat ¶ added in v0.9.8
ToBase64SHA384WithFormat computes the SHA-384 hash of the input string and returns it as a base64-encoded string, optionally prepending a "{sha384}" format label.
func ToBase64SHA512 ¶ added in v0.9.8
ToBase64SHA512 computes the SHA-512 hash of the input bytes and returns it as a base64-encoded string.
func ToBase64SHA512File ¶ added in v0.9.8
ToBase64SHA512File computes the SHA-512 hash of the file and returns it as a base64-encoded string.
func ToBase64SHA512FileWithFormat ¶ added in v0.9.8
ToBase64SHA512FileWithFormat computes the SHA-512 hash of the file and returns it as a base64-encoded string, optionally prepending a "{sha512}" format label.
func ToBase64SHA512String ¶ added in v0.9.8
ToBase64SHA512String computes the SHA-512 hash of the input string and returns it as a base64-encoded string.
func ToBase64SHA512WithFormat ¶ added in v0.9.8
ToBase64SHA512WithFormat computes the SHA-512 hash of the input string and returns it as a base64-encoded string, optionally prepending a "{sha512}" format label.
func ToHexSHA256 ¶ added in v0.9.8
ToHexSHA256 computes the SHA-256 hash of the input bytes and returns it as a hexadecimal string.
func ToHexSHA256File ¶ added in v0.9.8
ToHexSHA256File computes the SHA-256 hash of the file and returns it as a hexadecimal string.
func ToHexSHA256String ¶ added in v0.9.8
ToHexSHA256String computes the SHA-256 hash of the input string and returns it as a hexadecimal string.
func ToHexSHA384 ¶ added in v0.9.8
ToHexSHA384 computes the SHA-384 hash of the input bytes and returns it as a hexadecimal string.
func ToHexSHA384File ¶ added in v0.9.8
ToHexSHA384File computes the SHA-384 hash of the file and returns it as a hexadecimal string.
func ToHexSHA384String ¶ added in v0.9.8
ToHexSHA384String computes the SHA-384 hash of the input string and returns it as a hexadecimal string.
func ToHexSHA512 ¶ added in v0.9.8
ToHexSHA512 computes the SHA-512 hash of the input bytes and returns it as a hexadecimal string.
func ToHexSHA512File ¶ added in v0.9.8
ToHexSHA512File computes the SHA-512 hash of the file and returns it as a hexadecimal string.
func ToHexSHA512String ¶ added in v0.9.8
ToHexSHA512String computes the SHA-512 hash of the input string and returns it as a hexadecimal string.
func TryRandGenerate4Digits ¶
func TryRandGenerate4Digits() string
TryRandGenerate4Digits tries to generate a 4-digit random string and handles errors.
func ValidatePasswordComplex ¶
ValidatePasswordComplex checks if the password meets the specified criteria.
func ValidatePasswordComplexWithOptions ¶
func ValidatePasswordComplexWithOptions(password string, customValidator FNValidatePassword) error
ValidatePasswordComplexWithOptions checks if the password meets the specified criteria.
func ValidatePasswordWithOptions ¶
func ValidatePasswordWithOptions(password string, customValidator FNValidatePassword) (int, error)
ValidatePasswordWithOptions validates a password with additional custom checks.
func ValidatePasswordWithScore ¶
ValidatePasswordWithScore validates a password with basic requirements and checks its strength score.
func VerifyArgon2id ¶ added in v0.9.7
VerifyArgon2id compares an Argon2id hashed string with a plaintext string. It returns true if they match, false otherwise, along with an error if any occurs.
func VerifyBCrypt ¶ added in v0.9.7
VerifyBCrypt compares a bcrypt hashed string with a plaintext string. It returns true if they match, false otherwise, along with an error if the hash is invalid or other issues occur.
func VerifyECDSASignature ¶ added in v0.9.8
VerifyECDSASignature verifies an ECDSA signature with SHA-256.
func VerifyPBKDF2 ¶ added in v0.9.8
VerifyPBKDF2 compares a PBKDF2 hashed string with a plaintext string. It returns true if they match, false otherwise, along with an error if any occurs.
func VerifyRSAPSSSignature ¶ added in v0.9.8
VerifyRSAPSSSignature verifies an RSA-PSS signature with the specified hash (defaults to SHA-256).
Types ¶
type Argon2Presets ¶
type Argon2Presets struct {
Time uint32 // Time cost parameter
Memory uint32 // Memory cost parameter (in KiB)
Threads uint8 // Parallelism parameter
KeyLen uint32 // Key length
}
Argon2Presets holds the configuration parameters for Argon2.
func NewArgon2Presets ¶
func NewArgon2Presets() *Argon2Presets
NewArgon2Presets creates a new Argon2Presets with OWASP-recommended minimum values.
type CryptKeyBase64 ¶
type CryptKeyBase64 string
CryptKeyBase64 represents a key where base64 is expected.
func NewCryptKeyBase64 ¶
func NewCryptKeyBase64(key []byte) CryptKeyBase64
func (CryptKeyBase64) Decoded ¶
func (pk CryptKeyBase64) Decoded() ([]byte, error)
func (CryptKeyBase64) Encoded ¶
func (pk CryptKeyBase64) Encoded() string
func (CryptKeyBase64) IsBase64 ¶
func (pk CryptKeyBase64) IsBase64() bool
func (CryptKeyBase64) IsEmpty ¶
func (pk CryptKeyBase64) IsEmpty() bool
IsEmpty checks if the PublicKey is empty.
func (CryptKeyBase64) MustDecode ¶
func (pk CryptKeyBase64) MustDecode() []byte
func (CryptKeyBase64) Validate ¶
func (pk CryptKeyBase64) Validate(expectedSize int) error
Validate checks if the key is valid base64 and matches the expected size.
type CryptValue ¶ added in v0.9.8
type CryptValue struct {
Value string `json:"value"` // Formatted: "base64;<base64-encoded-key>"
OldValue string `json:"oldValue,omitempty"` // Previous value during rotation.
OldValueExpiresAt *time.Time `json:"oldValueExpiresAt,omitempty"` // Expiration for old value.
MaxDuration int `json:"maxDuration,omitempty"` // Max validity in minutes.
// contains filtered or unexported fields
}
CryptValue represents a simple rotatable secret value (no encryption, just decoding and rotation).
func (*CryptValue) Decode ¶ added in v0.9.8
func (cv *CryptValue) Decode() ([]byte, error)
Decode decodes the base64 value (caches if not already).
func (*CryptValue) GetDecoded ¶ added in v0.9.8
func (cv *CryptValue) GetDecoded() []byte
GetDecoded returns the cached decoded value.
func (*CryptValue) HasExpired ¶ added in v0.9.8
func (cv *CryptValue) HasExpired() bool
HasExpired checks if current or old value is expired.
func (*CryptValue) HasValue ¶ added in v0.9.8
func (cv *CryptValue) HasValue() bool
HasValue checks if the value is set.
func (*CryptValue) IsValid ¶ added in v0.9.8
func (cv *CryptValue) IsValid() bool
IsValid checks if the value is parseable (base64 format).
type CryptValueMap ¶ added in v0.9.8
type CryptValueMap map[SecretsKey]*CryptValue
CryptValueMap is a map of secrets with helper methods.
func (CryptValueMap) Delete ¶ added in v0.9.8
func (cvm CryptValueMap) Delete(key SecretsKey)
Delete removes a key.
func (CryptValueMap) GetDecoded ¶ added in v0.9.8
func (cvm CryptValueMap) GetDecoded(key SecretsKey) ([]byte, error)
GetDecoded returns decoded value for a key.
func (CryptValueMap) HasAnyExpired ¶ added in v0.9.8
func (cvm CryptValueMap) HasAnyExpired(requiredKeys []SecretsKey) bool
HasAnyExpired checks if any required secret expired.
func (CryptValueMap) Initialize ¶ added in v0.9.8
func (cvm CryptValueMap) Initialize(requiredKeys []SecretsKey) error
Initialize generates new secrets for missing keys.
func (CryptValueMap) Rotate ¶ added in v0.9.8
func (cvm CryptValueMap) Rotate(requiredKeys []SecretsKey, graceDuration time.Duration) error
Rotate rotates secrets for required keys with grace duration.
func (CryptValueMap) Set ¶ added in v0.9.8
func (cvm CryptValueMap) Set(key SecretsKey, value string) error
Set sets or updates a CryptValue.
func (CryptValueMap) SetCryptValueClearBytes ¶ added in v0.9.9
func (cvm CryptValueMap) SetCryptValueClearBytes(key SecretsKey, clearBytes []byte) error
SetCryptValueClearBytes sets or updates the CryptValue for the specified key using the provided clear bytes. The bytes are encoded in base64 and stored in the format "base64;<encoded>". It validates the key and bytes, decodes to cache the value, and returns an error if the key is empty, the bytes are nil or empty, or if decoding fails (though decoding failure is unlikely since the value is freshly encoded).
func (CryptValueMap) Validate ¶ added in v0.9.8
func (cvm CryptValueMap) Validate(requiredKeys []SecretsKey) error
Validate checks all required keys are present and valid.
type DecodedSecretsMap ¶
type DecodedSecretsMap map[SecretsKey][]byte
type EncodingType ¶
type EncodingType string
EncodingType represents the type of encoding used.
const ( ENCODINGTYPE_BASE64 EncodingType = "base64" ENCODINGTYPE_HEX EncodingType = "hex" ENCODINGTYPE_PLAIN EncodingType = "plain" )
Supported EncodingTypes
func (EncodingType) IsEmpty ¶
func (et EncodingType) IsEmpty() bool
IsEmpty checks if EncodingType is empty after trimming whitespace.
type EncryptionType ¶
type EncryptionType string
EncryptionType represents the type of encryption used.
const ( ENCRYPTIONTYPE_AES128 EncryptionType = "aes128" // 128-bit key; quantum-effective: 64 bits (use cautiously) ENCRYPTIONTYPE_AES192 EncryptionType = "aes192" // 192-bit key; quantum-effective: 96 bits ENCRYPTIONTYPE_AES256 EncryptionType = "aes256" // 256-bit key; quantum-effective: 128 bits (recommended default) )
Supported EncryptionTypes (all FIPS 140-3 compliant; default to AES-256 for quantum resistance)
func (EncryptionType) IsEmpty ¶
func (et EncryptionType) IsEmpty() bool
IsEmpty checks if EncryptionType is empty after trimming whitespace.
func (EncryptionType) KeySize ¶ added in v0.9.8
func (et EncryptionType) KeySize() int
KeySize returns the key size in bytes for the EncryptionType.
type EnvSecretSpec ¶ added in v0.9.11
type EnvSecretSpec struct {
Key SecretsKey // The target key (e.g., "conn:ldap:bind:pass").
ValVar string // Env var for inline value (e.g., "LDAP_BIND_PASS").
FileVar string // Env var for explicit file path (e.g., "LDAP_BIND_PASS_FILE").
}
EnvSecretSpec defines a secret to load from env vars.
type FNValidatePassword ¶
FNValidatePassword is a function type that takes a password string and returns an error.
type HashValueMap ¶ added in v0.9.11
type HashValueMap map[SecretsKey]string
HashValueMap is a simple map for storing hashed values (e.g., one-way password hashes) without decoding or rotation.
func (HashValueMap) Delete ¶ added in v0.9.11
func (hvm HashValueMap) Delete(key SecretsKey)
Delete removes a key.
func (HashValueMap) Get ¶ added in v0.9.11
func (hvm HashValueMap) Get(key SecretsKey) string
Get returns the hash value for a key, or an empty string if not found.
func (HashValueMap) Has ¶ added in v0.9.11
func (hvm HashValueMap) Has(key SecretsKey) bool
Has checks if the key exists and has a non-empty value.
func (HashValueMap) Set ¶ added in v0.9.11
func (hvm HashValueMap) Set(key SecretsKey, value string) error
Set sets or updates the hash value for the specified key. It validates that the key is not empty and the value is not blank.
func (HashValueMap) Validate ¶ added in v0.9.11
func (hvm HashValueMap) Validate(requiredKeys []SecretsKey) error
Validate checks all required keys are present and non-empty.
type ISecretsManager ¶
type ISecretsManager interface {
SetSecret(item *SecretsItem) error
FindSecret(key SecretsKey) *SecretsItem
RemoveSecret(key SecretsKey)
GetSecret(key SecretsKey) []byte
EnsureCryptMode(targetMode CryptMode, password string) error
GetMasterPassword() string
SetMasterPassword(oldPassword, newPassword string) error
}
ISecretsManager defines an interface for managing application secrets.
func APPSECRETS ¶
func APPSECRETS() ISecretsManager
APPSECRETS is a shortcut to GetAppSecretsManager(). Prior to using, set the manager using SetAppSecretsManager.
func GetAppSecretsManager ¶
func GetAppSecretsManager() ISecretsManager
GetAppSecretsManager returns the global instance of ISecretsManager.
func LoadSecretsManagerFromFile ¶
func LoadSecretsManagerFromFile(filePath, password string, mgr ISecretsManager) (ISecretsManager, error)
LoadSecretsManagerFromFile loads a SecretsManager from a file, optionally decrypting it with a password. If no manager is provided, a default *SecretsManager is created.
type IdBrief ¶
type IdBrief string
IdBrief represents a brief identifier, typically a string.
func MustNewIdBrief ¶
MustNewIdBrief is a generic wrapper that panics on error.
func NewIdBrief4Digits ¶
NewIdBrief4Digits creates a new IdBrief with 4 random digits.
func NewIdBriefToDay ¶
NewIdBriefToDay creates a new IdBrief with the current day.
func NewIdBriefToHour ¶
NewIdBriefToHour creates a new IdBrief with the current hour.
func NewIdBriefToMinute ¶
NewIdBriefToMinute creates a new IdBrief with the current minute.
type IsFIPSModeFunc ¶ added in v0.9.8
type IsFIPSModeFunc func() bool
IsFIPSModeFunc is the function type for checking FIPS mode.
var IsFIPSMode IsFIPSModeFunc = DefaultIsFIPSMode
IsFIPSMode is the global variable for function IsFIPSModeFunc (override in tests).
type MiniRandomCodes ¶
type MiniRandomCodes []string
MiniRandomCodes represents a slice of random codes.
func (*MiniRandomCodes) Generate ¶
func (codes *MiniRandomCodes) Generate(count int, length int, divider string) error
Generate creates a specified number of random codes with a given length and optional divider.
func (*MiniRandomCodes) GenerateWithCharSet ¶
func (codes *MiniRandomCodes) GenerateWithCharSet(count int, length int, divider string, charset string) error
GenerateWithCharSet creates a specified number of random codes with a given length and optional divider, using the provided character set. The generated codes are stored in the MiniRandomCodes slice.
func (*MiniRandomCodes) MatchAndRemove ¶
func (codes *MiniRandomCodes) MatchAndRemove(target string) bool
MatchAndRemove finds a target code and removes it from the slice.
func (MiniRandomCodes) ToStringArray ¶
func (codes MiniRandomCodes) ToStringArray() []string
ToStringArray converts MiniRandomCodes to a slice of strings.
type NonceStore ¶
type NonceStore struct {
// contains filtered or unexported fields
}
func NewNonceStore ¶
func NewNonceStore() *NonceStore
func (*NonceStore) Add ¶
func (ns *NonceStore) Add(nonce string) bool
type PBKDF2Presets ¶ added in v0.9.8
type PBKDF2Presets struct {
Iterations int // Number of iterations (OWASP min: 600,000 for SHA-256)
KeyLen int // Derived key length (32 bytes default)
HashFunc string // Hash function: "sha256" or "sha512"
}
PBKDF2Presets holds the configuration parameters for PBKDF2.
func NewPBKDF2Presets ¶ added in v0.9.8
func NewPBKDF2Presets() *PBKDF2Presets
NewPBKDF2Presets creates a new PBKDF2Presets with OWASP-recommended defaults (SHA-256, 600,000 iterations).
type PasswordRequirements ¶
type PasswordRequirements struct {
Password string `validate:"required,min=8,max=100"`
}
PasswordRequirements struct defines the requirements for a valid password.
type RandomTextGenerator ¶
type RandomTextGenerator struct {
Length int // Total length of the random text
NumDigits int // Number of digits in the random text
NumSymbols int // Number of symbols in the random text
NoUpper bool // If true, no uppercase letters will be included
AllowRepeat bool // If true, characters can be repeated
}
RandomTextGenerator is a struct that defines parameters for generating random text.
func (*RandomTextGenerator) Generate ¶
func (rg *RandomTextGenerator) Generate() (string, error)
Generate produces a random string based on the RandomTextGenerator's settings.
type ScryptPresets ¶
type ScryptPresets struct {
N int // CPU/memory cost parameter (must be power of 2)
R int // Block size parameter
P int // Parallelization parameter
KeyLen int // Key length
}
ScryptPresets holds the configuration parameters for scrypt.
func NewScryptPresets ¶
func NewScryptPresets() *ScryptPresets
NewScryptPresets creates a new ScryptPresets with OWASP-recommended minimum values.
type SecretsItem ¶
type SecretsItem struct {
Key SecretsKey `json:"key"` // The key associated with the secret item.
Value SecretsValue `json:"value"` // The current value of the secret.
// contains filtered or unexported fields
}
SecretsItem represents a single item in the secrets management system.
func NewSecretsItem ¶
func NewSecretsItem(key SecretsKey, value string, encoding EncodingType, encryption EncryptionType) *SecretsItem
NewSecretsItem creates a new SecretsItem with the provided key and value.
func NewSecretsItemAuto ¶
func NewSecretsItemAuto(key SecretsKey, length int) (*SecretsItem, error)
NewSecretsItemAuto creates a new SecretsItem with a random value of the specified length.
func (*SecretsItem) Decode ¶
func (si *SecretsItem) Decode(password string, cacheDecoded bool) ([]byte, error)
Decode ensures the value is decoded and optionally cached.
func (*SecretsItem) GetDecodedValue ¶
func (si *SecretsItem) GetDecodedValue(password string) ([]byte, error)
GetDecodedValue safely retrieves the decoded value of the SecretsItem.
func (*SecretsItem) GetKey ¶
func (si *SecretsItem) GetKey() SecretsKey
GetKey safely retrieves the key of the SecretsItem.
func (*SecretsItem) IsExpired ¶
func (si *SecretsItem) IsExpired() bool
IsExpired checks if the secret or its old value has expired.
func (*SecretsItem) SetKey ¶
func (si *SecretsItem) SetKey(key SecretsKey)
SetKey safely sets the key of the SecretsItem.
func (*SecretsItem) SetValueDecrypted ¶
func (si *SecretsItem) SetValueDecrypted(value string, encoding EncodingType, encryption EncryptionType)
SetValueDecrypted safely sets the decrypted value of the SecretsItem.
type SecretsItems ¶
type SecretsItems []*SecretsItem
SecretsItems represents a collection of SecretsItem pointers.
func (SecretsItems) Find ¶
func (sis SecretsItems) Find(key SecretsKey) *SecretsItem
Find searches for a SecretsItem by key within a slice of SecretsItems.
func (*SecretsItems) Remove ¶
func (sis *SecretsItems) Remove(key SecretsKey)
Remove deletes a SecretsItem from the collection based on its key.
func (*SecretsItems) Set ¶
func (sis *SecretsItems) Set(item *SecretsItem) error
Set adds or updates a SecretsItem in the collection based on its key.
type SecretsItemsMap ¶
type SecretsItemsMap map[SecretsKey]*SecretsItem
SecretsItemsMap is a map of SecretsKey to SecretsItem for easy lookup.
type SecretsKey ¶
type SecretsKey string
SecretsKey is a type that represents a key used in secret management.
const ( SECRETSKEY_APPHOSTEK SecretsKey = "apphostek" // App Host Encryption Key // Used for credential secrets and db passwords SECRETSKEY_SVT SecretsKey = "svt" // Secrets Vault Token SECRETSKEY_SALT SecretsKey = "salt" // Salt value SECRETSKEY_JWT SecretsKey = "jwt" // JWT signing key )
SecretsKey constants define specific keys used for encryption and configuration.
func (SecretsKey) IsEmpty ¶
func (sk SecretsKey) IsEmpty() bool
IsEmpty checks if the SecretsKey is empty after trimming whitespace.
func (SecretsKey) String ¶
func (sk SecretsKey) String() string
String converts the SecretsKey to a regular string.
func (SecretsKey) ToStringTrimLower ¶
func (sk SecretsKey) ToStringTrimLower() string
ToStringTrimLower converts the SecretsKey to a lowercase string with trimmed whitespace.
func (SecretsKey) TrimSpace ¶
func (sk SecretsKey) TrimSpace() SecretsKey
TrimSpace trims whitespace from both ends of the SecretsKey.
type SecretsKeys ¶
type SecretsKeys []SecretsKey
SecretsKeys is a slice of SecretsKey, representing a collection of keys.
type SecretsManager ¶
type SecretsManager struct {
Secrets SecretsItems `json:"secrets,omitempty"` // Collection of secrets.
// contains filtered or unexported fields
}
SecretsManager manages secrets within an application.
func NewSecretsManager ¶
func NewSecretsManager(masterPassword string) *SecretsManager
NewSecretsManager creates a new SecretsManager with an optional master password.
func NewSecretsManagerWithOptions ¶
func NewSecretsManagerWithOptions(masterPassword string, newMasterIfEmpty bool, secretItems SecretsItems) (*SecretsManager, error)
NewSecretsManagerWithOptions creates a new SecretsManager with an optional master password and secretItems.
func (*SecretsManager) EnsureCryptMode ¶
func (sm *SecretsManager) EnsureCryptMode(targetMode CryptMode, password string) error
EnsureCryptMode ensures all secrets are in the specified CryptMode.
func (*SecretsManager) FindSecret ¶
func (sm *SecretsManager) FindSecret(key SecretsKey) *SecretsItem
FindSecret retrieves a SecretsItem by key.
func (*SecretsManager) GetMasterPassword ¶
func (sm *SecretsManager) GetMasterPassword() string
GetMasterPassword retrieves the master password.
func (*SecretsManager) GetSecret ¶
func (sm *SecretsManager) GetSecret(key SecretsKey) []byte
GetSecret retrieves a fully decoded and decrypted SecretsItem by key.
func (*SecretsManager) HasSecret ¶
func (sm *SecretsManager) HasSecret(key SecretsKey) bool
HasSecret returns true if it can fully decode and decrypt a SecretsItem by key.
func (*SecretsManager) RemoveSecret ¶
func (sm *SecretsManager) RemoveSecret(key SecretsKey)
RemoveSecret deletes a SecretsItem by key.
func (*SecretsManager) SetMasterPassword ¶
func (sm *SecretsManager) SetMasterPassword(oldPassword, newPassword string) error
SetMasterPassword sets the master password and updates all secrets.
func (*SecretsManager) SetSecret ¶
func (sm *SecretsManager) SetSecret(item *SecretsItem) error
SetSecret adds a new SecretsItem to the manager.
func (*SecretsManager) Validate ¶
func (sm *SecretsManager) Validate() error
Validate ensures the secrets can be decrypted using the masterPassword and are applied to the map for faster access.
type SecretsValue ¶
type SecretsValue struct {
Value SecretsValueRaw `json:"value"` // The current raw value of the secret.
ExpiresAt *time.Time `json:"expiresAt,omitempty"` // Expiration time for the current value.
OldValue SecretsValueRaw `json:"oldValue,omitempty"` // The previous raw value of the secret being rotated out.
OldValueExpiresAt *time.Time `json:"oldValueExpiresAt,omitempty"` // Expiration time for the old value.
MaxDuration int `json:"maxDuration,omitempty"` // Maximum duration (in minutes) that the secret is valid.
// contains filtered or unexported fields
}
SecretsValue represents a single item in the secrets management system.
func (*SecretsValue) Decode ¶
func (s *SecretsValue) Decode(password string, cacheDecoded bool) ([]byte, error)
Decode decrypts and decodes the value of the secret, with an option to cache the decoded value.
func (*SecretsValue) EnsureCryptMode ¶
func (s *SecretsValue) EnsureCryptMode(password string, targetMode CryptMode) error
EnsureCryptMode ensures the CryptMode is set to the specified mode (either "e" or "d"). It switches between encryption and decryption based on the current mode and the provided password.
func (*SecretsValue) GetDecoded ¶
func (s *SecretsValue) GetDecoded() []byte
GetDecoded returns valueDecoded.
func (*SecretsValue) HasExpired ¶
func (s *SecretsValue) HasExpired() bool
HasExpired checks whether the secret has expired.
func (*SecretsValue) HasValue ¶
func (s *SecretsValue) HasValue() bool
HasValue returns true if there is content in the Value field.
func (*SecretsValue) IsDecoded ¶
func (s *SecretsValue) IsDecoded() bool
IsDecoded checks if the valueDecoded is set.
func (*SecretsValue) IsValidParsedValue ¶
func (s *SecretsValue) IsValidParsedValue() bool
IsValidParsedValue returns true if there is content in the Value field that is not empty and parseable.
func (*SecretsValue) NewJWTSecretKey ¶
func (s *SecretsValue) NewJWTSecretKey() error
NewJWTSecretKey initializes a new JWT secret key with a default encrypted format and rotates old values.
func (*SecretsValue) NewRandomSecret ¶ added in v0.9.8
func (s *SecretsValue) NewRandomSecret() error
NewRandomSecret generates and sets a new random 32-byte secret key in decrypted format. Suitable for any secret type (e.g., JWT, BadgerDB encryption keys).
type SecretsValueRaw ¶
type SecretsValueRaw string
func NewSecretsValueRawBase64Decrypted ¶
func NewSecretsValueRawBase64Decrypted(encryptionType EncryptionType, value []byte) SecretsValueRaw
func (SecretsValueRaw) Decode ¶
func (s SecretsValueRaw) Decode(password string) ([]byte, error)
Decode decrypts and decodes the value based on the encoding and encryption types.
func (*SecretsValueRaw) Encode ¶
func (s *SecretsValueRaw) Encode(rawValue []byte, masterPassword string) error
Encode sets the raw value to a new encoded and optionally encrypted format based on the mode.
func (SecretsValueRaw) IsEmpty ¶
func (s SecretsValueRaw) IsEmpty() bool
IsEmpty checks if SecretsValueRaw is empty after trimming whitespace.
func (SecretsValueRaw) Parse ¶
func (s SecretsValueRaw) Parse() (CryptMode, EncodingType, EncryptionType, string, error)
Parse splits the SecretsValueRaw into its components.
func (*SecretsValueRaw) Validate ¶
func (s *SecretsValueRaw) Validate(value string)
Validate ensures the raw value is in the proper format. If not, it defaults to a clear format.
type SignedPayload ¶
type SignedPayload struct {
Timestamp int64 `json:"timestamp"` // Unix timestamp to prevent replay attacks
Nonce string `json:"nonce"` // Random value to ensure uniqueness
Signature string `json:"signature"` // Signature of the payload
}
SignedPayload represents the payload signed by the subscriber for identity verification.
func (*SignedPayload) GenerateNonce ¶
func (sp *SignedPayload) GenerateNonce() string
GenerateNonce generates a unique nonce for payloads.
func (*SignedPayload) Sign ¶
func (sp *SignedPayload) Sign(payload string, privKey ed25519.PrivateKey) (SignedPayload, error)
Sign signs the payload using the private key.
func (*SignedPayload) ValidateTimestamp ¶
func (sp *SignedPayload) ValidateTimestamp(maxAge time.Duration) error
ValidateTimestamp checks whether the timestamp is within an acceptable range to prevent replay attacks.
type SigningType ¶ added in v0.9.8
type SigningType int
SigningType defines the asymmetric signing algorithm.
const ( SigningTypeECDSA256 SigningType = iota // ECDSA with P-256 SigningTypeECDSA384 // ECDSA with P-384 SigningTypeRSAPSS2048 // RSA-PSS with 2048-bit key SigningTypeRSAPSS3072 // RSA-PSS with 3072-bit key )
type TOTP ¶
type TOTP struct {
Secret string `json:"secret,omitempty"` // The TOTP secret key
Image []byte `json:"image,omitempty"` // PNG image bytes of the QR code
}
TOTP struct holds the secret and image for a TOTP (Time-based One-Time Password).
func TOTPGenerate ¶
TOTPGenerate generates a new TOTP object including the secret and QR code image.
func (*TOTP) BlurImage ¶
BlurImage applies a blur effect to the TOTP image and returns the new image bytes.
func (*TOTP) GetImageAsSrcAttrValue ¶
GetImageAsSrcAttrValue returns the TOTP image as a data URI suitable for HTML src attribute.
func (*TOTP) GetImageBase64 ¶
GetImageBase64 returns the base64-encoded string of the TOTP image.
func (*TOTP) SaveImageBlur ¶
SaveImageBlur saves a blurred version of the TOTP image to the specified file path.
Source Files
¶
- app-secrets-manager.go
- base36.go
- cryptkeybase64.go
- cryptmode.go
- cryptvalue.go
- encodingtype.go
- encryptiontype.go
- envsecretspec.go
- fips3-aes.go
- fips3-hashes.go
- fips3-passwords.go
- fips3-secrets.go
- fips3-signing.go
- id-brief.go
- idgen.go
- mini-random-codes.go
- noncestore.go
- pass-crypt.go
- random-generate.go
- secrethashvaluemap.go
- secrets-key.go
- secretsitem.go
- secretsmanager.go
- secretsvalue.go
- secretsvalueraw.go
- signedpayload.go
- totp.go
- validate-password.go