Recursive AI

AES-OCB encryption and decryption in C#

OneCrypto is a free, open-source cryptography library for .NET from Recursive AI. MIT or Apache-2.0, preview, no native dependencies.

AES-OCB encrypts a message and checks whether it was changed, using an authentication tag.

Use a new nonce for every message encrypted under the same key.

Terminal
dotnet add package RecursiveAI.OneCrypto --prerelease

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneCrypto.Primitives;
using System.Security.Cryptography;
using System.Text;
 
byte[] key = RandomNumberGenerator.GetBytes(32);
byte[] nonce = RandomNumberGenerator.GetBytes(15);
using var ocb = new AesOcb(key);
CryptographicOperations.ZeroMemory(key);
byte[] ciphertext = new byte[5], tag = new byte[16];
ocb.Encrypt(nonce, "hello"u8, ciphertext, tag);
byte[] plaintext = new byte[5];
ocb.Decrypt(nonce, ciphertext, tag, plaintext);
Console.WriteLine(Encoding.UTF8.GetString(plaintext));
Text
hello

Unzip the example, then dotnet run.

The full program

This example authenticates the unencrypted header message:v1 along with hello OCB, then rejects a changed tag. Each run generates a fresh key and nonce; the program does not save the key.

C#
using RecursiveAI.OneCrypto.Primitives;
using System.Security.Cryptography;
using System.Text;
 
byte[] key = RandomNumberGenerator.GetBytes(32);
byte[] nonce = RandomNumberGenerator.GetBytes(15);
byte[] message = "hello OCB"u8.ToArray();
byte[] header = "message:v1"u8.ToArray();
using var ocb = new AesOcb(key);
CryptographicOperations.ZeroMemory(key);
byte[] ciphertext = new byte[message.Length];
byte[] tag = new byte[ocb.TagSizeInBytes];
ocb.Encrypt(nonce, message, ciphertext, tag, header);
 
byte[] plaintext = new byte[ciphertext.Length];
ocb.Decrypt(nonce, ciphertext, tag, plaintext, header);
Console.WriteLine($"Decrypted: {Encoding.UTF8.GetString(plaintext)}");
Console.WriteLine($"Ciphertext: {ciphertext.Length} bytes; tag: {tag.Length} bytes");
 
tag[0] ^= 1;
try
{
    ocb.Decrypt(nonce, ciphertext, tag, plaintext, header);
    throw new InvalidOperationException("Tampered tag accepted");
}
catch (AuthenticationTagMismatchException)
{
    Console.WriteLine("Tampered tag: rejected");
    Console.WriteLine($"Destination cleared: {plaintext.All(b => b == 0)}");
}
Text
Decrypted: hello OCB
Ciphertext: 9 bytes; tag: 16 bytes
Tampered tag: rejected
Destination cleared: True

If authentication fails, Decrypt throws AuthenticationTagMismatchException and zeroes the destination; do not use that buffer before the call returns.

Variations

Use a 12-byte tag and return false on authentication failure

Set the tag length in the constructor, not by truncating a tag afterward. This standalone example deliberately changes a tag and uses TryDecrypt instead of catching an exception.

C#
using RecursiveAI.OneCrypto.Primitives;
using System.Security.Cryptography;
 
byte[] key = RandomNumberGenerator.GetBytes(32);
byte[] nonce = RandomNumberGenerator.GetBytes(15);
using var ocb = new AesOcb(key, tagSizeInBytes: 12);
CryptographicOperations.ZeroMemory(key);
byte[] ciphertext = new byte[5], tag = new byte[12];
ocb.Encrypt(nonce, "hello"u8, ciphertext, tag);
byte[] plaintext = new byte[5];
tag[0] ^= 1;
bool valid = ocb.TryDecrypt(nonce, ciphertext, tag, plaintext);
Console.WriteLine($"Authenticated: {valid}; tag: {tag.Length} bytes");
Text
Authenticated: False; tag: 12 bytes

The short answer

For C# AES-OCB encryption, use AesOcb from RecursiveAI.OneCrypto.Primitives. Construct it with an AES key, allocate separate ciphertext and tag buffers, and call Encrypt. To decrypt, supply the same key, nonce, tag length and associated data to Decrypt. Only consume the plaintext after authentication succeeds.

OneCrypto implements OCB3, the version specified in RFC 7253. Its AES block operation comes from the platform; OneCrypto supplies the mode. The example download pins the published preview package so its API matches the code on this page.

What is OCB3 encryption?

OCB3 is authenticated encryption with associated data: it hides the message and detects changes to both the ciphertext and any associated data. Associated data is an optional, unencrypted byte sequence, such as a protocol header. It must match exactly when decrypting. It is not a place for secrets.

The full program uses message:v1 as associated data. A receiver must provide those exact bytes, not just a string that looks similar. Altering the header causes authentication to fail just as altering the ciphertext or tag does. The AES modes documentation describes the buffer and failure behavior.

OCB3 is not a file format. These calls do not serialize a nonce, attach a tag or identify an algorithm for a recipient. When storing a message, define how your application records the nonce, ciphertext, tag and any header the receiver needs. Keep the secret key separate. Base64 can represent the resulting bytes as text, but does not encrypt them.

How do you encrypt and decrypt with an AES-256 key in C#?

The snippet at the top generates a 32-byte key, which selects AES-256. OneCrypto also accepts 16-byte and 24-byte AES keys. The ciphertext buffer has exactly the plaintext’s byte length: OCB accepts partial blocks, so this API does not ask for padding. The tag occupies a separate buffer, 16 bytes by default.

The constructor copies the key, so the example clears the caller’s key array afterward. The using declaration disposes the OCB object when its scope ends. For a real exchange, the recipient must already have the same secret key through your application’s key-management scheme; generating a different key at the receiving end will not decrypt the message. A password’s UTF-8 bytes are not a substitute for a randomly generated AES key.

A key object is not safe for concurrent use. Give each thread its own instance. This implementation also needs platform AES support and cannot run in a browser. Those constraints and the supported sizes are documented in the pinned AES modes guide.

How do the OCB nonce and authentication tag work?

A nonce distinguishes messages encrypted under the same key. It is not secret, but it must never repeat with that key. OneCrypto accepts nonces from 1 to 15 bytes; the examples use 15. For a long-lived key, manage uniqueness across restarts and all senders, not just within one method call. See RFC 7253’s nonce requirements.

The authentication tag is checked during decryption. OneCrypto accepts tag lengths from 8 to 16 bytes and fixes the length when constructing the object. OCB binds that choice into nonce formatting, so generating a 16-byte tag and cutting it to 12 bytes is not equivalent to constructing an object for 12-byte tags. Both sides must agree on the length.

An authentication failure does not identify which input was wrong. A different key, modified nonce, changed ciphertext, altered tag or mismatched associated data can all prevent successful decryption. Decrypt throws; TryDecrypt returns false. Both clear the destination on an authentication failure. Treat the entire message as rejected rather than attempting to recover part of it.

All onecrypto recipes