libsodium

package module
v0.0.0-...-0e73f94 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 12 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Reference

Go-Libsodium

Why

Libsodium should be easy.

How

A minimal cgo interface to the following Libsodium constructs:

What


func Init()

func StreamKeygen() (key []byte, err error)

func StreamEncrypt(key []byte, plainText io.Reader, cipherText io.Writer) error

func StreamDecrypt(key []byte, cipherText io.Reader, plainText io.Writer) error

func StreamEncryptRecipients(publicKeys [][]byte, plainText io.Reader, cipherText io.Writer) error

func NewKeyring(secretKeys [][]byte) (*Keyring, error)
func (ring *Keyring) Decrypt(cipherText io.Reader, plainText io.Writer) error

func BoxKeypair() (publicKey, secretKey []byte, err error)

func BoxSealedEncrypt(plainText, recipientPublicKey []byte) (cipherText []byte, err error)

func BoxSealedDecrypt(cipherText, recipientSecretKey []byte) (plainText []byte, err error)

func BoxEasyEncrypt(plainText, recipientPublicKey, senderSecretKey []byte) (cipherText []byte, err error)

func BoxEasyDecrypt(cipherText, senderPublicKey, recipientSecretKey []byte) (plainText []byte, err error)

func SignKeypair() (publicKey, secretKey []byte, err error)

func Sign(plainText, signerSecretKey []byte) (signedText []byte, err error)

func SignVerify(signedText, plainText, signerPublicKey []byte) error

Install

Requires Go 1.27+ and Libsodium. The keysource subpackage requires Linux.

brew install         go     libsodium     # homebrew
sudo pacman -S       go     libsodium     # arch
sudo apk add         go     libsodium-dev # alpine
sudo apt-get install golang libsodium-dev # ubuntu/debian
go get github.com/nathants/go-libsodium

Usage

Call Init() before cryptographic operations. Concurrent calls are safe and wait for one native initialization; native "already initialized" is also success. Native initialization failure remains a panic for every caller, and cryptographic operations still reject use before initialization. Configure StreamChunkSize before starting concurrent stream operations; concurrent mutation is unsupported.

package main

import (
	"bytes"
	"fmt"

	"github.com/nathants/go-libsodium"
)

func Stream() {
	libsodium.Init()
	key, err := libsodium.StreamKeygen()
	if err != nil {
		panic(err)
	}
	value := []byte("hello world")
	var cipher bytes.Buffer
	err = libsodium.StreamEncrypt(key, bytes.NewReader(value), &cipher)
	if err != nil {
		panic(err)
	}
	var plain bytes.Buffer
	err = libsodium.StreamDecrypt(key, bytes.NewReader(cipher.Bytes()), &plain)
	if err != nil {
		panic(err)
	}
	fmt.Println("stream", bytes.Equal(value, plain.Bytes()))
}

func StreamRecipients() {
	libsodium.Init()
	pk1, sk1, err := libsodium.BoxKeypair()
	if err != nil {
		panic(err)
	}
	pk2, sk2, err := libsodium.BoxKeypair()
	if err != nil {
		panic(err)
	}
	value := []byte("hello world")
	var cipher bytes.Buffer
	err = libsodium.StreamEncryptRecipients([][]byte{pk1, pk2}, bytes.NewReader(value), &cipher)
	if err != nil {
		panic(err)
	}
	var plain bytes.Buffer
	ring1, err := libsodium.NewKeyring([][]byte{sk1})
	if err != nil {
		panic(err)
	}
	err = ring1.Decrypt(bytes.NewReader(cipher.Bytes()), &plain)
	if err != nil {
		panic(err)
	}
	fmt.Println("recipient1", bytes.Equal(value, plain.Bytes()))
	plain.Reset()
	ring2, err := libsodium.NewKeyring([][]byte{sk2})
	if err != nil {
		panic(err)
	}
	err = ring2.Decrypt(bytes.NewReader(cipher.Bytes()), &plain)
	if err != nil {
		panic(err)
	}
	fmt.Println("recipient2", bytes.Equal(value, plain.Bytes()))
}

