+/*
+ * Extract the parameter into an allocated buffer.
+ * Any existing allocation in *out is cleared and freed.
+ *
+ * Returns 1 on success, 0 on failure and -1 if there are no matching params.
+ *
+ * *out and *out_len are guaranteed to be untouched if this function
+ * doesn't return success.
+ */
+int ossl_param_get1_octet_string(const OSSL_PARAM *params, const char *name,
+ unsigned char **out, size_t *out_len)
+{
+ const OSSL_PARAM *p = OSSL_PARAM_locate_const(params, name);
+ void *buf = NULL;
+ size_t len = 0;
+
+ if (p == NULL)
+ return -1;
+
+ if (p->data != NULL
+ && p->data_size > 0
+ && !OSSL_PARAM_get_octet_string(p, &buf, 0, &len))
+ return 0;
+
+ OPENSSL_clear_free(*out, *out_len);
+ *out = buf;
+ *out_len = len;
+ return 1;
+}
+
+static int setbuf_fromparams(const OSSL_PARAM *p, const char *name,
+ unsigned char *out, size_t *outlen)
+{
+ int ret = 0;
+ WPACKET pkt;
+
+ if (out == NULL) {
+ if (!WPACKET_init_null(&pkt, 0))
+ return 0;
+ } else {
+ if (!WPACKET_init_static_len(&pkt, out, *outlen, 0))
+ return 0;
+ }
+
+ for (; p != NULL; p = OSSL_PARAM_locate_const(p + 1, name)) {
+ if (p->data_type != OSSL_PARAM_OCTET_STRING)
+ goto err;
+ if (p->data != NULL
+ && p->data_size != 0
+ && !WPACKET_memcpy(&pkt, p->data, p->data_size))
+ goto err;
+ }
+ if (!WPACKET_get_total_written(&pkt, outlen)
+ || !WPACKET_finish(&pkt))
+ goto err;
+ ret = 1;
+err:
+ WPACKET_cleanup(&pkt);
+ return ret;
+}
+
+int ossl_param_get1_concat_octet_string(const OSSL_PARAM *params, const char *name,
+ unsigned char **out,
+ size_t *out_len, size_t maxsize)
+{
+ const OSSL_PARAM *p = OSSL_PARAM_locate_const(params, name);
+ unsigned char *res;
+ size_t sz = 0;
+
+ if (p == NULL)
+ return -1;
+
+ /* Calculate the total size */
+ if (!setbuf_fromparams(p, name, NULL, &sz))
+ return 0;
+
+ /* Check that it's not oversized */
+ if (maxsize > 0 && sz > maxsize)
+ return 0;
+
+ /* Special case zero length */
+ if (sz == 0) {
+ if ((res = OPENSSL_zalloc(1)) == NULL)
+ return 0;
+ goto fin;
+ }
+
+ /* Allocate the buffer */
+ res = OPENSSL_malloc(sz);
+ if (res == NULL)
+ return 0;
+
+ /* Concat one or more OSSL_KDF_PARAM_INFO fields */
+ if (!setbuf_fromparams(p, name, res, &sz)) {
+ OPENSSL_clear_free(res, sz);
+ return 0;
+ }
+
+ fin:
+ OPENSSL_clear_free(*out, *out_len);
+ *out = res;
+ *out_len = sz;
+ return 1;
+}
+