silk.crypto.aes_gcm.
Encrypt and authenticate data with AES-128-GCM, AES-192-GCM, or AES-256-GCM (NIST SP 800-38D).
When to use#
Use AesGcm.seal to encrypt a message so that only holders of the key can read it and any
change is detected. Use AesGcm.open to check and decrypt it. If the protocol does not name
an algorithm, silk.crypto.chacha20_poly1305 is also a good choice.
Details#
The key is 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256). The nonce is usually
12 bytes; any other nonzero length is hashed into the first counter block, as NIST SP 800-38D
says. The tag is 16 bytes, or a prefix of 4, 8 or 12 to 15 bytes. The tag is separate from the ciphertext ("detached"), so store or send
both. The associated data (aad) is authenticated but not encrypted. Use it for headers that
must stay readable. The ciphertext has the same length as the plaintext. Nothing allocates.
When one key protects many messages, prepare it once with AesGcmKey, whose seal and
open skip the key schedule.
For data that arrives in parts, such as a stream or a Node.js createCipheriv call, use
AesGcmEncryptor and AesGcmDecryptor. They take the message in any split, give the same
result, accept nonces of any nonzero length, and can write a truncated tag. On x86-64 they check
for AES-NI and PCLMULQDQ at run time, as AesGcm.seal and AesGcm.open do, and then run
the counter mode and GHASH eight blocks at a time.
Errors#
The functions return an AesGcmError. All checks come before the first write, and on any
error the output buffers do not change. AesGcm.open writes no plaintext unless the tag is
correct.
Gotchas#
The same key and nonce must never encrypt two messages. If they do, an attacker can recover the
XOR of the two plaintexts and forge tags. Use a counter, or 12 random bytes from
silk.system.random for a small number of messages per key.
Authentication does not stop replay: an attacker can send an old valid message again. The functions do not erase their copies of the key.
Examples#
Encrypt and decrypt a message#
import silk.crypto.aes_gcm { AesGcm, AesGcmError }
import silk.core.result { Result }
pub fn main() -> i32 {
let key: [u8; 16] = [0; 16]
let nonce: [u8; 12] = [0; 12]
let plaintext: [u8; 16] = [0; 16]
let mut ciphertext: [u8; 16] = [0; 16]
let mut tag: [u8; 16] = [0; 16]
match AesGcm.seal(&key, &nonce, b"header", &plaintext, &mut ciphertext, &mut tag) {
Result<(), AesGcmError>.Success { value: _ } => {}
Result<(), AesGcmError>.Failure { error: _ } => {
return 1
}
}
// For this key and nonce, the ciphertext starts with 0388dace.
if ciphertext[0] != 0x03 || ciphertext[1] != 0x88 {
return 1
}
let mut decrypted: [u8; 16] = [1; 16]
return match AesGcm.open(&key, &nonce, b"header", &ciphertext, &tag, &mut decrypted) {
Result<(), AesGcmError>.Success { value: _ } => {
if decrypted[0] != 0 || decrypted[15] != 0 {
return 1
}
return 0
}
Result<(), AesGcmError>.Failure { error: _ } => 1
}
}Detect a changed message#
import silk.crypto.aes_gcm { AesGcm, AesGcmError }
import silk.core.result { Result }
pub fn main() -> i32 {
let key: [u8; 32] = [7; 32]
let nonce: [u8; 12] = [1; 12]
let mut ciphertext: [u8; 5] = [0; 5]
let mut tag: [u8; 16] = [0; 16]
match AesGcm.seal(&key, &nonce, b"", b"hello", &mut ciphertext, &mut tag) {
Result<(), AesGcmError>.Success { value: _ } => {}
Result<(), AesGcmError>.Failure { error: _ } => {
return 1
}
}
ciphertext[0] = ciphertext[0] + 1
let mut plaintext: [u8; 5] = [0; 5]
return match AesGcm.open(&key, &nonce, b"", &ciphertext, &tag, &mut plaintext) {
Result<(), AesGcmError>.Failure { error: AesGcmError.AuthenticationFailed } => {
// The output does not change when the tag is wrong.
if plaintext[0] != 0 {
return 1
}
return 0
}
_ => 1
}
}Import as AesGcm with import silk.crypto.aes_gcm { AesGcm }.
Public declarations: 5.
AesGcmError#
pub union AesGcmErrorThe reason that AesGcm.seal or AesGcm.open rejected a call. The output buffers do not
change.
InvalidKeyLength#
InvalidKeyLengthThe key is not 16, 24, or 32 bytes.
InvalidNonceLength#
InvalidNonceLengthThe nonce is empty or longer than 2^61 - 1 bytes.
InvalidTagLength#
InvalidTagLengthThe tag, or the tag output, is not 4, 8, or 12 to 16 bytes.
OutputTooSmall#
OutputTooSmallThe output is shorter than the input message.
LimitExceeded#
LimitExceededThe message is longer than 2^36 - 32 bytes, or the associated data is longer than 2^61 - 1 bytes.
AuthenticationFailed#
AuthenticationFailedThe tag is not correct for the key, nonce, associated data, and ciphertext. The message was changed, or a value is wrong.
Implementation Debug for AesGcmError#
impl Debug for AesGcmErrorOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant and its fields, such as InvalidKeyLength.
AesGcm#
pub struct AesGcmFunctions that encrypt and authenticate with AES-128-GCM, AES-192-GCM, or AES-256-GCM (NIST SP 800-38D).
When to use#
Use AesGcm.seal to encrypt a message so that only holders of the key can read it and any
change is detected. Use AesGcm.open to check and decrypt it.
Details#
The key is 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256). The nonce is usually 12 bytes but can have any nonzero length. The tag is 16 bytes, or a prefix of 4, 8 or 12 to 15 bytes. The tag is separate from the ciphertext, so store or send both. The ciphertext has the same length as the plaintext. Nothing allocates. All checks come before the first write, and on any error the output buffers do not change.
Gotchas#
The same key and nonce must never encrypt two messages. If they do, an attacker can recover the XOR of the two plaintexts and forge tags. Authentication does not stop replay. The functions do not erase their copies of the key.
Implementation AesGcm#
impl AesGcmAssociated function seal#
pub fn seal(
key: &[u8],
nonce: &[u8],
aad: &[u8],
plaintext: &[u8],
ciphertext: &mut [u8],
tag: &mut [u8],
) -> Result<(), AesGcmError>Encrypts plaintext into ciphertext and writes the authentication tag to tag.
The key is 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256). The nonce is usually
12 bytes and can have any nonzero length. tag is 16 bytes for the full tag, or 4, 8 or 12 to
15 bytes for a prefix of it. aad is authenticated but not encrypted. Use it for headers that must stay readable.
The ciphertext has the same length as plaintext. ciphertext can be longer than
plaintext. The bytes after the written prefix do not change. The buffers must not overlap.
Nothing allocates.
Errors#
All checks come before the first write. On an error, ciphertext and tag do not change.
InvalidKeyLengthifkeyis not 16, 24, or 32 bytes.InvalidNonceLengthifnonceis empty or longer than 2^61 - 1 bytes.InvalidTagLengthiftagis not 4, 8, or 12 to 16 bytes.OutputTooSmallifciphertextis shorter thanplaintext.LimitExceededifplaintextis longer than 2^36 - 32 bytes oraadis longer than 2^61 - 1 bytes.
Gotchas#
Use a new nonce for each message under the same key. The function does not make one. If the
same key and nonce encrypt two messages, an attacker can recover the XOR of the two plaintexts
and forge tags. Use a counter, or 12 random bytes from silk.system.random for a small number
of messages per key. The function does not erase its copy of the key.
Associated function open#
pub fn open(
key: &[u8],
nonce: &[u8],
aad: &[u8],
ciphertext: &[u8],
tag: &[u8],
plaintext: &mut [u8],
) -> Result<(), AesGcmError>Checks tag, and if it is correct, decrypts ciphertext into plaintext.
The key is 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256), and the nonce is the
one given to AesGcm.seal. tag is 16 bytes, or a prefix of 4, 8 or 12 to 15 bytes, which
is compared in constant time. aad must be the same bytes that were given to
AesGcm.seal. The function checks every tag byte before it writes plaintext. The bytes
after the written prefix do not change. Nothing allocates.
Errors#
All checks come before the first write. On an error, plaintext does not change.
AuthenticationFailedif the tag is not correct for the key, nonce,aad, and ciphertext.InvalidKeyLengthifkeyis not 16, 24, or 32 bytes.InvalidNonceLengthifnonceis empty or longer than 2^61 - 1 bytes.InvalidTagLengthiftagis not 4, 8, or 12 to 16 bytes.OutputTooSmallifplaintextis shorter thanciphertext.LimitExceededifciphertextis longer than 2^36 - 32 bytes oraadis longer than 2^61 - 1 bytes.
Gotchas#
Authentication does not stop replay: an attacker can send an old valid message again. The function does not erase its copy of the key.
AesGcmKey#
pub struct AesGcmKeyAn AES-GCM key prepared once for many messages: its AES round keys and its GHASH key.
When to use#
Use it in place of AesGcm.seal and AesGcm.open when one key protects many messages,
such as the records of a TLS connection. Each of those calls computes the key schedule again,
which costs about as much as encrypting a few hundred bytes.
Details#
AesGcmKey.seal and AesGcmKey.open give the same output and errors as AesGcm.seal
and AesGcm.open with the same key bytes. With a 12-byte nonce and a 16-byte tag on a machine
with the AES instructions, they use the prepared key. Otherwise they run the same code as those
functions. Nothing allocates.
Gotchas#
The value holds a copy of the key and its schedule, and does not erase them when it is dropped.
The rules for nonces are those of AesGcm.seal.
Examples#
import silk.crypto.aes_gcm { AesGcmError, AesGcmKey }
import silk.core.result { Result }
pub fn main() -> i32 {
let key: [u8; 16] = [0; 16]
let prepared = match AesGcmKey.make(&key) {
Result<AesGcmKey, AesGcmError>.Success { value } => move value
Result<AesGcmKey, AesGcmError>.Failure { error: _ } => {
return 1
}
}
let nonce: [u8; 12] = [0; 12]
let plaintext: [u8; 16] = [0; 16]
let mut ciphertext: [u8; 16] = [0; 16]
let mut tag: [u8; 16] = [0; 16]
if let Result<(), AesGcmError>.Failure { error: _ } = prepared.seal(&nonce, b"header", &plaintext, &mut ciphertext, &mut tag) {
return 1
}
// The same ciphertext as `AesGcm.seal` with this key and nonce.
if ciphertext[0] != 0x03 || ciphertext[1] != 0x88 {
return 1
}
let mut decrypted: [u8; 16] = [1; 16]
return match prepared.open(&nonce, b"header", &ciphertext, &tag, &mut decrypted) {
Result<(), AesGcmError>.Success { value: _ } => if decrypted[0] == 0 { 0 } else { 1 }
Result<(), AesGcmError>.Failure { error: _ } => 1
}
}Implementation Transferable for AesGcmKey#
impl Transferable for AesGcmKeyImplementation AesGcmKey#
impl AesGcmKeyAssociated function make#
pub fn make(key: &[u8]) -> Result<AesGcmKey, AesGcmError>Prepares key, which is 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256).
Errors#
InvalidKeyLengthifkeyis not 16, 24, or 32 bytes.
Method seal#
pub fn seal(
self: &Self,
nonce: &[u8],
aad: &[u8],
plaintext: &[u8],
ciphertext: &mut [u8],
tag: &mut [u8],
) -> Result<(), AesGcmError>AesGcm.seal with this key: encrypts plaintext into ciphertext and writes the tag to
tag.
Errors#
The errors of AesGcm.seal, other than InvalidKeyLength. On an error, ciphertext and
tag do not change.
Method open#
pub fn open(
self: &Self,
nonce: &[u8],
aad: &[u8],
ciphertext: &[u8],
tag: &[u8],
plaintext: &mut [u8],
) -> Result<(), AesGcmError>AesGcm.open with this key: checks tag, and if it is correct, decrypts ciphertext into
plaintext.
Errors#
The errors of AesGcm.open, other than InvalidKeyLength. On an error, plaintext does
not change.
AesGcmEncryptor#
pub struct AesGcmEncryptorA streaming AES-GCM encryptor (NIST SP 800-38D) for a message that arrives in parts.
When to use#
Use it when the message does not fit in one buffer, or to implement an API that encrypts in
steps, such as createCipheriv("aes-256-gcm") in Node.js. For a message in one slice, use
AesGcm.seal.
Details#
Make one with AesGcmEncryptor.make and the associated data, give the message with
AesGcmEncryptor.update, then call AesGcmEncryptor.finish for the tag. Any split of the
message gives the same ciphertext and tag as AesGcm.seal. The key is 16, 24, or 32 bytes.
The nonce can have any nonzero length: a 12-byte nonce is used directly, and other lengths are
hashed as NIST SP 800-38D section 7.1 says. Nothing allocates.
Gotchas#
The same key and nonce must never encrypt two messages. Prefer 12-byte nonces, which are the
only length that AesGcm.seal takes. The value holds key material and is not erased when it
is dropped.
Implementation AesGcmEncryptor#
impl AesGcmEncryptorAssociated function make#
pub fn make(key: &[u8], nonce: &[u8], aad: &[u8]) -> Result<AesGcmEncryptor, AesGcmError>Returns an encryptor for key and nonce that authenticates the associated data aad.
aad is authenticated but not encrypted. Use it for headers that must stay readable. The
encryptor copies what it needs and does not borrow the arguments.
Errors#
InvalidKeyLengthifkeyis not 16, 24, or 32 bytes.InvalidNonceLengthifnonceis empty or longer than 2^61 - 1 bytes.LimitExceededifaadis longer than 2^61 - 1 bytes.
Method update#
pub fn update(self: &mut Self, plaintext: &[u8], ciphertext: &mut [u8]) -> Result<
(),
AesGcmError
>Encrypts plaintext into the first plaintext.length bytes of ciphertext.
The bytes of ciphertext after them do not change. The buffers must not overlap.
Errors#
On an error the state and ciphertext do not change.
OutputTooSmallifciphertextis shorter thanplaintext.LimitExceededif the message grows past 2^36 - 32 bytes.
Method finish#
pub fn finish(self: Self, tag: &mut [u8]) -> Result<(), AesGcmError>Writes the authentication tag to tag and consumes the state.
tag is 16 bytes for the full tag, or 4, 8, 12, 13, 14, or 15 bytes for a prefix of it, as
NIST SP 800-38D allows. Shorter tags are easier to forge.
Errors#
InvalidTagLengthiftaghas another length.tagdoes not change.
AesGcmDecryptor#
pub struct AesGcmDecryptorA streaming AES-GCM decryptor (NIST SP 800-38D) for a ciphertext that arrives in parts.
When to use#
Use it when the ciphertext does not fit in one buffer, or to implement an API that decrypts in
steps, such as createDecipheriv("aes-256-gcm") in Node.js. For a ciphertext in one slice, use
AesGcm.open, which writes no plaintext unless the tag is correct.
Details#
Make one with AesGcmDecryptor.make and the associated data, give the ciphertext with
AesGcmDecryptor.update, then call AesGcmDecryptor.finish with the received tag. The key
is 16, 24, or 32 bytes. The nonce can have any nonzero length. Nothing allocates.
Gotchas#
AesGcmDecryptor.update writes plaintext before the tag is checked. Do not use or release
that plaintext until AesGcmDecryptor.finish succeeds. The value holds key material and is
not erased when it is dropped.
Implementation AesGcmDecryptor#
impl AesGcmDecryptorAssociated function make#
pub fn make(key: &[u8], nonce: &[u8], aad: &[u8]) -> Result<AesGcmDecryptor, AesGcmError>Returns a decryptor for key and nonce that authenticates the associated data aad.
aad must be the same bytes that the encryptor got. The decryptor copies what it needs and
does not borrow the arguments.
Errors#
InvalidKeyLengthifkeyis not 16, 24, or 32 bytes.InvalidNonceLengthifnonceis empty or longer than 2^61 - 1 bytes.LimitExceededifaadis longer than 2^61 - 1 bytes.
Method update#
pub fn update(self: &mut Self, ciphertext: &[u8], plaintext: &mut [u8]) -> Result<
(),
AesGcmError
>Decrypts ciphertext into the first ciphertext.length bytes of plaintext.
The plaintext is not authenticated until AesGcmDecryptor.finish succeeds. The bytes of
plaintext after the written ones do not change. The buffers must not overlap.
Errors#
On an error the state and plaintext do not change.
OutputTooSmallifplaintextis shorter thanciphertext.LimitExceededif the ciphertext grows past 2^36 - 32 bytes.
Method finish#
pub fn finish(self: Self, tag: &[u8]) -> Result<(), AesGcmError>Checks the received tag and consumes the state.
tag is the full 16-byte tag or a 4, 8, 12, 13, 14, or 15-byte prefix of it. The comparison
takes the same time wherever the bytes differ.
Errors#
AuthenticationFailedif the tag is not correct for the key, nonce, associated data, and ciphertext. Discard all plaintext thatAesGcmDecryptor.updatewrote.InvalidTagLengthiftaghas another length.
Category: Cryptography.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.