func BoxSeal() {
	libsodium.Init()
	value := []byte("hello world")
	pk, sk, err := libsodium.BoxKeypair()
	if err != nil {
	    panic(err)
	}
	cipher, err := libsodium.BoxSealedEncrypt(value, pk)
	if err != nil {
	    panic(err)
	}
	plain, err := libsodium.BoxSealedDecrypt(cipher, sk)
	if err != nil {
	    panic(err)
	}
	fmt.Println("seal", bytes.Equal(value, plain))
}

func BoxEasy() {
	value := []byte("hello world")
	pk1, sk1, err := libsodium.BoxKeypair()
	if err != nil {
	    panic(err)
	}
	pk2, sk2, err := libsodium.BoxKeypair()
	if err != nil {
	    panic(err)
	}
	cipher, err := libsodium.BoxEasyEncrypt(value, pk2, sk1)
	if err != nil {
	    panic(err)
	}
	plain, err := libsodium.BoxEasyDecrypt(cipher, pk1, sk2)
	if err != nil {
	    panic(err)
	}
	fmt.Println("easy", bytes.Equal(value, plain))
}

func Sign() {
	value := []byte("hello world")
	pk, sk, err := libsodium.SignKeypair()
	if err != nil {
	    panic(err)
	}
	signature, err := libsodium.Sign(value, sk)
	if err != nil {
	    panic(err)
	}
	err = libsodium.SignVerify(signature, value, pk)
	if err != nil {
	    panic(err)
	}
	fmt.Println("signature")
}

func main() {
	Stream()
	StreamRecipients()
	BoxSeal()
	BoxEasy()
	Sign()
}

Recipient key chains

KeyChains ([][][]byte) stores one recipient per row, with generations oldest first. ParseKeyChains and KeyChains.MarshalText use 64 lowercase hex characters per key, colons between generations, and newlines between recipients. Rows need not be sorted. Blank lines and a missing final newline are allowed; serialization emits one newline per nonempty row. Duplicates, comments, spaces, tabs, and CR are rejected. Limits: 1,024 generations per row, 65,536 keys, and 4,259,840 input bytes. Parsing accepts empty input; encryption and keyring construction require keys.

  • RotateKeyChain(public, secret) creates a pair or validates and extends an existing pair. Returned buffers are independent; no files are written.
  • KeyChains.Latest() selects public chain tips for StreamEncryptRecipients.
  • KeyChains.Keyring() includes all supplied private generations for decryption.
  • BoxPublicKey(secret) derives the corresponding public key.
  • ValidateKeyChainTransition(old, next) allows recipient additions/removals and extensions, rejects edits within retained chains, and requires a nonempty result. It does not authenticate or sign rotations.

Retain historical secrets to decrypt historical ciphertext. Rotation does not re-encrypt old data or revoke access to existing copies. The ciphertext format is unchanged; replace calls to the removed StreamDecryptRecipients with NewKeyring and Keyring.Decrypt.

Secret loading (Linux)

keysource.Load(ctx, remoteURL) returns a keyring from exactly one nonempty source:

  • GIT_REMOTE_AWS_SECRETKEY: private chain text.
  • GIT_REMOTE_AWS_SECRETKEY_FILE: bounded regular file, not a symlink, with only owner read/write permissions.
  • GIT_REMOTE_AWS_SECRETKEY_CMD: executable that prints private chains. It receives remoteURL when nonempty; commands are not evaluated by a shell.

Command output is bounded and omitted from errors. Cancellation, SIGINT/SIGTERM, or output overflow terminates the command process group. Interactive commands receive the foreground terminal; terminal-attached background loading is rejected. Prompting has no deadline; inherited output pipes get 250ms to drain after exit. This is not a process sandbox or a guarantee of cleanup after SIGKILL.

Tests

Requires Python 3.8+ for executable/terminal tests, and libcheck for bin/check.sh.

bash bin/check.sh
go test -cover ./...
go test -race ./...
go test -run '^$' -fuzz '^FuzzKeyChains$' -fuzztime=10s

