Skip to content

Instantly share code, notes, and snippets.

@jpbland1
Created December 15, 2022 15:40
Embed
What would you like to do?
wolfSSL HPKE example
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <wolfssl/options.h>
#include <wolfssl/wolfcrypt/settings.h>
#include <wolfssl/wolfcrypt/hpke.h>
void main()
{
int ret = 0;
int rngRet = 0;
Hpke hpke[1];
WC_RNG rng[1];
const char* start_text = "this is a test";
const char* info_text = "info";
const char* aad_text = "aad";
byte ciphertext[MAX_HPKE_LABEL_SZ];
byte plaintext[MAX_HPKE_LABEL_SZ];
void* receiverKey = NULL;
void* ephemeralKey = NULL;
uint8_t pubKey[HPKE_Npk_MAX]; /* public key */
word16 pubKeySz = (word16)sizeof(pubKey);
ret = wc_HpkeInit(hpke, DHKEM_X25519_HKDF_SHA256, HKDF_SHA256,
HPKE_AES_128_GCM, NULL); /* or HPKE_AES_256_GCM */
if (ret != 0)
return ret;
rngRet = ret = wc_InitRng(rng);
if (ret != 0)
return ret;
/* generate the keys */
if (ret == 0)
ret = wc_HpkeGenerateKeyPair(hpke, &ephemeralKey, rng);
if (ret == 0)
ret = wc_HpkeGenerateKeyPair(hpke, &receiverKey, rng);
/* seal */
if (ret == 0)
ret = wc_HpkeSealBase(hpke, ephemeralKey, receiverKey,
(byte*)info_text, (word32)XSTRLEN(info_text),
(byte*)aad_text, (word32)XSTRLEN(aad_text),
(byte*)start_text, (word32)XSTRLEN(start_text),
ciphertext);
/* export ephemeral key */
if (ret == 0)
ret = wc_HpkeSerializePublicKey(hpke, ephemeralKey, pubKey, &pubKeySz);
/* open with exported ephemeral key */
if (ret == 0)
ret = wc_HpkeOpenBase(hpke, receiverKey, pubKey, pubKeySz,
(byte*)info_text, (word32)XSTRLEN(info_text),
(byte*)aad_text, (word32)XSTRLEN(aad_text),
ciphertext, (word32)XSTRLEN(start_text),
plaintext);
if (ret == 0)
ret = XMEMCMP(plaintext, start_text, XSTRLEN(start_text));
if (ephemeralKey != NULL)
wc_HpkeFreeKey(hpke->kem, ephemeralKey);
if (receiverKey != NULL)
wc_HpkeFreeKey(hpke->kem, receiverKey);
if (rngRet == 0)
wc_FreeRng(rng);
if (ret == 0)
printf("SUCCESS");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment