Path: blob/main/crypto/openssl/providers/implementations/encode_decode/ml_common_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/crypto.h>11#include <openssl/err.h>12#include <openssl/proverr.h>13#include "ml_common_codecs.h"1415static int pref_cmp(const void *va, const void *vb)16{17const ML_COMMON_PKCS8_FMT_PREF *a = va;18const ML_COMMON_PKCS8_FMT_PREF *b = vb;1920/*21* Zeros sort last, otherwise the sort is in increasing order.22*23* The preferences are small enough to ensure the comparison is transitive24* as required by qsort(3). When overflow or underflow is possible, the25* correct transitive comparison would be: (b < a) - (a < b).26*/27if (a->pref > 0 && b->pref > 0)28return a->pref - b->pref;29/* A preference of 0 is "larger" than (sorts after) any nonzero value. */30return b->pref - a->pref;31}3233ML_COMMON_PKCS8_FMT_PREF *34ossl_ml_common_pkcs8_fmt_order(const char *algorithm_name,35const ML_COMMON_PKCS8_FMT *p8fmt,36const char *direction, const char *formats)37{38ML_COMMON_PKCS8_FMT_PREF *ret;39int i, count = 0;40const char *fmt = formats, *end;41const char *sep = "\t ,";4243/* Reserve an extra terminal slot with fmt == NULL */44if ((ret = OPENSSL_zalloc((NUM_PKCS8_FORMATS + 1) * sizeof(*ret))) == NULL)45return NULL;4647/* Entries that match a format will get a non-zero preference. */48for (i = 0; i < NUM_PKCS8_FORMATS; ++i) {49ret[i].fmt = &p8fmt[i];50ret[i].pref = 0;51}5253/* Default to compile-time table order when none specified. */54if (formats == NULL)55return ret;5657/*58* Formats are case-insensitive, separated by spaces, tabs or commas.59* Duplicate formats are allowed, the first occurence determines the order.60*/61do {62if (*(fmt += strspn(fmt, sep)) == '\0')63break;64end = fmt + strcspn(fmt, sep);65for (i = 0; i < NUM_PKCS8_FORMATS; ++i) {66/* Skip slots already selected or with a different name. */67if (ret[i].pref > 068|| OPENSSL_strncasecmp(ret[i].fmt->p8_name,69fmt, (end - fmt)) != 0)70continue;71/* First time match */72ret[i].pref = ++count;73break;74}75fmt = end;76} while (count < NUM_PKCS8_FORMATS);7778/* No formats matched, raise an error */79if (count == 0) {80OPENSSL_free(ret);81ERR_raise_data(ERR_LIB_PROV, PROV_R_ML_DSA_NO_FORMAT,82"no %s private key %s formats are enabled",83algorithm_name, direction);84return NULL;85}86/* Sort by preference, with 0's last */87qsort(ret, NUM_PKCS8_FORMATS, sizeof(*ret), pref_cmp);88/* Terminate the list at first unselected entry, perhaps reserved slot. */89ret[count].fmt = NULL;90return ret;91}929394