testdata/pre-keychains.ciphertext preserves compatibility coverage against ciphertext generated by library revision 4e1a79aae4f3 with a public test-only key.

Documentation

Index

Constants

View Source
const (
	MaxKeyGenerations = 1024
	MaxChainKeys      = 65536
	MaxKeyChainsBytes = MaxChainKeys * 65
)

Variables

View Source
var (
	StreamChunkSize = 1024 * 1024
)

Functions

func BoxEasyDecrypt

func BoxEasyDecrypt(cipherText, senderPublicKey, recipientSecretKey []byte) (plainText []byte, err error)

func BoxEasyEncrypt

func BoxEasyEncrypt(plainText, recipientPublicKey, senderSecretKey []byte) (cipherText []byte, err error)

func BoxKeypair

func BoxKeypair() (publicKey, secretKey []byte, err error)

func BoxPublicKey

func BoxPublicKey(secret []byte) ([]byte, error)

BoxPublicKey derives the existing crypto_box public identity from its secret.

func BoxSealedDecrypt

func BoxSealedDecrypt(cipherText, recipientSecretKey []byte) (plainText []byte, err error)

func BoxSealedEncrypt

func BoxSealedEncrypt(plainText, recipientPublicKey []byte) (cipherText []byte, err error)

func Init

func Init()

Init initializes native sodium once and waits for concurrent callers. A native failure is replayed to every caller; cryptographic APIs remain unavailable.

func RotateKeyChain

func RotateKeyChain(public, secret KeyChains) (KeyChains, KeyChains, error)

RotateKeyChain validates one personal public/private pair, then returns both extended chains. Persistence is the caller's responsibility, private first.

func Sign

func Sign(plainText, signerSecretKey []byte) (signedText []byte, err error)

func SignKeypair

func SignKeypair() (publicKey, secretKey []byte, err error)

func SignVerify

func SignVerify(signedText, plainText, signerPublicKey []byte) error

func StreamDecrypt

func StreamDecrypt(key []byte, cipherText io.Reader, plainText io.Writer) error

func StreamEncrypt

func StreamEncrypt(key []byte, plainText io.Reader, cipherText io.Writer) error

func StreamEncryptRecipients

func StreamEncryptRecipients(publicKeys [][]byte, plainText io.Reader, cipherText io.Writer) error

func StreamKeygen

func StreamKeygen() (key []byte, err error)

func ValidateKeyChainTransition

func ValidateKeyChainTransition(old, next KeyChains) error

ValidateKeyChainTransition permits adding/removing recipients and appending generations. A retained first-generation identity cannot truncate or rewrite its chain. These are structural checks, not signed proof of succession.

Types

type KeyChains

type KeyChains [][][]byte

KeyChains contains one individual's generations per row, oldest first. Public and secret chains use the same syntax but must never share a file.

func ParseKeyChains

func ParseKeyChains(input io.Reader) (KeyChains, error)

ParseKeyChains reads lowercase hex generations separated by colons and recipient rows separated by LF. Row order is insignificant and preserved; generations remain oldest first. Blank lines and a missing final LF are allowed. Empty input is accepted; encryption still requires recipients.

func (KeyChains) Keyring

func (chains KeyChains) Keyring() (*Keyring, error)

func (KeyChains) Latest

func (chains KeyChains) Latest() ([][]byte, error)

Latest returns the current generation of every recipient, for new encryption.

func (KeyChains) MarshalText

func (chains KeyChains) MarshalText() ([]byte, error)

MarshalText validates and serializes chains without reordering generations.

type Keyring

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

Keyring routes each recipient header to a retained secret without retrying or buffering ciphertext. Construct it once per operation and do not mutate it.

func NewKeyring

func NewKeyring(secretKeys [][]byte) (*Keyring, error)

func (*Keyring) Decrypt

func (ring *Keyring) Decrypt(cipherText io.Reader, plainText io.Writer) error

Directories

Path Synopsis
Package keysource implements the shared, on-demand application key source.
Package keysource implements the shared, on-demand application key source.

Jump to

Keyboard shortcuts

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