CDC Badge OS
Firmware for the CDC Badge v1.0 hardware security key
Loading...
Searching...
No Matches
Crypto.h
Go to the documentation of this file.
1
10
11#pragma once
12
13#include <mbedtls/gcm.h>
14
15#include <cstddef>
16#include <cstdint>
17
18namespace cdc::core {
19
22public:
23 GcmContext() { mbedtls_gcm_init(&ctx_); }
24 ~GcmContext() { mbedtls_gcm_free(&ctx_); }
25 GcmContext(const GcmContext&) = delete;
26 GcmContext& operator=(const GcmContext&) = delete;
30 mbedtls_gcm_context* get() { return &ctx_; }
31private:
32 mbedtls_gcm_context ctx_;
33};
34
48inline bool aesGcm256Seal(const uint8_t key[32],
49 const uint8_t* iv, size_t ivLen,
50 const uint8_t* aad, size_t aadLen,
51 const uint8_t* pt, size_t ptLen,
52 uint8_t* ctOut, uint8_t tagOut[16]) {
53 GcmContext gcm;
54 int rc = mbedtls_gcm_setkey(gcm.get(), MBEDTLS_CIPHER_ID_AES, key, 256);
55 if (rc == 0) {
56 rc = mbedtls_gcm_crypt_and_tag(
57 gcm.get(), MBEDTLS_GCM_ENCRYPT, ptLen,
58 iv, ivLen,
59 aad, aadLen,
60 pt, ctOut,
61 16, tagOut);
62 }
63 return rc == 0;
64}
65
79inline bool aesGcm256Open(const uint8_t key[32],
80 const uint8_t* iv, size_t ivLen,
81 const uint8_t* aad, size_t aadLen,
82 const uint8_t* ct, size_t ctLen,
83 const uint8_t tag[16], uint8_t* ptOut) {
84 GcmContext gcm;
85 int rc = mbedtls_gcm_setkey(gcm.get(), MBEDTLS_CIPHER_ID_AES, key, 256);
86 if (rc == 0) {
87 rc = mbedtls_gcm_auth_decrypt(
88 gcm.get(), ctLen,
89 iv, ivLen,
90 aad, aadLen,
91 tag, 16,
92 ct, ptOut);
93 }
94 return rc == 0;
95}
96
97} // namespace cdc::core
RAII wrapper around mbedtls_gcm_context. Non-copyable, non-movable.
Definition Crypto.h:21
GcmContext & operator=(const GcmContext &)=delete
GcmContext(const GcmContext &)=delete
mbedtls_gcm_context * get()
Returns the underlying mbedTLS context.
Definition Crypto.h:30
GcmContext(GcmContext &&)=delete
GcmContext & operator=(GcmContext &&)=delete
bool aesGcm256Seal(const uint8_t key[32], const uint8_t *iv, size_t ivLen, const uint8_t *aad, size_t aadLen, const uint8_t *pt, size_t ptLen, uint8_t *ctOut, uint8_t tagOut[16])
Encrypts pt with AES-256-GCM and produces a 16-byte tag.
Definition Crypto.h:48
bool aesGcm256Open(const uint8_t key[32], const uint8_t *iv, size_t ivLen, const uint8_t *aad, size_t aadLen, const uint8_t *ct, size_t ctLen, const uint8_t tag[16], uint8_t *ptOut)
Authenticates and decrypts ct with AES-256-GCM.
Definition Crypto.h:79