...

Package chacha20poly1305

import "golang.org/x/crypto/chacha20poly1305"
Overview
Index
Examples

Overview ▾

Package chacha20poly1305 implements the ChaCha20-Poly1305 AEAD as specified in RFC 7539, and its extended nonce variant XChaCha20-Poly1305.

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

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

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

func NewX

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.

Example

Code:

aead, err := NewX(key)
if err != nil {
    log.Fatalln("Failed to instantiate XChaCha20-Poly1305:", err)
}

for _, msg := range []string{
    "Attack at dawn.",
    "The eagle has landed.",
    "Gophers, gophers, gophers everywhere!",
} {
    // Encryption.
    nonce := make([]byte, NonceSizeX)
    if _, err := cryptorand.Read(nonce); err != nil {
        panic(err)
    }
    ciphertext := aead.Seal(nil, nonce, []byte(msg), nil)

    // Decryption.
    plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
    if err != nil {
        log.Fatalln("Failed to decrypt or authenticate message:", err)
    }

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

Output:

Attack at dawn.
The eagle has landed.
Gophers, gophers, gophers everywhere!