purify
C++ Purify implementation with native circuit and BPP support
Loading...
Searching...
No Matches
core.c
Go to the documentation of this file.
1// Copyright (c) 2026 Judica, Inc.
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or https://opensource.org/license/mit/.
4
5#include "core.h"
6
7#include <stddef.h>
8#include <stdlib.h>
9#include <string.h>
10
11#include "purify/secp_bridge.h"
12
13#if defined(_WIN32)
14#ifndef NOMINMAX
15#define NOMINMAX
16#endif
17#ifndef WIN32_LEAN_AND_MEAN
18#define WIN32_LEAN_AND_MEAN
19#endif
20#include <windows.h>
21#include <bcrypt.h>
22#elif defined(__linux__)
23#include <errno.h>
24#include <sys/random.h>
25#include <unistd.h>
26#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
27#include <unistd.h>
28#else
29#include <errno.h>
30#include <stdio.h>
31#include <unistd.h>
32#endif
33
34/*
35 * Big-endian encoding of half_n1 * half_n2.
36 *
37 * Packed secrets use the mixed-radix encoding:
38 * z = (z1 - 1) + half_n1 * (z2 - 1)
39 * with 1 <= z1 <= half_n1 and 1 <= z2 <= half_n2.
40 * Therefore the valid packed range is [0, half_n1 * half_n2).
41 */
43 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
44 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
45 0x5d, 0x57, 0x6e, 0x73, 0x57, 0xa4, 0x50, 0x1d,
46 0xdf, 0xe9, 0x2f, 0x46, 0x68, 0x1b, 0x20, 0xa0,
47 0xb2, 0x92, 0x66, 0xf8, 0xfd, 0xd3, 0x36, 0x23,
48 0x17, 0x0b, 0xa9, 0x62, 0x08, 0xc6, 0x3e, 0x47,
49 0x58, 0xfb, 0xa2, 0xd2, 0xca, 0xf0, 0xc1, 0x8d,
50 0xc4, 0x8a, 0xf1, 0x1c, 0xeb, 0xe3, 0xf4, 0x64,
51};
52
53/*
54 * Big-endian encoding of p^2.
55 *
56 * Packed public keys use:
57 * packed = x1 + p * x2
58 * with 0 <= x1, x2 < p.
59 * Therefore the valid packed range is [0, p^2).
60 */
62 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
63 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd,
64 0x75, 0x5d, 0xb9, 0xcd, 0x5e, 0x91, 0x40, 0x77,
65 0x7f, 0xa4, 0xbd, 0x19, 0xa0, 0x6c, 0x82, 0x83,
66 0x9d, 0x67, 0x1c, 0xd5, 0x81, 0xc6, 0x9b, 0xc5,
67 0xe6, 0x97, 0xf5, 0xe4, 0x5b, 0xcd, 0x07, 0xc5,
68 0x2e, 0xc3, 0x73, 0xa8, 0xbd, 0xc5, 0x98, 0xb4,
69 0x49, 0x3f, 0x50, 0xa1, 0x38, 0x0e, 0x12, 0x81,
70};
71
72static const char* const kErrorNames[] = {
73 "ok",
74 "invalid_hex",
75 "invalid_hex_length",
76 "invalid_fixed_size",
77 "overflow",
78 "underflow",
79 "narrowing_overflow",
80 "division_by_zero",
81 "bit_index_out_of_range",
82 "range_violation",
83 "empty_input",
84 "size_mismatch",
85 "missing_value",
86 "invalid_symbol",
87 "unsupported_symbol",
88 "uninitialized_state",
89 "index_out_of_range",
90 "invalid_dimensions",
91 "non_boolean_value",
92 "equation_mismatch",
93 "binding_mismatch",
94 "io_open_failed",
95 "io_write_failed",
96 "entropy_unavailable",
97 "backend_rejected_input",
98 "hash_to_curve_exhausted",
99 "unexpected_size",
100 "generator_order_check_failed",
101 "internal_mismatch",
102 "transcript_check_failed",
103};
104
105static const char* const kErrorMessages[] = {
106 "success",
107 "hex input contains a non-hexadecimal character",
108 "hex input has an invalid length",
109 "input does not have the required fixed size",
110 "operation overflowed the target representation",
111 "operation underflowed the target representation",
112 "narrowing conversion would discard non-zero bits",
113 "division by zero is not permitted",
114 "bit index is outside the valid range",
115 "input is outside the documented valid range",
116 "input must not be empty",
117 "related inputs do not have matching sizes",
118 "required value is missing",
119 "symbol encoding is malformed",
120 "symbol is well-formed but not supported",
121 "object must be initialized before this operation",
122 "index is outside the valid range",
123 "inputs imply an invalid shape or dimension",
124 "value violates a required boolean constraint",
125 "value violates a required equality constraint",
126 "prepared state is bound to a different secret, message, or topic",
127 "unable to open the requested file or stream",
128 "unable to write the requested file or stream",
129 "unable to obtain secure operating-system randomness",
130 "the cryptographic backend rejected the supplied input",
131 "hash-to-curve sampling exhausted all retry attempts",
132 "backend returned an unexpected serialized size",
133 "fixed generator failed its subgroup order check",
134 "internal consistency check failed",
135 "internally generated transcript failed validation",
136};
137
138static void purify_core_secure_clear(void* data, size_t size) {
139 volatile unsigned char* out = (volatile unsigned char*)data;
140 while (size != 0) {
141 *out = 0;
142 ++out;
143 --size;
144 }
145}
146
147static int purify_core_compare_be(const unsigned char* lhs, const unsigned char* rhs, size_t size) {
148 unsigned int less = 0;
149 unsigned int greater = 0;
150 size_t i = 0;
151 for (i = 0; i < size; ++i) {
152 unsigned int undecided = (less | greater) ^ 1u;
153 less |= undecided & (unsigned int)(lhs[i] < rhs[i]);
154 greater |= undecided & (unsigned int)(lhs[i] > rhs[i]);
155 }
156 return (int)greater - (int)less;
157}
158
159#if defined(PURIFY_VALGRIND_TESTING)
160int purify_core_compare_be_test(const unsigned char* lhs,
161 const unsigned char* rhs, size_t size) {
162 return purify_core_compare_be(lhs, rhs, size);
163}
164#endif
165
166static purify_error_code purify_core_validate_below(const unsigned char* value,
167 size_t size,
168 const unsigned char* upper_bound) {
169 if (value == NULL) {
171 }
172 if (purify_core_compare_be(value, upper_bound, size) >= 0) {
174 }
175 return PURIFY_ERROR_OK;
176}
177
179 size_t out_len,
180 const unsigned char* ikm,
181 size_t ikm_len,
182 const unsigned char* salt,
183 size_t salt_len,
184 const unsigned char* info,
185 size_t info_len) {
186 static const unsigned char kZeroSalt[32] = {0};
187 unsigned char prk[32];
188 unsigned char t[32];
189 size_t offset = 0;
190 size_t block_index = 0;
191
192 if (out_len != 0 && out == NULL) {
194 }
195 if (ikm_len != 0 && ikm == NULL) {
197 }
198 if (salt_len != 0 && salt == NULL) {
200 }
201 if (info_len != 0 && info == NULL) {
203 }
204
205 memset(prk, 0, sizeof(prk));
206 memset(t, 0, sizeof(t));
208 salt_len == 0 ? kZeroSalt : salt,
209 salt_len == 0 ? sizeof(kZeroSalt) : salt_len,
210 ikm,
211 ikm_len);
212
213 while (offset < out_len) {
214 const size_t prev_len = block_index == 0 ? 0 : sizeof(t);
215 const size_t input_len = prev_len + info_len + 1;
216 unsigned char* input = (unsigned char*)malloc(input_len == 0 ? 1 : input_len);
217 size_t copy_len;
218 if (input == NULL) {
219 purify_core_secure_clear(prk, sizeof(prk));
220 purify_core_secure_clear(t, sizeof(t));
222 }
223 if (prev_len != 0) {
224 memcpy(input, t, prev_len);
225 }
226 if (info_len != 0) {
227 memcpy(input + prev_len, info, info_len);
228 }
229 input[input_len - 1] = (unsigned char)(block_index + 1);
230 purify_hmac_sha256(t, prk, sizeof(prk), input, input_len);
231 purify_core_secure_clear(input, input_len);
232 free(input);
233
234 copy_len = sizeof(t);
235 if (copy_len > out_len - offset) {
236 copy_len = out_len - offset;
237 }
238 memcpy(out + offset, t, copy_len);
239 offset += copy_len;
240 ++block_index;
241 }
242
243 purify_core_secure_clear(prk, sizeof(prk));
244 purify_core_secure_clear(t, sizeof(t));
245 return PURIFY_ERROR_OK;
246}
247
249 const size_t count = sizeof(kErrorNames) / sizeof(kErrorNames[0]);
250 const unsigned int index = (unsigned int)code;
251 if (index >= count) {
252 return "unknown";
253 }
254 return kErrorNames[index];
255}
256
258 const size_t count = sizeof(kErrorMessages) / sizeof(kErrorMessages[0]);
259 const unsigned int index = (unsigned int)code;
260 if (index >= count) {
261 return "unknown status code";
262 }
263 return kErrorMessages[index];
264}
265
266purify_error_code purify_fill_secure_random(unsigned char* bytes, size_t bytes_len) {
267 if (bytes_len != 0 && bytes == NULL) {
269 }
270#if defined(_WIN32)
271 while (bytes_len != 0) {
272 ULONG chunk = (ULONG)(bytes_len > 0xFFFFFFFFu ? 0xFFFFFFFFu : bytes_len);
273 NTSTATUS status = BCryptGenRandom(NULL, bytes, chunk, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
274 if (status < 0) {
276 }
277 bytes += chunk;
278 bytes_len -= chunk;
279 }
280 return PURIFY_ERROR_OK;
281#elif defined(__linux__)
282 while (bytes_len != 0) {
283 ssize_t written = getrandom(bytes, bytes_len, 0);
284 if (written > 0) {
285 bytes += (size_t)written;
286 bytes_len -= (size_t)written;
287 continue;
288 }
289 if (written < 0 && errno == EINTR) {
290 continue;
291 }
293 }
294 return PURIFY_ERROR_OK;
295#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
296 arc4random_buf(bytes, bytes_len);
297 return PURIFY_ERROR_OK;
298#else
299 FILE* file = fopen("/dev/urandom", "rb");
300 size_t read_count;
301 if (file == NULL) {
303 }
304 read_count = fread(bytes, 1, bytes_len, file);
305 fclose(file);
306 if (read_count != bytes_len) {
308 }
309 return PURIFY_ERROR_OK;
310#endif
311}
312
316
320
322 purify_error_code status;
323 if (out_secret_key == NULL) {
325 }
326 memset(out_secret_key, 0, PURIFY_SECRET_KEY_BYTES);
327 while (1) {
328 status = purify_fill_secure_random(out_secret_key, PURIFY_SECRET_KEY_BYTES);
329 if (status != PURIFY_ERROR_OK) {
331 return status;
332 }
333 out_secret_key[0] &= 0x3f;
335 return PURIFY_ERROR_OK;
336 }
337 }
338}
339
341 const unsigned char* seed,
342 size_t seed_len) {
343 static const unsigned char kInfo[] = "Purify/KeyGen";
344 unsigned char salt[1];
345 unsigned int attempt;
346 purify_error_code status;
347
348 if (out_secret_key == NULL) {
350 }
351 memset(out_secret_key, 0, PURIFY_SECRET_KEY_BYTES);
352 if (seed_len != 0 && seed == NULL) {
354 }
355 if (seed_len < 16) {
357 }
358
359 /* Preserve the legacy hash_to_int<8>(seed, key_space_size(), "Purify/KeyGen") derivation. */
360 for (attempt = 0; attempt < 256; ++attempt) {
361 salt[0] = (unsigned char)attempt;
362 status = purify_core_hkdf_sha256(out_secret_key,
364 seed,
365 seed_len,
366 salt,
367 sizeof(salt),
368 kInfo,
369 sizeof(kInfo) - 1);
370 if (status != PURIFY_ERROR_OK) {
372 return status;
373 }
374 out_secret_key[0] &= 0x3f;
376 return PURIFY_ERROR_OK;
377 }
378 }
379
382}
static int purify_core_compare_be(const unsigned char *lhs, const unsigned char *rhs, size_t size)
Definition core.c:147
static void purify_core_secure_clear(void *data, size_t size)
Definition core.c:138
purify_error_code purify_core_sample_secret_key(unsigned char out_secret_key[PURIFY_SECRET_KEY_BYTES])
Definition core.c:321
purify_error_code purify_fill_secure_random(unsigned char *bytes, size_t bytes_len)
Fills a caller-owned buffer with secure operating-system randomness.
Definition core.c:266
const char * purify_error_message(purify_error_code code)
Returns a human-facing description for one status code.
Definition core.c:257
static purify_error_code purify_core_validate_below(const unsigned char *value, size_t size, const unsigned char *upper_bound)
Definition core.c:166
static const char *const kErrorNames[]
Definition core.c:72
static const char *const kErrorMessages[]
Definition core.c:105
const char * purify_error_name(purify_error_code code)
Returns a stable programmatic name for one status code.
Definition core.c:248
purify_error_code purify_validate_secret_key(const unsigned char secret_key[PURIFY_SECRET_KEY_BYTES])
Validates one packed Purify secret key.
Definition core.c:313
static const unsigned char kPackedSecretKeySpaceSize[PURIFY_SECRET_KEY_BYTES]
Definition core.c:42
purify_error_code purify_core_seed_secret_key(unsigned char out_secret_key[PURIFY_SECRET_KEY_BYTES], const unsigned char *seed, size_t seed_len)
Definition core.c:340
static purify_error_code purify_core_hkdf_sha256(unsigned char *out, size_t out_len, const unsigned char *ikm, size_t ikm_len, const unsigned char *salt, size_t salt_len, const unsigned char *info, size_t info_len)
Definition core.c:178
static const unsigned char kPackedPublicKeySpaceSize[PURIFY_PUBLIC_KEY_BYTES]
Definition core.c:61
purify_error_code purify_validate_public_key(const unsigned char public_key[PURIFY_PUBLIC_KEY_BYTES])
Validates one packed Purify public key.
Definition core.c:317
#define PURIFY_SECRET_KEY_BYTES
Definition purify.h:17
#define PURIFY_PUBLIC_KEY_BYTES
Definition purify.h:18
purify_error_code
Machine-readable status code returned by the Purify C core.
Definition purify.h:28
@ PURIFY_ERROR_MISSING_VALUE
Definition purify.h:41
@ PURIFY_ERROR_OK
Definition purify.h:29
@ PURIFY_ERROR_ENTROPY_UNAVAILABLE
Definition purify.h:52
@ PURIFY_ERROR_INTERNAL_MISMATCH
Definition purify.h:57
@ PURIFY_ERROR_RANGE_VIOLATION
Definition purify.h:38
Narrow C ABI exposing secp256k1 scalar and HMAC helpers to the C++ headers.
void purify_hmac_sha256(unsigned char output32[32], const unsigned char *key, size_t key_len, const unsigned char *data, size_t data_len)
Computes HMAC-SHA256 over a byte string.