Path: blob/main/crypto/openssl/providers/implementations/encode_decode/ml_kem_codecs.c
48383 views
/*1* Copyright 2025 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89#include <string.h>10#include <openssl/byteorder.h>11#include <openssl/proverr.h>12#include <openssl/x509.h>13#include <openssl/core_names.h>14#include "internal/encoder.h"15#include "prov/ml_kem.h"16#include "ml_kem_codecs.h"1718/* Tables describing supported ASN.1 input/output formats. */1920/*-21* ML-KEM-512:22* Public key bytes: 800 (0x0320)23* Private key bytes: 1632 (0x0660)24*/25static const ML_COMMON_SPKI_FMT ml_kem_512_spkifmt = {26{ 0x30, 0x82, 0x03, 0x32, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48,270x01, 0x65, 0x03, 0x04, 0x04, 0x01, 0x03, 0x82, 0x03, 0x21, 0x00, }28};29static const ML_COMMON_PKCS8_FMT ml_kem_512_p8fmt[NUM_PKCS8_FORMATS] = {30{ "seed-priv", 0x06aa, 0, 0x308206a6, 0x0440, 6, 0x40, 0x04820660, 0x4a, 0x0660, 0, 0 },31{ "priv-only", 0x0664, 0, 0x04820660, 0, 0, 0, 0, 0x04, 0x0660, 0, 0 },32{ "oqskeypair", 0x0984, 0, 0x04820980, 0, 0, 0, 0, 0x04, 0x0660, 0x0664, 0x0320 },33{ "seed-only", 0x0042, 2, 0x8040, 0, 2, 0x40, 0, 0, 0, 0, 0 },34{ "bare-priv", 0x0660, 4, 0, 0, 0, 0, 0, 0, 0x0660, 0, 0 },35{ "bare-seed", 0x0040, 4, 0, 0, 0, 0x40, 0, 0, 0, 0, 0 },36};3738/*-39* ML-KEM-768:40* Public key bytes: 1184 (0x04a0)41* Private key bytes: 2400 (0x0960)42*/43static const ML_COMMON_SPKI_FMT ml_kem_768_spkifmt = {44{ 0x30, 0x82, 0x04, 0xb2, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48,450x01, 0x65, 0x03, 0x04, 0x04, 0x02, 0x03, 0x82, 0x04, 0xa1, 0x00, }46};47static const ML_COMMON_PKCS8_FMT ml_kem_768_p8fmt[NUM_PKCS8_FORMATS] = {48{ "seed-priv", 0x09aa, 0, 0x308209a6, 0x0440, 6, 0x40, 0x04820960, 0x4a, 0x0960, 0, 0, },49{ "priv-only", 0x0964, 0, 0x04820960, 0, 0, 0, 0, 0x04, 0x0960, 0, 0, },50{ "oqskeypair", 0x0e04, 0, 0x04820e00, 0, 0, 0, 0, 0x04, 0x0960, 0x0964, 0x04a0 },51{ "seed-only", 0x0042, 2, 0x8040, 0, 2, 0x40, 0, 0, 0, 0, 0, },52{ "bare-priv", 0x0960, 4, 0, 0, 0, 0, 0, 0, 0x0960, 0, 0, },53{ "bare-seed", 0x0040, 4, 0, 0, 0, 0x40, 0, 0, 0, 0, 0, },54};5556/*-57* ML-KEM-1024:58* Private key bytes: 3168 (0x0c60)59* Public key bytes: 1568 (0x0620)60*/61static const ML_COMMON_SPKI_FMT ml_kem_1024_spkifmt = {62{ 0x30, 0x82, 0x06, 0x32, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48,630x01, 0x65, 0x03, 0x04, 0x04, 0x03, 0x03, 0x82, 0x06, 0x21, 0x00, }64};65static const ML_COMMON_PKCS8_FMT ml_kem_1024_p8fmt[NUM_PKCS8_FORMATS] = {66{ "seed-priv", 0x0caa, 0, 0x30820ca6, 0x0440, 6, 0x40, 0x04820c60, 0x4a, 0x0c60, 0, 0 },67{ "priv-only", 0x0c64, 0, 0x04820c60, 0, 0, 0, 0, 0x04, 0x0c60, 0, 0 },68{ "oqskeypair", 0x1284, 0, 0x04821280, 0, 0, 0, 0, 0x04, 0x0c60, 0x0c64, 0x0620 },69{ "seed-only", 0x0042, 2, 0x8040, 0, 2, 0x40, 0, 0, 0, 0, 0 },70{ "bare-priv", 0x0c60, 4, 0, 0, 0, 0, 0, 0, 0x0c60, 0, 0 },71{ "bare-seed", 0x0040, 4, 0, 0, 0, 0x40, 0, 0, 0, 0, 0 },72};7374/* Indices of slots in the `codecs` table below */75#define ML_KEM_512_CODEC 076#define ML_KEM_768_CODEC 177#define ML_KEM_1024_CODEC 27879/*80* Per-variant fixed parameters81*/82static const ML_COMMON_CODEC codecs[3] = {83{ &ml_kem_512_spkifmt, ml_kem_512_p8fmt },84{ &ml_kem_768_spkifmt, ml_kem_768_p8fmt },85{ &ml_kem_1024_spkifmt, ml_kem_1024_p8fmt }86};8788/* Retrieve the parameters of one of the ML-KEM variants */89static const ML_COMMON_CODEC *ml_kem_get_codec(int evp_type)90{91switch (evp_type) {92case EVP_PKEY_ML_KEM_512:93return &codecs[ML_KEM_512_CODEC];94case EVP_PKEY_ML_KEM_768:95return &codecs[ML_KEM_768_CODEC];96case EVP_PKEY_ML_KEM_1024:97return &codecs[ML_KEM_1024_CODEC];98}99return NULL;100}101102ML_KEM_KEY *103ossl_ml_kem_d2i_PUBKEY(const uint8_t *pubenc, int publen, int evp_type,104PROV_CTX *provctx, const char *propq)105{106OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(provctx);107const ML_KEM_VINFO *v;108const ML_COMMON_CODEC *codec;109const ML_COMMON_SPKI_FMT *vspki;110ML_KEM_KEY *ret;111112if ((v = ossl_ml_kem_get_vinfo(evp_type)) == NULL113|| (codec = ml_kem_get_codec(evp_type)) == NULL)114return NULL;115vspki = codec->spkifmt;116if (publen != ML_COMMON_SPKI_OVERHEAD + (ossl_ssize_t) v->pubkey_bytes117|| memcmp(pubenc, vspki->asn1_prefix, ML_COMMON_SPKI_OVERHEAD) != 0)118return NULL;119publen -= ML_COMMON_SPKI_OVERHEAD;120pubenc += ML_COMMON_SPKI_OVERHEAD;121122if ((ret = ossl_ml_kem_key_new(libctx, propq, evp_type)) == NULL)123return NULL;124125if (!ossl_ml_kem_parse_public_key(pubenc, (size_t) publen, ret)) {126ERR_raise_data(ERR_LIB_PROV, PROV_R_BAD_ENCODING,127"errror parsing %s public key from input SPKI",128v->algorithm_name);129ossl_ml_kem_key_free(ret);130return NULL;131}132133return ret;134}135136ML_KEM_KEY *137ossl_ml_kem_d2i_PKCS8(const uint8_t *prvenc, int prvlen,138int evp_type, PROV_CTX *provctx,139const char *propq)140{141const ML_KEM_VINFO *v;142const ML_COMMON_CODEC *codec;143ML_COMMON_PKCS8_FMT_PREF *fmt_slots = NULL, *slot;144const ML_COMMON_PKCS8_FMT *p8fmt;145ML_KEM_KEY *key = NULL, *ret = NULL;146PKCS8_PRIV_KEY_INFO *p8inf = NULL;147const uint8_t *buf, *pos;148const X509_ALGOR *alg = NULL;149const char *formats;150int len, ptype;151uint32_t magic;152uint16_t seed_magic;153154/* Which ML-KEM variant? */155if ((v = ossl_ml_kem_get_vinfo(evp_type)) == NULL156|| (codec = ml_kem_get_codec(evp_type)) == NULL)157return 0;158159/* Extract the key OID and any parameters. */160if ((p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, &prvenc, prvlen)) == NULL)161return 0;162/* Shortest prefix is 4 bytes: seq tag/len + octet string tag/len */163if (!PKCS8_pkey_get0(NULL, &buf, &len, &alg, p8inf))164goto end;165/* Bail out early if this is some other key type. */166if (OBJ_obj2nid(alg->algorithm) != evp_type)167goto end;168169/* Get the list of enabled decoders. Their order is not important here. */170formats = ossl_prov_ctx_get_param(171provctx, OSSL_PKEY_PARAM_ML_KEM_INPUT_FORMATS, NULL);172fmt_slots = ossl_ml_common_pkcs8_fmt_order(v->algorithm_name, codec->p8fmt,173"input", formats);174if (fmt_slots == NULL)175goto end;176177/* Parameters must be absent. */178X509_ALGOR_get0(NULL, &ptype, NULL, alg);179if (ptype != V_ASN1_UNDEF) {180ERR_raise_data(ERR_LIB_PROV, PROV_R_UNEXPECTED_KEY_PARAMETERS,181"unexpected parameters with a PKCS#8 %s private key",182v->algorithm_name);183goto end;184}185if ((ossl_ssize_t)len < (ossl_ssize_t)sizeof(magic))186goto end;187188/* Find the matching p8 info slot, that also has the expected length. */189pos = OPENSSL_load_u32_be(&magic, buf);190for (slot = fmt_slots; (p8fmt = slot->fmt) != NULL; ++slot) {191if (len != (ossl_ssize_t)p8fmt->p8_bytes)192continue;193if (p8fmt->p8_shift == sizeof(magic)194|| (magic >> (p8fmt->p8_shift * 8)) == p8fmt->p8_magic) {195pos -= p8fmt->p8_shift;196break;197}198}199if (p8fmt == NULL200|| (p8fmt->seed_length > 0 && p8fmt->seed_length != ML_KEM_SEED_BYTES)201|| (p8fmt->priv_length > 0 && p8fmt->priv_length != v->prvkey_bytes)202|| (p8fmt->pub_length > 0 && p8fmt->pub_length != v->pubkey_bytes)) {203ERR_raise_data(ERR_LIB_PROV, PROV_R_ML_KEM_NO_FORMAT,204"no matching enabled %s private key input formats",205v->algorithm_name);206goto end;207}208209if (p8fmt->seed_length > 0) {210/* Check |seed| tag/len, if not subsumed by |magic|. */211if (pos + sizeof(uint16_t) == buf + p8fmt->seed_offset) {212pos = OPENSSL_load_u16_be(&seed_magic, pos);213if (seed_magic != p8fmt->seed_magic)214goto end;215} else if (pos != buf + p8fmt->seed_offset) {216goto end;217}218pos += ML_KEM_SEED_BYTES;219}220if (p8fmt->priv_length > 0) {221/* Check |priv| tag/len */222if (pos + sizeof(uint32_t) == buf + p8fmt->priv_offset) {223pos = OPENSSL_load_u32_be(&magic, pos);224if (magic != p8fmt->priv_magic)225goto end;226} else if (pos != buf + p8fmt->priv_offset) {227goto end;228}229pos += v->prvkey_bytes;230}231if (p8fmt->pub_length > 0) {232if (pos != buf + p8fmt->pub_offset)233goto end;234pos += v->pubkey_bytes;235}236if (pos != buf + len)237goto end;238239/*240* Collect the seed and/or key into a "decoded" private key object,241* to be turned into a real key on provider "load" or "import".242*/243if ((key = ossl_prov_ml_kem_new(provctx, propq, evp_type)) == NULL)244goto end;245246if (p8fmt->seed_length > 0) {247if (!ossl_ml_kem_set_seed(buf + p8fmt->seed_offset,248ML_KEM_SEED_BYTES, key)) {249ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR,250"error storing %s private key seed",251v->algorithm_name);252goto end;253}254}255if (p8fmt->priv_length > 0) {256if ((key->encoded_dk = OPENSSL_malloc(p8fmt->priv_length)) == NULL) {257ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,258"error parsing %s private key",259v->algorithm_name);260goto end;261}262memcpy(key->encoded_dk, buf + p8fmt->priv_offset, p8fmt->priv_length);263}264/* Any OQS public key content is ignored */265ret = key;266267end:268OPENSSL_free(fmt_slots);269PKCS8_PRIV_KEY_INFO_free(p8inf);270if (ret == NULL)271ossl_ml_kem_key_free(key);272return ret;273}274275/* Same as ossl_ml_kem_encode_pubkey, but allocates the output buffer. */276int ossl_ml_kem_i2d_pubkey(const ML_KEM_KEY *key, unsigned char **out)277{278size_t publen;279280if (!ossl_ml_kem_have_pubkey(key)) {281ERR_raise_data(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY,282"no %s public key data available",283key->vinfo->algorithm_name);284return 0;285}286publen = key->vinfo->pubkey_bytes;287288if (out != NULL289&& (*out = OPENSSL_malloc(publen)) == NULL)290return 0;291if (!ossl_ml_kem_encode_public_key(*out, publen, key)) {292ERR_raise_data(ERR_LIB_OSSL_ENCODER, ERR_R_INTERNAL_ERROR,293"error encoding %s public key",294key->vinfo->algorithm_name);295OPENSSL_free(*out);296return 0;297}298299return (int)publen;300}301302/* Allocate and encode PKCS#8 private key payload. */303int ossl_ml_kem_i2d_prvkey(const ML_KEM_KEY *key, uint8_t **out,304PROV_CTX *provctx)305{306const ML_KEM_VINFO *v = key->vinfo;307const ML_COMMON_CODEC *codec;308ML_COMMON_PKCS8_FMT_PREF *fmt_slots, *slot;309const ML_COMMON_PKCS8_FMT *p8fmt;310uint8_t *buf = NULL, *pos;311const char *formats;312int len = ML_KEM_SEED_BYTES;313int ret = 0;314315/* Not ours to handle */316if ((codec = ml_kem_get_codec(v->evp_type)) == NULL)317return 0;318319if (!ossl_ml_kem_have_prvkey(key)) {320ERR_raise_data(ERR_LIB_PROV, PROV_R_NOT_A_PRIVATE_KEY,321"no %s private key data available",322key->vinfo->algorithm_name);323return 0;324}325326formats = ossl_prov_ctx_get_param(327provctx, OSSL_PKEY_PARAM_ML_KEM_OUTPUT_FORMATS, NULL);328fmt_slots = ossl_ml_common_pkcs8_fmt_order(v->algorithm_name, codec->p8fmt,329"output", formats);330if (fmt_slots == NULL)331return 0;332333/* If we don't have a seed, skip seedful entries */334for (slot = fmt_slots; (p8fmt = slot->fmt) != NULL; ++slot)335if (ossl_ml_kem_have_seed(key) || p8fmt->seed_length == 0)336break;337/* No matching table entries, give up */338if (p8fmt == NULL339|| (p8fmt->seed_length > 0 && p8fmt->seed_length != ML_KEM_SEED_BYTES)340|| (p8fmt->priv_length > 0 && p8fmt->priv_length != v->prvkey_bytes)341|| (p8fmt->pub_length > 0 && p8fmt->pub_length != v->pubkey_bytes)) {342ERR_raise_data(ERR_LIB_PROV, PROV_R_ML_KEM_NO_FORMAT,343"no matching enabled %s private key output formats",344v->algorithm_name);345goto end;346}347len = p8fmt->p8_bytes;348349if (out == NULL) {350ret = len;351goto end;352}353354if ((pos = buf = OPENSSL_malloc((size_t) len)) == NULL)355goto end;356357switch (p8fmt->p8_shift) {358case 0:359pos = OPENSSL_store_u32_be(pos, p8fmt->p8_magic);360break;361case 2:362pos = OPENSSL_store_u16_be(pos, (uint16_t)p8fmt->p8_magic);363break;364case 4:365break;366default:367ERR_raise_data(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR,368"error encoding %s private key",369v->algorithm_name);370goto end;371}372373if (p8fmt->seed_length != 0) {374/*375* Either the tag/len were already included in |magic| or they require376* us to write two bytes now.377*/378if (pos + sizeof(uint16_t) == buf + p8fmt->seed_offset)379pos = OPENSSL_store_u16_be(pos, p8fmt->seed_magic);380if (pos != buf + p8fmt->seed_offset381|| !ossl_ml_kem_encode_seed(pos, ML_KEM_SEED_BYTES, key)) {382ERR_raise_data(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR,383"error encoding %s private key",384v->algorithm_name);385goto end;386}387pos += ML_KEM_SEED_BYTES;388}389if (p8fmt->priv_length != 0) {390if (pos + sizeof(uint32_t) == buf + p8fmt->priv_offset)391pos = OPENSSL_store_u32_be(pos, p8fmt->priv_magic);392if (pos != buf + p8fmt->priv_offset393|| !ossl_ml_kem_encode_private_key(pos, v->prvkey_bytes, key)) {394ERR_raise_data(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR,395"error encoding %s private key",396v->algorithm_name);397goto end;398}399pos += v->prvkey_bytes;400}401/* OQS form output with tacked-on public key */402if (p8fmt->pub_length != 0) {403/* The OQS pubkey is never separately DER-wrapped */404if (pos != buf + p8fmt->pub_offset405|| !ossl_ml_kem_encode_public_key(pos, v->pubkey_bytes, key)) {406ERR_raise_data(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR,407"error encoding %s private key",408v->algorithm_name);409goto end;410}411pos += v->pubkey_bytes;412}413414if (pos == buf + len) {415*out = buf;416ret = len;417}418419end:420OPENSSL_free(fmt_slots);421if (ret == 0)422OPENSSL_free(buf);423return ret;424}425426int ossl_ml_kem_key_to_text(BIO *out, const ML_KEM_KEY *key, int selection)427{428uint8_t seed[ML_KEM_SEED_BYTES], *prvenc = NULL, *pubenc = NULL;429size_t publen, prvlen;430const char *type_label = NULL;431int ret = 0;432433if (out == NULL || key == NULL) {434ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);435return 0;436}437type_label = key->vinfo->algorithm_name;438publen = key->vinfo->pubkey_bytes;439prvlen = key->vinfo->prvkey_bytes;440441if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0442&& (ossl_ml_kem_have_prvkey(key)443|| ossl_ml_kem_have_seed(key))) {444if (BIO_printf(out, "%s Private-Key:\n", type_label) <= 0)445return 0;446447if (ossl_ml_kem_have_seed(key)) {448if (!ossl_ml_kem_encode_seed(seed, sizeof(seed), key))449goto end;450if (!ossl_bio_print_labeled_buf(out, "seed:", seed, sizeof(seed)))451goto end;452}453if (ossl_ml_kem_have_prvkey(key)) {454if ((prvenc = OPENSSL_malloc(prvlen)) == NULL)455return 0;456if (!ossl_ml_kem_encode_private_key(prvenc, prvlen, key))457goto end;458if (!ossl_bio_print_labeled_buf(out, "dk:", prvenc, prvlen))459goto end;460}461ret = 1;462}463464/* The public key is output regardless of the selection */465if (ossl_ml_kem_have_pubkey(key)) {466/* If we did not output private key bits, this is a public key */467if (ret == 0 && BIO_printf(out, "%s Public-Key:\n", type_label) <= 0)468goto end;469470if ((pubenc = OPENSSL_malloc(key->vinfo->pubkey_bytes)) == NULL471|| !ossl_ml_kem_encode_public_key(pubenc, publen, key)472|| !ossl_bio_print_labeled_buf(out, "ek:", pubenc, publen))473goto end;474ret = 1;475}476477/* If we got here, and ret == 0, there was no key material */478if (ret == 0)479ERR_raise_data(ERR_LIB_PROV, PROV_R_MISSING_KEY,480"no %s key material available",481type_label);482483end:484OPENSSL_free(pubenc);485OPENSSL_free(prvenc);486return ret;487}488489490