sodium

package module
v0.0.0-...-8abc581 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: BSD-3-Clause Imports: 16 Imported by: 0

README

go-ruby-sodium/sodium

sodium — go-ruby-sodium

Docs License Go Coverage

A pure-Go (no cgo) reimplementation of Ruby's rbnacl gem — the libsodium/NaCl binding. It mirrors RbNaCl's public surface (RbNaCl::SecretBox, RbNaCl::Box, RbNaCl::SigningKey / VerifyKey, RbNaCl::Hash, RbNaCl::Auth, RbNaCl::PasswordHash, RbNaCl::GroupElement, RbNaCl::AEAD, RbNaCl::Random) and produces byte-identical ciphertexts, signatures and digests to libsodium — without any C, cgo or libsodium.

Where the rbnacl gem is a thin C extension over libsodium, this port stands on the pure-Go crypto in golang.org/x/crypto and the standard library: it consumes rather than reinvents the primitives.

It is the NaCl/libsodium backend for go-embedded-ruby, but is a standalone, reusable module — a sibling of go-ruby-bcrypt (the OpenBSD bcrypt port), go-ruby-jwt and go-ruby-regexp.

What it consumes

Every primitive is delegated to audited pure-Go code — no hand-rolled crypto:

RbNaCl surface Primitive Backend
SecretBox XSalsa20-Poly1305 golang.org/x/crypto/nacl/secretbox
Box / PrivateKey / PublicKey Curve25519-XSalsa20-Poly1305 golang.org/x/crypto/nacl/box
SigningKey / VerifyKey Ed25519 crypto/ed25519
Hash.sha256 / .sha512 SHA-2 crypto/sha256, crypto/sha512
Hash.blake2b BLAKE2b (sized + keyed) golang.org/x/crypto/blake2b
Auth::HMAC HMAC-SHA-256/512/512256 crypto/hmac
PasswordHash.argon2 / .argon2id Argon2i / Argon2id golang.org/x/crypto/argon2
PasswordHash.scrypt scrypt golang.org/x/crypto/scrypt
GroupElement Curve25519 scalar mult (X25519) golang.org/x/crypto/curve25519
AEAD ChaCha20-Poly1305 IETF / XChaCha20 golang.org/x/crypto/chacha20poly1305
Random CSPRNG crypto/rand

Features

  • Symmetric auth-encSecretBox (XSalsa20-Poly1305): Encrypt / Decrypt, 32-byte key, 24-byte nonce, 16-byte Poly1305 tag.
  • Public-key auth-encBox (Curve25519-XSalsa20-Poly1305) with PrivateKey / PublicKey, precomputed shared key (crypto_box_beforenm).
  • SignaturesSigningKey / VerifyKey (Ed25519), Sign / Verify, GenerateSigningKey.
  • HashingSHA256, SHA512, Blake2b with DigestSize and Key.
  • MACsNewHMACSHA256 / SHA512 / SHA512256 (Auth / Verify).
  • Password hashingArgon2i, Argon2id, Scrypt.
  • Scalar multiplicationGroupElement.Mult, ScalarMultBase (X25519).
  • AEADNewChaCha20Poly1305IETF (12-byte nonce), NewXChaCha20Poly1305IETF (24-byte nonce), with associated data.
  • Error treeErrCryptoErrLength (*LengthError) and ErrBadAuthenticator (*BadAuthenticatorError), mirroring RbNaCl's CryptoError / LengthError / BadAuthenticatorError and matchable with errors.Is / errors.As. Exact libsodium key/nonce/tag byte lengths.

CGO-free, 100% test coverage, gofmt + go vet clean, -race clean, and green across the six 64-bit Go targets (amd64, arm64, riscv64, loong64, ppc64le, s390x — big-endian).

Note. golang.org/x/crypto/blake2b implements the sized, keyed generichash but not the salt/personalization parameter-block variant, so Blake2b supports DigestSize and Key and rejects a non-empty Salt or Personal rather than silently ignoring it.

Install

go get github.com/go-ruby-sodium/sodium

Usage

package main

import (
	"fmt"

	"github.com/go-ruby-sodium/sodium"
)

func main() {
	// SecretBox: symmetric authenticated encryption.
	key := sodium.RandomBytes(sodium.SecretBoxKeyBytes)
	nonce := sodium.RandomBytes(sodium.SecretBoxNonceBytes)
	sb, _ := sodium.NewSecretBox(key)
	ct, _ := sb.Encrypt(nonce, []byte("attack at dawn"))
	pt, _ := sb.Decrypt(nonce, ct)
	fmt.Printf("%s\n", pt) // attack at dawn

	// Box: public-key authenticated encryption.
	alice := sodium.GeneratePrivateKey()
	bob := sodium.GeneratePrivateKey()
	box := sodium.NewBox(bob.PublicKey(), alice)
	sealed, _ := box.Encrypt(nonce, []byte("hi bob"))
	_ = sealed

	// Ed25519 signatures.
	sk := sodium.GenerateSigningKey()
	sig := sk.Sign([]byte("sign me"))
	fmt.Println(sk.VerifyKey().Verify(sig, []byte("sign me"))) // <nil>
}

Tests & coverage

The suite is deterministic and network-free — it drives every primitive with published test vectors: the NaCl reference ciphertexts (generated by the C implementation of NaCl) for SecretBox and Box, RFC 8032 for Ed25519, RFC 8439 for ChaCha20-Poly1305, RFC 7748 for X25519, RFC 7693 for BLAKE2b, RFC 4231 for HMAC, RFC 7914 for scrypt, and Argon2 reference-validated goldens. Encrypt / decrypt / sign / verify / hash reproduce the exact expected bytes; a tampered ciphertext or signature raises *BadAuthenticatorError; a wrong-length key, nonce or tag raises *LengthError. These alone hold coverage at 100%, so the qemu cross-arch and Windows lanes pass the gate with no Ruby or libsodium present.

COVERPKG=$(go list ./... | paste -sd, -)
go test -race -coverpkg="$COVERPKG" -coverprofile=cover.out ./...
go tool cover -func=cover.out | tail -1   # 100.0%

License

BSD-3-Clause — see LICENSE. Copyright the go-ruby-sodium/sodium authors.

WebAssembly

Being pure Go (CGO=0), this library also compiles to WebAssembly — both GOOS=js GOARCH=wasm (browser / Node.js) and GOOS=wasip1 GOARCH=wasm (WASI). CI builds both targets on every push, alongside the six 64-bit native/qemu arches.

GOOS=js     GOARCH=wasm go build ./...   # browser / Node
GOOS=wasip1 GOARCH=wasm go build ./...   # WASI (wasmtime, wasmer, wasmedge, …)

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

View Source
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_*.

View Source
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}.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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}.

View Source
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

View Source
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

func RandomBytes(n int) []byte

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 SHA256

func SHA256(message []byte) []byte

SHA256 returns the SHA-256 digest of message, mirroring RbNaCl::Hash.sha256.

func SHA512

func SHA512(message []byte) []byte

SHA512 returns the SHA-512 digest of message, mirroring RbNaCl::Hash.sha512.

func ScalarMultBase

func ScalarMultBase(scalar []byte) ([]byte, error)

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

func Scrypt(password, salt []byte, n, r, p, digestSize int) ([]byte, error)

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

func NewChaCha20Poly1305IETF(key []byte) (*AEAD, error)

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

func NewXChaCha20Poly1305IETF(key []byte) (*AEAD, error)

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

func (a *AEAD) Decrypt(nonce, ciphertext, additionalData []byte) ([]byte, error)

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

func (a *AEAD) Encrypt(nonce, message, additionalData []byte) ([]byte, error)

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

func (a *AEAD) NonceBytes() int

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

func (b *Box) Decrypt(nonce, ciphertext []byte) ([]byte, error)

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.

func (*Box) Encrypt

func (b *Box) Encrypt(nonce, message []byte) ([]byte, error)

Encrypt seals message under nonce for the recipient and returns the combined ciphertext (16-byte tag followed by the encrypted bytes), mirroring RbNaCl::Box#encrypt. A wrong-length nonce yields a *LengthError.

func (*Box) SharedKey

func (b *Box) SharedKey() []byte

SharedKey returns a copy of the precomputed 32-byte shared secret (RbNaCl::Box's crypto_box_beforenm output).

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

func NewPublicKey(key []byte) (*PublicKey, error)

NewPublicKey wraps a 32-byte public key, mirroring RbNaCl::PublicKey.new. Any other length yields a *LengthError.

func (*PublicKey) Bytes

func (pub *PublicKey) Bytes() []byte

Bytes returns a copy of the raw public key (RbNaCl::PublicKey#to_bytes).

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

func NewSecretBox(key []byte) (*SecretBox, error)

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

func (sb *SecretBox) Decrypt(nonce, ciphertext []byte) ([]byte, error)

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.

func (*SecretBox) Encrypt

func (sb *SecretBox) Encrypt(nonce, message []byte) ([]byte, error)

Encrypt seals message under nonce and returns the combined ciphertext (the 16-byte Poly1305 tag followed by the encrypted bytes), mirroring RbNaCl::SecretBox#encrypt. A nonce of the wrong length yields a *LengthError.

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

func NewVerifyKey(pub []byte) (*VerifyKey, error)

NewVerifyKey wraps a 32-byte public key, mirroring RbNaCl::VerifyKey.new. Any other length yields a *LengthError.

func (*VerifyKey) Bytes

func (vk *VerifyKey) Bytes() []byte

Bytes returns a copy of the raw public key (RbNaCl::VerifyKey#to_bytes).

func (*VerifyKey) Verify

func (vk *VerifyKey) Verify(signature, message []byte) error

Verify checks the 64-byte signature over message, mirroring RbNaCl::VerifyKey#verify. It returns nil on success; a wrong-length signature yields a *LengthError and a signature that does not verify yields a *BadAuthenticatorError (RbNaCl::BadSignatureError).

Jump to

Keyboard shortcuts

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