Documentation
¶
Overview ¶
Package sodium is a pure-Go (no cgo) reimplementation of Ruby's rbnacl gem, the libsodium/NaCl binding.
The rbnacl gem is a thin C extension over libsodium. This package mirrors its public surface — RbNaCl::SecretBox, RbNaCl::Box, RbNaCl::SigningKey / VerifyKey, RbNaCl::Hash, RbNaCl::Auth, RbNaCl::PasswordHash, RbNaCl::PWHash, RbNaCl::GroupElement, RbNaCl::AEAD and RbNaCl::Random — on top of the pure-Go crypto in golang.org/x/crypto (nacl/secretbox, nacl/box, nacl/sign, ed25519, curve25519, blake2b, argon2, scrypt, chacha20poly1305) and the standard library (crypto/sha256, crypto/sha512, crypto/hmac). No cgo, no libsodium, no C. The byte outputs are identical to libsodium's, so ciphertexts, signatures and digests produced here are accepted by libsodium/rbnacl and vice versa.
The Go names deliberately track the Ruby ones: a Ruby RbNaCl::SecretBox.new maps to sodium.NewSecretBox, #encrypt / #decrypt map to Encrypt / Decrypt, the key/nonce byte-length constants (SecretBoxKeyBytes = 32, SecretBoxNonceBytes = 24, ...) match libsodium's crypto_secretbox_*BYTES, and the error hierarchy (CryptoError, LengthError, BadAuthenticatorError, ...) mirrors RbNaCl's exception tree so callers port over one-to-one.
Every wrong-length key, nonce or tag raises a *LengthError; every failed authentication (a tampered ciphertext, a bad signature) raises a *BadAuthenticatorError wrapped in CryptoError, exactly where libsodium returns -1.
Index ¶
- Constants
- Variables
- func Argon2i(password, salt []byte, time, memoryKiB uint32, threads uint8, ...) []byte
- func Argon2id(password, salt []byte, time, memoryKiB uint32, threads uint8, ...) []byte
- func Blake2b(message []byte, opts Blake2bOptions) ([]byte, error)
- func RandomBytes(n int) []byte
- func SHA256(message []byte) []byte
- func SHA512(message []byte) []byte
- func ScalarMultBase(scalar []byte) ([]byte, error)
- func Scrypt(password, salt []byte, n, r, p, digestSize int) ([]byte, error)
- type AEAD
- type Authenticator
- type BadAuthenticatorError
- type Blake2bOptions
- type Box
- type GroupElement
- type LengthError
- type PrivateKey
- type PublicKey
- type SecretBox
- type SigningKey
- type VerifyKey
Constants ¶
const ( // AEADKeyBytes is the ChaCha20-Poly1305 key length (32). AEADKeyBytes = 32 // AEADTagBytes is the Poly1305 tag length appended to every ciphertext // (16). AEADTagBytes = 16 // ChaCha20Poly1305IETFNonceBytes is the IETF ChaCha20-Poly1305 nonce length // (12). ChaCha20Poly1305IETFNonceBytes = 12 // XChaCha20Poly1305IETFNonceBytes is the XChaCha20-Poly1305 nonce length // (24). XChaCha20Poly1305IETFNonceBytes = 24 )
Byte-length constants for the AEAD constructions, matching libsodium's crypto_aead_*.
const ( // HMACKeyBytes is libsodium's recommended HMAC key length (32). Standard // HMAC accepts a key of any length, and so does this package; the constant // documents the default rbnacl uses. HMACKeyBytes = 32 // HMACSHA256Bytes is the HMAC-SHA-256 tag length (32). HMACSHA256Bytes = 32 // HMACSHA512Bytes is the HMAC-SHA-512 tag length (64). HMACSHA512Bytes = 64 // HMACSHA512256Bytes is the HMAC-SHA-512-256 tag length (32); it is // HMAC-SHA-512 truncated to its leading 32 bytes, i.e. libsodium's // crypto_auth (crypto_auth_hmacsha512256). HMACSHA512256Bytes = 32 )
Byte-length constants for the HMAC authenticators, matching libsodium's crypto_auth_hmacsha*_{KEYBYTES,BYTES}.
const ( // PublicKeyBytes is the Curve25519 public-key length (32). PublicKeyBytes = 32 // PrivateKeyBytes is the Curve25519 secret-key length (32). PrivateKeyBytes = 32 // BoxNonceBytes is the nonce length (24). BoxNonceBytes = 24 // BoxMACBytes is the Poly1305 tag length (16). BoxMACBytes = 16 // BeforeNMBytes is the precomputed shared-key length (32). BeforeNMBytes = 32 )
Byte-length constants for public-key authenticated encryption, matching libsodium's crypto_box_*BYTES.
const ( // GroupElementBytes is the length of a Curve25519 group element / point // (32). GroupElementBytes = 32 // ScalarBytes is the length of a Curve25519 scalar (32). ScalarBytes = 32 )
Byte-length constants for Curve25519 scalar multiplication, matching libsodium's crypto_scalarmult_*BYTES.
const ( // SHA256Bytes is the SHA-256 digest length (32). SHA256Bytes = 32 // SHA512Bytes is the SHA-512 digest length (64). SHA512Bytes = 64 // Blake2bBytes is the default BLAKE2b digest length // (crypto_generichash_BYTES, 32). Blake2bBytes = 32 // Blake2bBytesMin is the smallest BLAKE2b digest length (1). Blake2bBytesMin = 1 // Blake2bBytesMax is the largest BLAKE2b digest length (64). Blake2bBytesMax = 64 // Blake2bKeyBytesMax is the largest BLAKE2b key length (64). Blake2bKeyBytesMax = 64 // Blake2bSaltBytes is the BLAKE2b salt length when supplied (16). Blake2bSaltBytes = 16 // Blake2bPersonalBytes is the BLAKE2b personalization length when supplied // (16). Blake2bPersonalBytes = 16 )
Byte-length constants for the hash functions, matching libsodium.
const ( // PWHashSaltBytes is libsodium's Argon2 salt length (crypto_pwhash_SALTBYTES, // 16). PWHashSaltBytes = 16 // ScryptSaltBytes is libsodium's scrypt salt length // (crypto_pwhash_scryptsalsa208sha256_SALTBYTES, 32). ScryptSaltBytes = 32 )
Byte-length constants for the password-hashing primitives, matching libsodium.
const ( // SecretBoxKeyBytes is the shared-secret key length (32). SecretBoxKeyBytes = 32 // SecretBoxNonceBytes is the nonce length (24). SecretBoxNonceBytes = 24 // SecretBoxMACBytes is the Poly1305 authentication tag length (16). SecretBoxMACBytes = 16 )
Byte-length constants for the secret-key box, matching libsodium's crypto_secretbox_*BYTES and RbNaCl::SecretBox::{KEYBYTES,NONCEBYTES,MACBYTES}.
const ( // SignSeedBytes is the 32-byte seed a SigningKey wraps // (crypto_sign_SEEDBYTES). SignSeedBytes = 32 // VerifyKeyBytes is the 32-byte Ed25519 public key length // (crypto_sign_PUBLICKEYBYTES). VerifyKeyBytes = 32 // SignatureBytes is the 64-byte detached signature length // (crypto_sign_BYTES). SignatureBytes = 64 )
Byte-length constants for Ed25519 signing, matching libsodium's crypto_sign_*BYTES.
Variables ¶
var ( // ErrCrypto is the root of the tree (RbNaCl::CryptoError). Every error this // package returns satisfies errors.Is(err, ErrCrypto). ErrCrypto = errors.New("sodium: crypto error") // ErrLength is the RbNaCl::LengthError root: a key, nonce, tag or message // did not have the exact byte length libsodium requires. ErrLength = fmt.Errorf("%w: incorrect length", ErrCrypto) // ErrBadAuthenticator is the RbNaCl::BadAuthenticatorError / // RbNaCl::BadSignatureError root: authentication or signature verification // failed. It is what libsodium signals by returning -1. ErrBadAuthenticator = fmt.Errorf("%w: authentication failed", ErrCrypto) )
The error tree mirrors RbNaCl's exception hierarchy. In Ruby every error is a subclass of RbNaCl::CryptoError; the notable leaves are LengthError (a key, nonce, tag or message of the wrong size) and BadAuthenticatorError (a ciphertext or signature that fails verification). Go callers match them with errors.Is / errors.As.
The sentinels below are the roots a caller reaches for with errors.Is; the *LengthError and *BadAuthenticatorError concrete types carry the offending detail and unwrap to those sentinels.
Functions ¶
func Argon2i ¶
func Argon2i(password, salt []byte, time, memoryKiB uint32, threads uint8, digestSize uint32) []byte
Argon2i derives a key from password and salt with the Argon2i function, mirroring RbNaCl::PasswordHash.argon2. time is the number of passes (opslimit), memoryKiB is the memory cost in kibibytes (libsodium's memlimit divided by 1024), threads the degree of parallelism and digestSize the output length. The bytes equal libsodium's crypto_pwhash Argon2i (version 0x13).
func Argon2id ¶
func Argon2id(password, salt []byte, time, memoryKiB uint32, threads uint8, digestSize uint32) []byte
Argon2id derives a key with the Argon2id function, mirroring RbNaCl::PasswordHash.argon2id. The parameters are as for Argon2i; the bytes equal libsodium's crypto_pwhash Argon2id (version 0x13).
func Blake2b ¶
func Blake2b(message []byte, opts Blake2bOptions) ([]byte, error)
Blake2b returns the BLAKE2b digest of message under opts, mirroring RbNaCl::Hash.blake2b. An out-of-range digest size or over-long key yields a *LengthError; a non-empty salt or personalization yields errBlake2bParams (see errBlake2bParams). With the default options it equals libsodium's crypto_generichash.
func RandomBytes ¶
RandomBytes returns n cryptographically secure random bytes, mirroring RbNaCl::Random.random_bytes(n). It panics only if the system CSPRNG fails, matching RbNaCl, which raises rather than returning a short read.
func ScalarMultBase ¶
ScalarMultBase multiplies the Curve25519 base point by scalar, mirroring RbNaCl::GroupElement.base.mult(scalar) — the public-key derivation crypto_scalarmult_base. A wrong-length scalar yields a *LengthError.
func Scrypt ¶
Scrypt derives a key with scrypt, mirroring RbNaCl::PasswordHash.scrypt. n is the CPU/memory cost (a power of two), r the block size, p the parallelism and digestSize the output length. It returns an error only when the parameters are invalid (n not a power of two > 1, or r*p >= 2^30), matching scrypt's domain. The bytes equal libsodium's crypto_pwhash_scryptsalsa208sha256.
Types ¶
type AEAD ¶
type AEAD struct {
// contains filtered or unexported fields
}
AEAD is authenticated encryption with associated data using ChaCha20-Poly1305 (RbNaCl::AEAD). Construct it with NewChaCha20Poly1305IETF (12-byte nonce) or NewXChaCha20Poly1305IETF (24-byte nonce); the associated data is authenticated but not encrypted.
func NewChaCha20Poly1305IETF ¶
NewChaCha20Poly1305IETF builds an IETF ChaCha20-Poly1305 AEAD from a 32-byte key (RbNaCl::AEAD::ChaCha20Poly1305IETF.new). Any other key length yields a *LengthError.
func NewXChaCha20Poly1305IETF ¶
NewXChaCha20Poly1305IETF builds an XChaCha20-Poly1305 AEAD from a 32-byte key (RbNaCl::AEAD::XChaCha20Poly1305IETF.new). Any other key length yields a *LengthError.
func (*AEAD) Decrypt ¶
Decrypt opens a ciphertext produced by Encrypt with the same nonce and associated data, mirroring RbNaCl::AEAD#decrypt. A wrong-length nonce yields a *LengthError; a forged or corrupt ciphertext (or mismatched associated data) yields a *BadAuthenticatorError.
func (*AEAD) Encrypt ¶
Encrypt seals message under nonce with the given associated data and returns the ciphertext with its 16-byte tag appended, mirroring RbNaCl::AEAD#encrypt. A wrong-length nonce yields a *LengthError.
func (*AEAD) NonceBytes ¶
NonceBytes returns the nonce length this AEAD requires (12 for the IETF variant, 24 for XChaCha20).
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator is a keyed HMAC message-authentication code (RbNaCl::Auth::HMAC). It computes and verifies a fixed-length tag over a message with a secret key.
func NewHMACSHA256 ¶
func NewHMACSHA256(key []byte) *Authenticator
NewHMACSHA256 builds an HMAC-SHA-256 authenticator (RbNaCl::Auth::HMAC::SHA256.new(key)).
func NewHMACSHA512 ¶
func NewHMACSHA512(key []byte) *Authenticator
NewHMACSHA512 builds an HMAC-SHA-512 authenticator (RbNaCl::Auth::HMAC::SHA512.new(key)).
func NewHMACSHA512256 ¶
func NewHMACSHA512256(key []byte) *Authenticator
NewHMACSHA512256 builds an HMAC-SHA-512-256 authenticator (RbNaCl::Auth::HMAC::SHA512256.new(key)), the truncated form libsodium exposes as crypto_auth.
func (*Authenticator) Auth ¶
func (a *Authenticator) Auth(message []byte) []byte
Auth computes the authentication tag over message, mirroring RbNaCl::Auth::HMAC#auth. The tag is truncated to the code's tag length (a no-op for SHA-256/512, a 32-byte truncation for SHA-512-256).
func (*Authenticator) Verify ¶
func (a *Authenticator) Verify(tag, message []byte) error
Verify checks tag against message in constant time, mirroring RbNaCl::Auth::HMAC#verify. It returns nil when the tag matches and a *BadAuthenticatorError otherwise.
type BadAuthenticatorError ¶
type BadAuthenticatorError struct {
// Op names the operation that failed, e.g. "secretbox open".
Op string
}
BadAuthenticatorError is raised when a ciphertext fails its Poly1305 check or a signature fails Ed25519 verification (RbNaCl::BadAuthenticatorError / RbNaCl::BadSignatureError). libsodium returns -1 in exactly these cases.
func (*BadAuthenticatorError) Error ¶
func (e *BadAuthenticatorError) Error() string
func (*BadAuthenticatorError) Unwrap ¶
func (e *BadAuthenticatorError) Unwrap() error
Unwrap ties every *BadAuthenticatorError to ErrBadAuthenticator (and thereby ErrCrypto).
type Blake2bOptions ¶
type Blake2bOptions struct {
// DigestSize is the output length in bytes (1..64). Zero means the default
// 32 (crypto_generichash_BYTES).
DigestSize int
// Key is an optional up-to-64-byte key turning BLAKE2b into a keyed MAC.
Key []byte
// Salt is an optional 16-byte salt (crypto_generichash_blake2b_salt).
Salt []byte
// Personal is an optional 16-byte personalization string.
Personal []byte
}
Blake2bOptions carries the keyword arguments RbNaCl::Hash.blake2b accepts: digest_size:, key:, salt: and personal:. The zero value asks for the default 32-byte unkeyed digest.
type Box ¶
type Box struct {
// contains filtered or unexported fields
}
Box is Curve25519-XSalsa20-Poly1305 public-key authenticated encryption (RbNaCl::Box). It binds the recipient's public key to the sender's private key; the shared secret is computed once and cached, matching libsodium's crypto_box_beforenm.
func NewBox ¶
func NewBox(their *PublicKey, mine *PrivateKey) *Box
NewBox constructs a Box between their public key and my private key, mirroring RbNaCl::Box.new(their_public_key, my_private_key).
func (*Box) Decrypt ¶
Decrypt opens a combined ciphertext produced by Encrypt, mirroring RbNaCl::Box#decrypt. A wrong-length nonce yields a *LengthError; a forged or corrupt ciphertext yields a *BadAuthenticatorError.
type GroupElement ¶
type GroupElement struct {
// contains filtered or unexported fields
}
GroupElement is a point on Curve25519 (RbNaCl::GroupElement). Multiplying it by a scalar is the X25519 Diffie-Hellman operation.
func NewGroupElement ¶
func NewGroupElement(point []byte) (*GroupElement, error)
NewGroupElement wraps a 32-byte point, mirroring RbNaCl::GroupElement.new. Any other length yields a *LengthError.
func (*GroupElement) Bytes ¶
func (ge *GroupElement) Bytes() []byte
Bytes returns a copy of the raw point (RbNaCl::GroupElement#to_bytes).
func (*GroupElement) Mult ¶
func (ge *GroupElement) Mult(scalar []byte) (*GroupElement, error)
Mult multiplies the point by scalar and returns the resulting group element, mirroring RbNaCl::GroupElement#mult. A wrong-length scalar yields a *LengthError; a result of all zeroes (a small-order input point) yields a *BadAuthenticatorError, exactly where libsodium's crypto_scalarmult returns -1.
type LengthError ¶
type LengthError struct {
// What names the offending value, e.g. "key", "nonce", "public key".
What string
// Got is the byte length that was supplied.
Got int
// Want is the byte length libsodium requires.
Want int
}
LengthError is raised when a value handed to the library is not the exact size libsodium mandates (RbNaCl::LengthError). It names the value, the length it received and the length it wanted.
func (*LengthError) Error ¶
func (e *LengthError) Error() string
func (*LengthError) Unwrap ¶
func (e *LengthError) Unwrap() error
Unwrap ties every *LengthError to the ErrLength (and thereby ErrCrypto) root so errors.Is(err, ErrLength) and errors.Is(err, ErrCrypto) both hold.
type PrivateKey ¶
type PrivateKey struct {
// contains filtered or unexported fields
}
PrivateKey is a Curve25519 secret key (RbNaCl::PrivateKey). Its matching PublicKey is derived by scalar multiplication of the Curve25519 base point.
func GeneratePrivateKey ¶
func GeneratePrivateKey() *PrivateKey
GeneratePrivateKey draws a fresh secret key from the system CSPRNG, mirroring RbNaCl::PrivateKey.generate.
func NewPrivateKey ¶
func NewPrivateKey(key []byte) (*PrivateKey, error)
NewPrivateKey wraps a 32-byte secret key, mirroring RbNaCl::PrivateKey.new. Any other length yields a *LengthError.
func (*PrivateKey) Bytes ¶
func (pk *PrivateKey) Bytes() []byte
Bytes returns a copy of the raw secret key (RbNaCl::PrivateKey#to_bytes).
func (*PrivateKey) PublicKey ¶
func (pk *PrivateKey) PublicKey() *PublicKey
PublicKey derives the matching public key (RbNaCl::PrivateKey#public_key).
type PublicKey ¶
type PublicKey struct {
// contains filtered or unexported fields
}
PublicKey is a Curve25519 public key (RbNaCl::PublicKey).
func NewPublicKey ¶
NewPublicKey wraps a 32-byte public key, mirroring RbNaCl::PublicKey.new. Any other length yields a *LengthError.
type SecretBox ¶
type SecretBox struct {
// contains filtered or unexported fields
}
SecretBox is symmetric authenticated encryption with the XSalsa20 stream cipher and a Poly1305 MAC (RbNaCl::SecretBox). A single 32-byte key both encrypts and authenticates; a fresh 24-byte nonce is required for every message.
func NewSecretBox ¶
NewSecretBox constructs a SecretBox from a 32-byte key, mirroring RbNaCl::SecretBox.new(key). A key of any other length yields a *LengthError.
func (*SecretBox) Decrypt ¶
Decrypt opens a combined ciphertext produced by Encrypt and returns the plaintext, mirroring RbNaCl::SecretBox#decrypt. A wrong-length nonce yields a *LengthError; a ciphertext that is too short or fails its Poly1305 check yields a *BadAuthenticatorError.
type SigningKey ¶
type SigningKey struct {
// contains filtered or unexported fields
}
SigningKey is an Ed25519 secret signing key (RbNaCl::SigningKey). It is carried as its 32-byte seed, exactly as rbnacl stores it; the full expanded private key is derived on demand.
func GenerateSigningKey ¶
func GenerateSigningKey() *SigningKey
GenerateSigningKey draws a fresh signing key from the system CSPRNG, mirroring RbNaCl::SigningKey.generate.
func NewSigningKey ¶
func NewSigningKey(seed []byte) (*SigningKey, error)
NewSigningKey wraps a 32-byte seed, mirroring RbNaCl::SigningKey.new(seed). Any other length yields a *LengthError.
func (*SigningKey) Seed ¶
func (sk *SigningKey) Seed() []byte
Seed returns a copy of the 32-byte seed (RbNaCl::SigningKey#to_bytes).
func (*SigningKey) Sign ¶
func (sk *SigningKey) Sign(message []byte) []byte
Sign returns the 64-byte detached Ed25519 signature over message, mirroring RbNaCl::SigningKey#sign.
func (*SigningKey) VerifyKey ¶
func (sk *SigningKey) VerifyKey() *VerifyKey
VerifyKey derives the matching public key (RbNaCl::SigningKey#verify_key).
type VerifyKey ¶
type VerifyKey struct {
// contains filtered or unexported fields
}
VerifyKey is an Ed25519 public verification key (RbNaCl::VerifyKey).
func NewVerifyKey ¶
NewVerifyKey wraps a 32-byte public key, mirroring RbNaCl::VerifyKey.new. Any other length yields a *LengthError.
