ML‑KEM usage
Use the following example code to perform a post‑quantum key‑encapsulation exchange via Crypto Interface QS_* APIs.
Initiator
MSTATUS status = OK;
QS_CTX *pCtx = NULL;
ubyte *pPub = NULL;
ubyte4 pubLen = 0;
ubyte *pCipher = NULL;
ubyte4 cipherLen = 0;
ubyte *pSS = NULL;
ubyte4 ssLen = 0;
/* Create a new context shell for a ML-KEM-512 key */
status = CRYPTO_INTERFACE_QS_newCtx(&pCtx, cid_PQC_MLKEM_512);
if (OK != status)
goto exit;
/* generate a new key pair */
status = CRYPTO_INTERFACE_QS_generateKeyPair(pCtx, RANDOM_rngFun, g_pRandomContext);
if (OK != status)
goto exit;
/* get the public key in order to send it to the other party */
status = CRYPTO_INTERFACE_QS_getPublicKeyAlloc(pCtx, &pPub, &pubLen);
if (OK != status)
goto exit;
/* transmit the public key to the responder */
...
/* receive the responder's ciphertext from its encapsulation */
...
/* decapsulate to get a shared secret */
status = CRYPTO_INTERFACE_QS_KEM_decapsulateAlloc(pCtx, pCipher, cipherLen, &pSS, &ssLen);
exit:
/* Cleanup the context and other buffers, zero sensitive data */
(void) CRYPTO_INTERFACE_QS_deleteCtx(&pCtx);
(void) MOC_MEMSET_FREE(&pPub, pubLen);
(void) MOC_MEMSET_FREE(&pSS, ssLen);
return status;
Responder
MSTATUS status = OK;
QS_CTX *pCtx = NULL;
ubyte *pPub = NULL;
ubyte4 pubLen = 0;
ubyte *pCipher = NULL;
ubyte4 cipherLen = 0;
ubyte *pSS = NULL;
ubyte4 ssLen = 0;
/* Create a new context shell for a ML-KEM-512 key */
status = CRYPTO_INTERFACE_QS_newCtx(&pCtx, cid_PQC_MLKEM_512);
if (OK != status)
goto exit;
/* Receive the public key from the initiator */
...
/* Set the public key in the context */
status = CRYPTO_INTERFACE_QS_setPublicKey(pCtx, pPub, pubLen);
if (OK != status)
goto exit;
/* encapsulate to get a shared secret and ciphertext */
status = CRYPTO_INTERFACE_QS_KEM_encapsulateAlloc(pCtx, RANDOM_rngFun,
g_pRandomContext, &pCipher, &cipherLen, &pSS, &ssLen);
if (OK != status)
goto exit;
/* transmit the ciphertext to the initiator */
...
exit:
/* Cleanup the context and other buffers, zero sensitive data */
(void) CRYPTO_INTERFACE_QS_deleteCtx(&pCtx);
(void) MOC_MEMSET_FREE(&pCipher, cipherLen);
(void) MOC_MEMSET_FREE(&pSS, ssLen);
return status;