crypto: golang.org/x/crypto/chacha20poly1305 Index | Examples | Files

package chacha20poly1305

import "golang.org/x/crypto/chacha20poly1305"

Package chacha20poly1305 implements the ChaCha20-Poly1305 AEAD and its extended nonce variant XChaCha20-Poly1305, as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01.

Index

Examples

Package Files

chacha20poly1305.go chacha20poly1305_amd64.go chacha20poly1305_generic.go xchacha20poly1305.go

Constants

const (
    // KeySize is the size of the key used by this AEAD, in bytes.
    KeySize = 32

    // NonceSize is the size of the nonce used with the standard variant of this
    // AEAD, in bytes.
    //
    // Note that this is too short to be safely generated at random if the same
    // key is reused more than 2³² times.
    NonceSize = 12

    // NonceSizeX is the size of the nonce used with the XChaCha20-Poly1305
    // variant of this AEAD, in bytes.
    NonceSizeX = 24
)

func New Uses

func New(key []byte) (cipher.AEAD, error)

New returns a ChaCha20-Poly1305 AEAD that uses the given 256-bit key.

func NewX Uses

func NewX(key []byte) (cipher.AEAD, error)

NewX returns a XChaCha20-Poly1305 AEAD that uses the given 256-bit key.

XChaCha20-Poly1305 is a ChaCha20-Poly1305 variant that takes a longer nonce, suitable to be generated randomly without risk of collisions. It should be preferred when nonce uniqueness cannot be trivially ensured, or whenever nonces are randomly generated.

Code:

// key should be randomly generated or derived from a function like Argon2.
key := make([]byte, KeySize)
if _, err := cryptorand.Read(key); err != nil {
    panic(err)
}

aead, err := NewX(key)
if err != nil {
    panic(err)
}

// Encryption.
var encryptedMsg []byte
{
    msg := []byte("Gophers, gophers, gophers everywhere!")

    // Select a random nonce, and leave capacity for the ciphertext.
    nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(msg)+aead.Overhead())
    if _, err := cryptorand.Read(nonce); err != nil {
        panic(err)
    }

    // Encrypt the message and append the ciphertext to the nonce.
    encryptedMsg = aead.Seal(nonce, nonce, msg, nil)
}

// Decryption.
{
    if len(encryptedMsg) < aead.NonceSize() {
        panic("ciphertext too short")
    }

    // Split nonce and ciphertext.
    nonce, ciphertext := encryptedMsg[:aead.NonceSize()], encryptedMsg[aead.NonceSize():]

    // Decrypt the message and check it wasn't tampered with.
    plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%s\n", plaintext)
}

Output:

Gophers, gophers, gophers everywhere!

Package chacha20poly1305 imports 7 packages (graph) and is imported by 357 packages. Updated 2020-10-24. Refresh now. Tools for package owners.