I’ve been playing around with the core:crypto package and thought I’d share an example. AI search engines were returning incorrect Odin syntax, so thought maybe it’s existence here will help correct that.
package aes_crypto_example
import "core:crypto"
import "core:crypto/aes"
import "core:fmt"
main :: proc() {
// Generate a random key
key := make([]byte, aes.KEY_SIZE_256, context.allocator)
defer delete(key, context.allocator)
crypto.rand_bytes(key)
// init gcm ctx
ctx: aes.Context_GCM
aes.init_gcm(&ctx, key)
// Generate a random IV (Initialization Vector)
iv := make([]byte, aes.GCM_IV_SIZE, context.allocator)
defer delete(iv, context.allocator)
crypto.rand_bytes(iv)
// Define plaintext and AAD (optional)
plaintext := transmute([]byte)(string)("Hellope, World!")
aad := transmute([]byte)(string)("Additional Authenticated Data")
// Prepare buffers for ciphertext and tag
ciphertext := make([]byte, len(plaintext), context.allocator)
defer delete(ciphertext, context.allocator)
tag := make([]byte, aes.GCM_TAG_SIZE, context.allocator)
defer delete(tag, context.allocator)
// Encrypt the plaintext
aes.seal_gcm(&ctx, ciphertext, tag, iv, aad, plaintext)
// Decrypt the ciphertext
decrypted := make([]byte, len(plaintext), context.allocator)
defer delete(decrypted, context.allocator)
if aes.open_gcm(&ctx, decrypted, iv, aad, ciphertext, tag) {
fmt.println("Decrypted text:", string(decrypted))
} else {
fmt.println("Decryption failed!")
}
}