repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
openssl
openssl-master/crypto/property/property_string.c
/* * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/crypto.h> #include <openssl/lhash.h> #include "crypto/lhash.h" #include "property_local.h" #include "crypto/context.h" /* * Property strings are a consolidation of all strings seen by the property * subsystem. There are two name spaces to keep property names separate from * property values (numeric values are not expected to be cached however). * They allow a rapid conversion from a string to a unique index and any * subsequent string comparison can be done via an integer compare. * * This implementation uses OpenSSL's standard hash table. There are more * space and time efficient algorithms if this becomes a bottleneck. */ typedef struct { const char *s; OSSL_PROPERTY_IDX idx; char body[1]; } PROPERTY_STRING; DEFINE_LHASH_OF_EX(PROPERTY_STRING); typedef LHASH_OF(PROPERTY_STRING) PROP_TABLE; typedef struct { CRYPTO_RWLOCK *lock; PROP_TABLE *prop_names; PROP_TABLE *prop_values; OSSL_PROPERTY_IDX prop_name_idx; OSSL_PROPERTY_IDX prop_value_idx; #ifndef OPENSSL_SMALL_FOOTPRINT STACK_OF(OPENSSL_CSTRING) *prop_namelist; STACK_OF(OPENSSL_CSTRING) *prop_valuelist; #endif } PROPERTY_STRING_DATA; static unsigned long property_hash(const PROPERTY_STRING *a) { return OPENSSL_LH_strhash(a->s); } static int property_cmp(const PROPERTY_STRING *a, const PROPERTY_STRING *b) { return strcmp(a->s, b->s); } static void property_free(PROPERTY_STRING *ps) { OPENSSL_free(ps); } static void property_table_free(PROP_TABLE **pt) { PROP_TABLE *t = *pt; if (t != NULL) { lh_PROPERTY_STRING_doall(t, &property_free); lh_PROPERTY_STRING_free(t); *pt = NULL; } } void ossl_property_string_data_free(void *vpropdata) { PROPERTY_STRING_DATA *propdata = vpropdata; if (propdata == NULL) return; CRYPTO_THREAD_lock_free(propdata->lock); property_table_free(&propdata->prop_names); property_table_free(&propdata->prop_values); #ifndef OPENSSL_SMALL_FOOTPRINT sk_OPENSSL_CSTRING_free(propdata->prop_namelist); sk_OPENSSL_CSTRING_free(propdata->prop_valuelist); propdata->prop_namelist = propdata->prop_valuelist = NULL; #endif propdata->prop_name_idx = propdata->prop_value_idx = 0; OPENSSL_free(propdata); } void *ossl_property_string_data_new(OSSL_LIB_CTX *ctx) { PROPERTY_STRING_DATA *propdata = OPENSSL_zalloc(sizeof(*propdata)); if (propdata == NULL) return NULL; propdata->lock = CRYPTO_THREAD_lock_new(); propdata->prop_names = lh_PROPERTY_STRING_new(&property_hash, &property_cmp); propdata->prop_values = lh_PROPERTY_STRING_new(&property_hash, &property_cmp); #ifndef OPENSSL_SMALL_FOOTPRINT propdata->prop_namelist = sk_OPENSSL_CSTRING_new_null(); propdata->prop_valuelist = sk_OPENSSL_CSTRING_new_null(); #endif if (propdata->lock == NULL #ifndef OPENSSL_SMALL_FOOTPRINT || propdata->prop_namelist == NULL || propdata->prop_valuelist == NULL #endif || propdata->prop_names == NULL || propdata->prop_values == NULL) { ossl_property_string_data_free(propdata); return NULL; } return propdata; } static PROPERTY_STRING *new_property_string(const char *s, OSSL_PROPERTY_IDX *pidx) { const size_t l = strlen(s); PROPERTY_STRING *ps = OPENSSL_malloc(sizeof(*ps) + l); if (ps != NULL) { memcpy(ps->body, s, l + 1); ps->s = ps->body; ps->idx = ++*pidx; if (ps->idx == 0) { OPENSSL_free(ps); return NULL; } } return ps; } static OSSL_PROPERTY_IDX ossl_property_string(OSSL_LIB_CTX *ctx, int name, int create, const char *s) { PROPERTY_STRING p, *ps, *ps_new; PROP_TABLE *t; OSSL_PROPERTY_IDX *pidx; PROPERTY_STRING_DATA *propdata = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_PROPERTY_STRING_INDEX); if (propdata == NULL) return 0; t = name ? propdata->prop_names : propdata->prop_values; p.s = s; if (!CRYPTO_THREAD_read_lock(propdata->lock)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_UNABLE_TO_GET_READ_LOCK); return 0; } ps = lh_PROPERTY_STRING_retrieve(t, &p); if (ps == NULL && create) { CRYPTO_THREAD_unlock(propdata->lock); if (!CRYPTO_THREAD_write_lock(propdata->lock)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_UNABLE_TO_GET_WRITE_LOCK); return 0; } pidx = name ? &propdata->prop_name_idx : &propdata->prop_value_idx; ps = lh_PROPERTY_STRING_retrieve(t, &p); if (ps == NULL && (ps_new = new_property_string(s, pidx)) != NULL) { #ifndef OPENSSL_SMALL_FOOTPRINT STACK_OF(OPENSSL_CSTRING) *slist; slist = name ? propdata->prop_namelist : propdata->prop_valuelist; if (sk_OPENSSL_CSTRING_push(slist, ps_new->s) <= 0) { property_free(ps_new); CRYPTO_THREAD_unlock(propdata->lock); return 0; } #endif lh_PROPERTY_STRING_insert(t, ps_new); if (lh_PROPERTY_STRING_error(t)) { /*- * Undo the previous push which means also decrementing the * index and freeing the allocated storage. */ #ifndef OPENSSL_SMALL_FOOTPRINT sk_OPENSSL_CSTRING_pop(slist); #endif property_free(ps_new); --*pidx; CRYPTO_THREAD_unlock(propdata->lock); return 0; } ps = ps_new; } } CRYPTO_THREAD_unlock(propdata->lock); return ps != NULL ? ps->idx : 0; } #ifdef OPENSSL_SMALL_FOOTPRINT struct find_str_st { const char *str; OSSL_PROPERTY_IDX idx; }; static void find_str_fn(PROPERTY_STRING *prop, void *vfindstr) { struct find_str_st *findstr = vfindstr; if (prop->idx == findstr->idx) findstr->str = prop->s; } #endif static const char *ossl_property_str(int name, OSSL_LIB_CTX *ctx, OSSL_PROPERTY_IDX idx) { const char *r; PROPERTY_STRING_DATA *propdata = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_PROPERTY_STRING_INDEX); if (propdata == NULL) return NULL; if (!CRYPTO_THREAD_read_lock(propdata->lock)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_UNABLE_TO_GET_READ_LOCK); return NULL; } #ifdef OPENSSL_SMALL_FOOTPRINT { struct find_str_st findstr; findstr.str = NULL; findstr.idx = idx; lh_PROPERTY_STRING_doall_arg(name ? propdata->prop_names : propdata->prop_values, find_str_fn, &findstr); r = findstr.str; } #else r = sk_OPENSSL_CSTRING_value(name ? propdata->prop_namelist : propdata->prop_valuelist, idx - 1); #endif CRYPTO_THREAD_unlock(propdata->lock); return r; } OSSL_PROPERTY_IDX ossl_property_name(OSSL_LIB_CTX *ctx, const char *s, int create) { return ossl_property_string(ctx, 1, create, s); } const char *ossl_property_name_str(OSSL_LIB_CTX *ctx, OSSL_PROPERTY_IDX idx) { return ossl_property_str(1, ctx, idx); } OSSL_PROPERTY_IDX ossl_property_value(OSSL_LIB_CTX *ctx, const char *s, int create) { return ossl_property_string(ctx, 0, create, s); } const char *ossl_property_value_str(OSSL_LIB_CTX *ctx, OSSL_PROPERTY_IDX idx) { return ossl_property_str(0, ctx, idx); }
8,178
29.069853
78
c
openssl
openssl-master/crypto/rand/prov_seed.c
/* * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "crypto/rand.h" #include "crypto/rand_pool.h" #include <openssl/core_dispatch.h> #include <openssl/err.h> size_t ossl_rand_get_entropy(ossl_unused const OSSL_CORE_HANDLE *handle, unsigned char **pout, int entropy, size_t min_len, size_t max_len) { size_t ret = 0; size_t entropy_available; RAND_POOL *pool; pool = ossl_rand_pool_new(entropy, 1, min_len, max_len); if (pool == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_RAND_LIB); return 0; } /* Get entropy by polling system entropy sources. */ entropy_available = ossl_pool_acquire_entropy(pool); if (entropy_available > 0) { ret = ossl_rand_pool_length(pool); *pout = ossl_rand_pool_detach(pool); } ossl_rand_pool_free(pool); return ret; } void ossl_rand_cleanup_entropy(ossl_unused const OSSL_CORE_HANDLE *handle, unsigned char *buf, size_t len) { OPENSSL_secure_clear_free(buf, len); } size_t ossl_rand_get_nonce(ossl_unused const OSSL_CORE_HANDLE *handle, unsigned char **pout, size_t min_len, size_t max_len, const void *salt, size_t salt_len) { size_t ret = 0; RAND_POOL *pool; pool = ossl_rand_pool_new(0, 0, min_len, max_len); if (pool == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_RAND_LIB); return 0; } if (!ossl_pool_add_nonce_data(pool)) goto err; if (salt != NULL && !ossl_rand_pool_add(pool, salt, salt_len, 0)) goto err; ret = ossl_rand_pool_length(pool); *pout = ossl_rand_pool_detach(pool); err: ossl_rand_pool_free(pool); return ret; } void ossl_rand_cleanup_nonce(ossl_unused const OSSL_CORE_HANDLE *handle, unsigned char *buf, size_t len) { OPENSSL_clear_free(buf, len); }
2,232
28
80
c
openssl
openssl-master/crypto/rand/rand_deprecated.c
/* * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/e_os.h" #include <openssl/macros.h> #include <openssl/rand.h> #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # include <windows.h> # if OPENSSL_API_COMPAT < 0x10100000L # define DEPRECATED_RAND_FUNCTIONS_DEFINED int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam) { RAND_poll(); return RAND_status(); } void RAND_screen(void) { RAND_poll(); } # endif #endif #ifndef DEPRECATED_RAND_FUNCTIONS_DEFINED NON_EMPTY_TRANSLATION_UNIT #endif
827
22
74
c
openssl
openssl-master/crypto/rand/rand_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/randerr.h> #include "crypto/randerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA RAND_str_reasons[] = { {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ADDITIONAL_INPUT_TOO_LONG), "additional input too long"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ALREADY_INSTANTIATED), "already instantiated"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ARGUMENT_OUT_OF_RANGE), "argument out of range"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_CANNOT_OPEN_FILE), "Cannot open file"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_DRBG_ALREADY_INITIALIZED), "drbg already initialized"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_DRBG_NOT_INITIALISED), "drbg not initialised"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ENTROPY_INPUT_TOO_LONG), "entropy input too long"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ENTROPY_OUT_OF_RANGE), "entropy out of range"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED), "error entropy pool was ignored"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_INITIALISING_DRBG), "error initialising drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_INSTANTIATING_DRBG), "error instantiating drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_ADDITIONAL_INPUT), "error retrieving additional input"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_ENTROPY), "error retrieving entropy"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_NONCE), "error retrieving nonce"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FAILED_TO_CREATE_LOCK), "failed to create lock"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FUNC_NOT_IMPLEMENTED), "Function not implemented"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FWRITE_ERROR), "Error writing file"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_GENERATE_ERROR), "generate error"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_INSUFFICIENT_DRBG_STRENGTH), "insufficient drbg strength"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_INTERNAL_ERROR), "internal error"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_IN_ERROR_STATE), "in error state"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NOT_A_REGULAR_FILE), "Not a regular file"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NOT_INSTANTIATED), "not instantiated"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED), "no drbg implementation selected"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PARENT_LOCKING_NOT_ENABLED), "parent locking not enabled"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PARENT_STRENGTH_TOO_WEAK), "parent strength too weak"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PERSONALISATION_STRING_TOO_LONG), "personalisation string too long"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED), "prediction resistance not supported"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PRNG_NOT_SEEDED), "PRNG not seeded"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RANDOM_POOL_OVERFLOW), "random pool overflow"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RANDOM_POOL_UNDERFLOW), "random pool underflow"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG), "request too large for drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RESEED_ERROR), "reseed error"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_SELFTEST_FAILURE), "selftest failure"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_TOO_LITTLE_NONCE_REQUESTED), "too little nonce requested"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_TOO_MUCH_NONCE_REQUESTED), "too much nonce requested"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_CREATE_DRBG), "unable to create drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_FETCH_DRBG), "unable to fetch drbg"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_GET_PARENT_RESEED_PROP_COUNTER), "unable to get parent reseed prop counter"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_GET_PARENT_STRENGTH), "unable to get parent strength"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNABLE_TO_LOCK_PARENT), "unable to lock parent"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNSUPPORTED_DRBG_FLAGS), "unsupported drbg flags"}, {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNSUPPORTED_DRBG_TYPE), "unsupported drbg type"}, {0, NULL} }; #endif int ossl_err_load_RAND_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(RAND_str_reasons[0].error) == NULL) ERR_load_strings_const(RAND_str_reasons); #endif return 1; }
4,811
43.555556
80
c
openssl
openssl-master/crypto/rand/rand_lib.c
/* * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/err.h> #include <openssl/opensslconf.h> #include <openssl/core_names.h> #include "internal/cryptlib.h" #include "internal/thread_once.h" #include "crypto/rand.h" #include "crypto/cryptlib.h" #include "rand_local.h" #include "crypto/context.h" #ifndef FIPS_MODULE # include <stdio.h> # include <time.h> # include <limits.h> # include <openssl/conf.h> # include <openssl/trace.h> # include <openssl/engine.h> # include "crypto/rand_pool.h" # include "prov/seeding.h" # include "internal/e_os.h" # ifndef OPENSSL_NO_ENGINE /* non-NULL if default_RAND_meth is ENGINE-provided */ static ENGINE *funct_ref; static CRYPTO_RWLOCK *rand_engine_lock; # endif # ifndef OPENSSL_NO_DEPRECATED_3_0 static CRYPTO_RWLOCK *rand_meth_lock; static const RAND_METHOD *default_RAND_meth; # endif static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT; static int rand_inited = 0; DEFINE_RUN_ONCE_STATIC(do_rand_init) { # ifndef OPENSSL_NO_ENGINE rand_engine_lock = CRYPTO_THREAD_lock_new(); if (rand_engine_lock == NULL) return 0; # endif # ifndef OPENSSL_NO_DEPRECATED_3_0 rand_meth_lock = CRYPTO_THREAD_lock_new(); if (rand_meth_lock == NULL) goto err; # endif if (!ossl_rand_pool_init()) goto err; rand_inited = 1; return 1; err: # ifndef OPENSSL_NO_DEPRECATED_3_0 CRYPTO_THREAD_lock_free(rand_meth_lock); rand_meth_lock = NULL; # endif # ifndef OPENSSL_NO_ENGINE CRYPTO_THREAD_lock_free(rand_engine_lock); rand_engine_lock = NULL; # endif return 0; } void ossl_rand_cleanup_int(void) { # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = default_RAND_meth; if (!rand_inited) return; if (meth != NULL && meth->cleanup != NULL) meth->cleanup(); RAND_set_rand_method(NULL); # endif ossl_rand_pool_cleanup(); # ifndef OPENSSL_NO_ENGINE CRYPTO_THREAD_lock_free(rand_engine_lock); rand_engine_lock = NULL; # endif # ifndef OPENSSL_NO_DEPRECATED_3_0 CRYPTO_THREAD_lock_free(rand_meth_lock); rand_meth_lock = NULL; # endif ossl_release_default_drbg_ctx(); rand_inited = 0; } /* * RAND_close_seed_files() ensures that any seed file descriptors are * closed after use. This only applies to libcrypto/default provider, * it does not apply to other providers. */ void RAND_keep_random_devices_open(int keep) { if (RUN_ONCE(&rand_init, do_rand_init)) ossl_rand_pool_keep_random_devices_open(keep); } /* * RAND_poll() reseeds the default RNG using random input * * The random input is obtained from polling various entropy * sources which depend on the operating system and are * configurable via the --with-rand-seed configure option. */ int RAND_poll(void) { static const char salt[] = "polling"; # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = RAND_get_rand_method(); int ret = meth == RAND_OpenSSL(); if (meth == NULL) return 0; if (!ret) { /* fill random pool and seed the current legacy RNG */ RAND_POOL *pool = ossl_rand_pool_new(RAND_DRBG_STRENGTH, 1, (RAND_DRBG_STRENGTH + 7) / 8, RAND_POOL_MAX_LENGTH); if (pool == NULL) return 0; if (ossl_pool_acquire_entropy(pool) == 0) goto err; if (meth->add == NULL || meth->add(ossl_rand_pool_buffer(pool), ossl_rand_pool_length(pool), (ossl_rand_pool_entropy(pool) / 8.0)) == 0) goto err; ret = 1; err: ossl_rand_pool_free(pool); return ret; } # endif RAND_seed(salt, sizeof(salt)); return 1; } # ifndef OPENSSL_NO_DEPRECATED_3_0 static int rand_set_rand_method_internal(const RAND_METHOD *meth, ossl_unused ENGINE *e) { if (!RUN_ONCE(&rand_init, do_rand_init)) return 0; if (!CRYPTO_THREAD_write_lock(rand_meth_lock)) return 0; # ifndef OPENSSL_NO_ENGINE ENGINE_finish(funct_ref); funct_ref = e; # endif default_RAND_meth = meth; CRYPTO_THREAD_unlock(rand_meth_lock); return 1; } int RAND_set_rand_method(const RAND_METHOD *meth) { return rand_set_rand_method_internal(meth, NULL); } const RAND_METHOD *RAND_get_rand_method(void) { const RAND_METHOD *tmp_meth = NULL; if (!RUN_ONCE(&rand_init, do_rand_init)) return NULL; if (!CRYPTO_THREAD_read_lock(rand_meth_lock)) return NULL; tmp_meth = default_RAND_meth; CRYPTO_THREAD_unlock(rand_meth_lock); if (tmp_meth != NULL) return tmp_meth; if (!CRYPTO_THREAD_write_lock(rand_meth_lock)) return NULL; if (default_RAND_meth == NULL) { # ifndef OPENSSL_NO_ENGINE ENGINE *e; /* If we have an engine that can do RAND, use it. */ if ((e = ENGINE_get_default_RAND()) != NULL && (tmp_meth = ENGINE_get_RAND(e)) != NULL) { funct_ref = e; default_RAND_meth = tmp_meth; } else { ENGINE_finish(e); default_RAND_meth = &ossl_rand_meth; } # else default_RAND_meth = &ossl_rand_meth; # endif } tmp_meth = default_RAND_meth; CRYPTO_THREAD_unlock(rand_meth_lock); return tmp_meth; } # if !defined(OPENSSL_NO_ENGINE) int RAND_set_rand_engine(ENGINE *engine) { const RAND_METHOD *tmp_meth = NULL; if (!RUN_ONCE(&rand_init, do_rand_init)) return 0; if (engine != NULL) { if (!ENGINE_init(engine)) return 0; tmp_meth = ENGINE_get_RAND(engine); if (tmp_meth == NULL) { ENGINE_finish(engine); return 0; } } if (!CRYPTO_THREAD_write_lock(rand_engine_lock)) { ENGINE_finish(engine); return 0; } /* This function releases any prior ENGINE so call it first */ rand_set_rand_method_internal(tmp_meth, engine); CRYPTO_THREAD_unlock(rand_engine_lock); return 1; } # endif # endif /* OPENSSL_NO_DEPRECATED_3_0 */ void RAND_seed(const void *buf, int num) { EVP_RAND_CTX *drbg; # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth->seed != NULL) { meth->seed(buf, num); return; } # endif drbg = RAND_get0_primary(NULL); if (drbg != NULL && num > 0) EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num); } void RAND_add(const void *buf, int num, double randomness) { EVP_RAND_CTX *drbg; # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth->add != NULL) { meth->add(buf, num, randomness); return; } # endif drbg = RAND_get0_primary(NULL); if (drbg != NULL && num > 0) # ifdef OPENSSL_RAND_SEED_NONE /* Without an entropy source, we have to rely on the user */ EVP_RAND_reseed(drbg, 0, buf, num, NULL, 0); # else /* With an entropy source, we downgrade this to additional input */ EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num); # endif } # if !defined(OPENSSL_NO_DEPRECATED_1_1_0) int RAND_pseudo_bytes(unsigned char *buf, int num) { const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth->pseudorand != NULL) return meth->pseudorand(buf, num); ERR_raise(ERR_LIB_RAND, RAND_R_FUNC_NOT_IMPLEMENTED); return -1; } # endif int RAND_status(void) { EVP_RAND_CTX *rand; # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth != RAND_OpenSSL()) return meth->status != NULL ? meth->status() : 0; # endif if ((rand = RAND_get0_primary(NULL)) == NULL) return 0; return EVP_RAND_get_state(rand) == EVP_RAND_STATE_READY; } # else /* !FIPS_MODULE */ # ifndef OPENSSL_NO_DEPRECATED_3_0 const RAND_METHOD *RAND_get_rand_method(void) { return NULL; } # endif #endif /* !FIPS_MODULE */ /* * This function is not part of RAND_METHOD, so if we're not using * the default method, then just call RAND_bytes(). Otherwise make * sure we're instantiated and use the private DRBG. */ int RAND_priv_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, size_t num, unsigned int strength) { EVP_RAND_CTX *rand; #if !defined(OPENSSL_NO_DEPRECATED_3_0) && !defined(FIPS_MODULE) const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth != RAND_OpenSSL()) { if (meth->bytes != NULL) return meth->bytes(buf, num); ERR_raise(ERR_LIB_RAND, RAND_R_FUNC_NOT_IMPLEMENTED); return -1; } #endif rand = RAND_get0_private(ctx); if (rand != NULL) return EVP_RAND_generate(rand, buf, num, strength, 0, NULL, 0); return 0; } int RAND_priv_bytes(unsigned char *buf, int num) { if (num < 0) return 0; return RAND_priv_bytes_ex(NULL, buf, (size_t)num, 0); } int RAND_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, size_t num, unsigned int strength) { EVP_RAND_CTX *rand; #if !defined(OPENSSL_NO_DEPRECATED_3_0) && !defined(FIPS_MODULE) const RAND_METHOD *meth = RAND_get_rand_method(); if (meth != NULL && meth != RAND_OpenSSL()) { if (meth->bytes != NULL) return meth->bytes(buf, num); ERR_raise(ERR_LIB_RAND, RAND_R_FUNC_NOT_IMPLEMENTED); return -1; } #endif rand = RAND_get0_public(ctx); if (rand != NULL) return EVP_RAND_generate(rand, buf, num, strength, 0, NULL, 0); return 0; } int RAND_bytes(unsigned char *buf, int num) { if (num < 0) return 0; return RAND_bytes_ex(NULL, buf, (size_t)num, 0); } typedef struct rand_global_st { /* * The three shared DRBG instances * * There are three shared DRBG instances: <primary>, <public>, and * <private>. The <public> and <private> DRBGs are secondary ones. * These are used for non-secret (e.g. nonces) and secret * (e.g. private keys) data respectively. */ CRYPTO_RWLOCK *lock; EVP_RAND_CTX *seed; /* * The <primary> DRBG * * Not used directly by the application, only for reseeding the two other * DRBGs. It reseeds itself by pulling either randomness from os entropy * sources or by consuming randomness which was added by RAND_add(). * * The <primary> DRBG is a global instance which is accessed concurrently by * all threads. The necessary locking is managed automatically by its child * DRBG instances during reseeding. */ EVP_RAND_CTX *primary; /* * The <public> DRBG * * Used by default for generating random bytes using RAND_bytes(). * * The <public> secondary DRBG is thread-local, i.e., there is one instance * per thread. */ CRYPTO_THREAD_LOCAL public; /* * The <private> DRBG * * Used by default for generating private keys using RAND_priv_bytes() * * The <private> secondary DRBG is thread-local, i.e., there is one * instance per thread. */ CRYPTO_THREAD_LOCAL private; /* Which RNG is being used by default and it's configuration settings */ char *rng_name; char *rng_cipher; char *rng_digest; char *rng_propq; /* Allow the randomness source to be changed */ char *seed_name; char *seed_propq; } RAND_GLOBAL; /* * Initialize the OSSL_LIB_CTX global DRBGs on first use. * Returns the allocated global data on success or NULL on failure. */ void *ossl_rand_ctx_new(OSSL_LIB_CTX *libctx) { RAND_GLOBAL *dgbl = OPENSSL_zalloc(sizeof(*dgbl)); if (dgbl == NULL) return NULL; #ifndef FIPS_MODULE /* * We need to ensure that base libcrypto thread handling has been * initialised. */ OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL); #endif dgbl->lock = CRYPTO_THREAD_lock_new(); if (dgbl->lock == NULL) goto err1; if (!CRYPTO_THREAD_init_local(&dgbl->private, NULL)) goto err1; if (!CRYPTO_THREAD_init_local(&dgbl->public, NULL)) goto err2; return dgbl; err2: CRYPTO_THREAD_cleanup_local(&dgbl->private); err1: CRYPTO_THREAD_lock_free(dgbl->lock); OPENSSL_free(dgbl); return NULL; } void ossl_rand_ctx_free(void *vdgbl) { RAND_GLOBAL *dgbl = vdgbl; if (dgbl == NULL) return; CRYPTO_THREAD_lock_free(dgbl->lock); CRYPTO_THREAD_cleanup_local(&dgbl->private); CRYPTO_THREAD_cleanup_local(&dgbl->public); EVP_RAND_CTX_free(dgbl->primary); EVP_RAND_CTX_free(dgbl->seed); OPENSSL_free(dgbl->rng_name); OPENSSL_free(dgbl->rng_cipher); OPENSSL_free(dgbl->rng_digest); OPENSSL_free(dgbl->rng_propq); OPENSSL_free(dgbl->seed_name); OPENSSL_free(dgbl->seed_propq); OPENSSL_free(dgbl); } static RAND_GLOBAL *rand_get_global(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DRBG_INDEX); } static void rand_delete_thread_state(void *arg) { OSSL_LIB_CTX *ctx = arg; RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *rand; if (dgbl == NULL) return; rand = CRYPTO_THREAD_get_local(&dgbl->public); CRYPTO_THREAD_set_local(&dgbl->public, NULL); EVP_RAND_CTX_free(rand); rand = CRYPTO_THREAD_get_local(&dgbl->private); CRYPTO_THREAD_set_local(&dgbl->private, NULL); EVP_RAND_CTX_free(rand); } #ifndef FIPS_MODULE static EVP_RAND_CTX *rand_new_seed(OSSL_LIB_CTX *libctx) { EVP_RAND *rand; RAND_GLOBAL *dgbl = rand_get_global(libctx); EVP_RAND_CTX *ctx; char *name; if (dgbl == NULL) return NULL; name = dgbl->seed_name != NULL ? dgbl->seed_name : "SEED-SRC"; rand = EVP_RAND_fetch(libctx, name, dgbl->seed_propq); if (rand == NULL) { ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_FETCH_DRBG); return NULL; } ctx = EVP_RAND_CTX_new(rand, NULL); EVP_RAND_free(rand); if (ctx == NULL) { ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_CREATE_DRBG); return NULL; } if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0, NULL)) { ERR_raise(ERR_LIB_RAND, RAND_R_ERROR_INSTANTIATING_DRBG); EVP_RAND_CTX_free(ctx); return NULL; } return ctx; } #endif static EVP_RAND_CTX *rand_new_drbg(OSSL_LIB_CTX *libctx, EVP_RAND_CTX *parent, unsigned int reseed_interval, time_t reseed_time_interval, int use_df) { EVP_RAND *rand; RAND_GLOBAL *dgbl = rand_get_global(libctx); EVP_RAND_CTX *ctx; OSSL_PARAM params[8], *p = params; const OSSL_PARAM *settables; char *name, *cipher; if (dgbl == NULL) return NULL; name = dgbl->rng_name != NULL ? dgbl->rng_name : "CTR-DRBG"; rand = EVP_RAND_fetch(libctx, name, dgbl->rng_propq); if (rand == NULL) { ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_FETCH_DRBG); return NULL; } ctx = EVP_RAND_CTX_new(rand, parent); EVP_RAND_free(rand); if (ctx == NULL) { ERR_raise(ERR_LIB_RAND, RAND_R_UNABLE_TO_CREATE_DRBG); return NULL; } settables = EVP_RAND_CTX_settable_params(ctx); if (OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_CIPHER)) { cipher = dgbl->rng_cipher != NULL ? dgbl->rng_cipher : "AES-256-CTR"; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER, cipher, 0); } if (dgbl->rng_digest != NULL && OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_DIGEST)) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_DIGEST, dgbl->rng_digest, 0); if (dgbl->rng_propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_PROPERTIES, dgbl->rng_propq, 0); if (OSSL_PARAM_locate_const(settables, OSSL_ALG_PARAM_MAC)) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_MAC, "HMAC", 0); if (OSSL_PARAM_locate_const(settables, OSSL_DRBG_PARAM_USE_DF)) *p++ = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_USE_DF, &use_df); *p++ = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_REQUESTS, &reseed_interval); *p++ = OSSL_PARAM_construct_time_t(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL, &reseed_time_interval); *p = OSSL_PARAM_construct_end(); if (!EVP_RAND_instantiate(ctx, 0, 0, NULL, 0, params)) { ERR_raise(ERR_LIB_RAND, RAND_R_ERROR_INSTANTIATING_DRBG); EVP_RAND_CTX_free(ctx); return NULL; } return ctx; } /* * Get the primary random generator. * Returns pointer to its EVP_RAND_CTX on success, NULL on failure. * */ EVP_RAND_CTX *RAND_get0_primary(OSSL_LIB_CTX *ctx) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *ret; if (dgbl == NULL) return NULL; if (!CRYPTO_THREAD_read_lock(dgbl->lock)) return NULL; ret = dgbl->primary; CRYPTO_THREAD_unlock(dgbl->lock); if (ret != NULL) return ret; if (!CRYPTO_THREAD_write_lock(dgbl->lock)) return NULL; ret = dgbl->primary; if (ret != NULL) { CRYPTO_THREAD_unlock(dgbl->lock); return ret; } #ifndef FIPS_MODULE if (dgbl->seed == NULL) { ERR_set_mark(); dgbl->seed = rand_new_seed(ctx); ERR_pop_to_mark(); } #endif ret = dgbl->primary = rand_new_drbg(ctx, dgbl->seed, PRIMARY_RESEED_INTERVAL, PRIMARY_RESEED_TIME_INTERVAL, 1); /* * The primary DRBG may be shared between multiple threads so we must * enable locking. */ if (ret != NULL && !EVP_RAND_enable_locking(ret)) { ERR_raise(ERR_LIB_EVP, EVP_R_UNABLE_TO_ENABLE_LOCKING); EVP_RAND_CTX_free(ret); ret = dgbl->primary = NULL; } CRYPTO_THREAD_unlock(dgbl->lock); return ret; } /* * Get the public random generator. * Returns pointer to its EVP_RAND_CTX on success, NULL on failure. */ EVP_RAND_CTX *RAND_get0_public(OSSL_LIB_CTX *ctx) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *rand, *primary; if (dgbl == NULL) return NULL; rand = CRYPTO_THREAD_get_local(&dgbl->public); if (rand == NULL) { primary = RAND_get0_primary(ctx); if (primary == NULL) return NULL; ctx = ossl_lib_ctx_get_concrete(ctx); /* * If the private is also NULL then this is the first time we've * used this thread. */ if (CRYPTO_THREAD_get_local(&dgbl->private) == NULL && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state)) return NULL; rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL, SECONDARY_RESEED_TIME_INTERVAL, 0); CRYPTO_THREAD_set_local(&dgbl->public, rand); } return rand; } /* * Get the private random generator. * Returns pointer to its EVP_RAND_CTX on success, NULL on failure. */ EVP_RAND_CTX *RAND_get0_private(OSSL_LIB_CTX *ctx) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *rand, *primary; if (dgbl == NULL) return NULL; rand = CRYPTO_THREAD_get_local(&dgbl->private); if (rand == NULL) { primary = RAND_get0_primary(ctx); if (primary == NULL) return NULL; ctx = ossl_lib_ctx_get_concrete(ctx); /* * If the public is also NULL then this is the first time we've * used this thread. */ if (CRYPTO_THREAD_get_local(&dgbl->public) == NULL && !ossl_init_thread_start(NULL, ctx, rand_delete_thread_state)) return NULL; rand = rand_new_drbg(ctx, primary, SECONDARY_RESEED_INTERVAL, SECONDARY_RESEED_TIME_INTERVAL, 0); CRYPTO_THREAD_set_local(&dgbl->private, rand); } return rand; } int RAND_set0_public(OSSL_LIB_CTX *ctx, EVP_RAND_CTX *rand) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *old; int r; if (dgbl == NULL) return 0; old = CRYPTO_THREAD_get_local(&dgbl->public); if ((r = CRYPTO_THREAD_set_local(&dgbl->public, rand)) > 0) EVP_RAND_CTX_free(old); return r; } int RAND_set0_private(OSSL_LIB_CTX *ctx, EVP_RAND_CTX *rand) { RAND_GLOBAL *dgbl = rand_get_global(ctx); EVP_RAND_CTX *old; int r; if (dgbl == NULL) return 0; old = CRYPTO_THREAD_get_local(&dgbl->private); if ((r = CRYPTO_THREAD_set_local(&dgbl->private, rand)) > 0) EVP_RAND_CTX_free(old); return r; } #ifndef FIPS_MODULE static int random_set_string(char **p, const char *s) { char *d = NULL; if (s != NULL) { d = OPENSSL_strdup(s); if (d == NULL) return 0; } OPENSSL_free(*p); *p = d; return 1; } /* * Load the DRBG definitions from a configuration file. */ static int random_conf_init(CONF_IMODULE *md, const CONF *cnf) { STACK_OF(CONF_VALUE) *elist; CONF_VALUE *cval; RAND_GLOBAL *dgbl = rand_get_global(NCONF_get0_libctx((CONF *)cnf)); int i, r = 1; OSSL_TRACE1(CONF, "Loading random module: section %s\n", CONF_imodule_get_value(md)); /* Value is a section containing RANDOM configuration */ elist = NCONF_get_section(cnf, CONF_imodule_get_value(md)); if (elist == NULL) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_RANDOM_SECTION_ERROR); return 0; } if (dgbl == NULL) return 0; for (i = 0; i < sk_CONF_VALUE_num(elist); i++) { cval = sk_CONF_VALUE_value(elist, i); if (OPENSSL_strcasecmp(cval->name, "random") == 0) { if (!random_set_string(&dgbl->rng_name, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "cipher") == 0) { if (!random_set_string(&dgbl->rng_cipher, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "digest") == 0) { if (!random_set_string(&dgbl->rng_digest, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "properties") == 0) { if (!random_set_string(&dgbl->rng_propq, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "seed") == 0) { if (!random_set_string(&dgbl->seed_name, cval->value)) return 0; } else if (OPENSSL_strcasecmp(cval->name, "seed_properties") == 0) { if (!random_set_string(&dgbl->seed_propq, cval->value)) return 0; } else { ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_UNKNOWN_NAME_IN_RANDOM_SECTION, "name=%s, value=%s", cval->name, cval->value); r = 0; } } return r; } static void random_conf_deinit(CONF_IMODULE *md) { OSSL_TRACE(CONF, "Cleaned up random\n"); } void ossl_random_add_conf_module(void) { OSSL_TRACE(CONF, "Adding config module 'random'\n"); CONF_module_add("random", random_conf_init, random_conf_deinit); } int RAND_set_DRBG_type(OSSL_LIB_CTX *ctx, const char *drbg, const char *propq, const char *cipher, const char *digest) { RAND_GLOBAL *dgbl = rand_get_global(ctx); if (dgbl == NULL) return 0; if (dgbl->primary != NULL) { ERR_raise(ERR_LIB_CRYPTO, RAND_R_ALREADY_INSTANTIATED); return 0; } return random_set_string(&dgbl->rng_name, drbg) && random_set_string(&dgbl->rng_propq, propq) && random_set_string(&dgbl->rng_cipher, cipher) && random_set_string(&dgbl->rng_digest, digest); } int RAND_set_seed_source_type(OSSL_LIB_CTX *ctx, const char *seed, const char *propq) { RAND_GLOBAL *dgbl = rand_get_global(ctx); if (dgbl == NULL) return 0; if (dgbl->primary != NULL) { ERR_raise(ERR_LIB_CRYPTO, RAND_R_ALREADY_INSTANTIATED); return 0; } return random_set_string(&dgbl->seed_name, seed) && random_set_string(&dgbl->seed_propq, propq); } #endif
24,803
27.122449
80
c
openssl
openssl-master/crypto/rand/rand_local.h
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_RAND_LOCAL_H # define OSSL_CRYPTO_RAND_LOCAL_H # include <openssl/aes.h> # include <openssl/evp.h> # include <openssl/sha.h> # include <openssl/hmac.h> # include <openssl/ec.h> # include <openssl/rand.h> # include "internal/tsan_assist.h" # include "crypto/rand.h" /* Default reseed intervals */ # define PRIMARY_RESEED_INTERVAL (1 << 8) # define SECONDARY_RESEED_INTERVAL (1 << 16) # define PRIMARY_RESEED_TIME_INTERVAL (60 * 60) /* 1 hour */ # define SECONDARY_RESEED_TIME_INTERVAL (7 * 60) /* 7 minutes */ # ifndef FIPS_MODULE /* The global RAND method, and the global buffer and DRBG instance. */ extern RAND_METHOD ossl_rand_meth; # endif #endif
1,063
30.294118
74
h
openssl
openssl-master/crypto/rand/rand_meth.c
/* * Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/evp.h> #include <openssl/rand.h> #include "rand_local.h" /* Implements the default OpenSSL RAND_add() method */ static int drbg_add(const void *buf, int num, double randomness) { EVP_RAND_CTX *drbg = RAND_get0_primary(NULL); if (drbg == NULL || num <= 0) return 0; return EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num); } /* Implements the default OpenSSL RAND_seed() method */ static int drbg_seed(const void *buf, int num) { return drbg_add(buf, num, num); } /* Implements the default OpenSSL RAND_status() method */ static int drbg_status(void) { EVP_RAND_CTX *drbg = RAND_get0_primary(NULL); if (drbg == NULL) return 0; return EVP_RAND_get_state(drbg) == EVP_RAND_STATE_READY ? 1 : 0; } /* Implements the default OpenSSL RAND_bytes() method */ static int drbg_bytes(unsigned char *out, int count) { EVP_RAND_CTX *drbg = RAND_get0_public(NULL); if (drbg == NULL) return 0; return EVP_RAND_generate(drbg, out, count, 0, 0, NULL, 0); } RAND_METHOD ossl_rand_meth = { drbg_seed, drbg_bytes, NULL, drbg_add, drbg_bytes, drbg_status }; RAND_METHOD *RAND_OpenSSL(void) { return &ossl_rand_meth; }
1,551
22.515152
74
c
openssl
openssl-master/crypto/rand/rand_pool.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/opensslconf.h> #include "crypto/rand.h" #include <openssl/engine.h> #include "internal/thread_once.h" #include "crypto/rand_pool.h" /* * Allocate memory and initialize a new random pool */ RAND_POOL *ossl_rand_pool_new(int entropy_requested, int secure, size_t min_len, size_t max_len) { RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool)); size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure); if (pool == NULL) return NULL; pool->min_len = min_len; pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ? RAND_POOL_MAX_LENGTH : max_len; pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len; if (pool->alloc_len > pool->max_len) pool->alloc_len = pool->max_len; if (secure) pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len); else pool->buffer = OPENSSL_zalloc(pool->alloc_len); if (pool->buffer == NULL) goto err; pool->entropy_requested = entropy_requested; pool->secure = secure; return pool; err: OPENSSL_free(pool); return NULL; } /* * Attach new random pool to the given buffer * * This function is intended to be used only for feeding random data * provided by RAND_add() and RAND_seed() into the <master> DRBG. */ RAND_POOL *ossl_rand_pool_attach(const unsigned char *buffer, size_t len, size_t entropy) { RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool)); if (pool == NULL) return NULL; /* * The const needs to be cast away, but attached buffers will not be * modified (in contrary to allocated buffers which are zeroed and * freed in the end). */ pool->buffer = (unsigned char *) buffer; pool->len = len; pool->attached = 1; pool->min_len = pool->max_len = pool->alloc_len = pool->len; pool->entropy = entropy; return pool; } /* * Free |pool|, securely erasing its buffer. */ void ossl_rand_pool_free(RAND_POOL *pool) { if (pool == NULL) return; /* * Although it would be advisable from a cryptographical viewpoint, * we are not allowed to clear attached buffers, since they are passed * to ossl_rand_pool_attach() as `const unsigned char*`. * (see corresponding comment in ossl_rand_pool_attach()). */ if (!pool->attached) { if (pool->secure) OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len); else OPENSSL_clear_free(pool->buffer, pool->alloc_len); } OPENSSL_free(pool); } /* * Return the |pool|'s buffer to the caller (readonly). */ const unsigned char *ossl_rand_pool_buffer(RAND_POOL *pool) { return pool->buffer; } /* * Return the |pool|'s entropy to the caller. */ size_t ossl_rand_pool_entropy(RAND_POOL *pool) { return pool->entropy; } /* * Return the |pool|'s buffer length to the caller. */ size_t ossl_rand_pool_length(RAND_POOL *pool) { return pool->len; } /* * Detach the |pool| buffer and return it to the caller. * It's the responsibility of the caller to free the buffer * using OPENSSL_secure_clear_free() or to re-attach it * again to the pool using ossl_rand_pool_reattach(). */ unsigned char *ossl_rand_pool_detach(RAND_POOL *pool) { unsigned char *ret = pool->buffer; pool->buffer = NULL; pool->entropy = 0; return ret; } /* * Re-attach the |pool| buffer. It is only allowed to pass * the |buffer| which was previously detached from the same pool. */ void ossl_rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer) { pool->buffer = buffer; OPENSSL_cleanse(pool->buffer, pool->len); pool->len = 0; } /* * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one * need to obtain at least |bits| bits of entropy? */ #define ENTROPY_TO_BYTES(bits, entropy_factor) \ (((bits) * (entropy_factor) + 7) / 8) /* * Checks whether the |pool|'s entropy is available to the caller. * This is the case when entropy count and buffer length are high enough. * Returns * * |entropy| if the entropy count and buffer size is large enough * 0 otherwise */ size_t ossl_rand_pool_entropy_available(RAND_POOL *pool) { if (pool->entropy < pool->entropy_requested) return 0; if (pool->len < pool->min_len) return 0; return pool->entropy; } /* * Returns the (remaining) amount of entropy needed to fill * the random pool. */ size_t ossl_rand_pool_entropy_needed(RAND_POOL *pool) { if (pool->entropy < pool->entropy_requested) return pool->entropy_requested - pool->entropy; return 0; } /* Increase the allocation size -- not usable for an attached pool */ static int rand_pool_grow(RAND_POOL *pool, size_t len) { if (len > pool->alloc_len - pool->len) { unsigned char *p; const size_t limit = pool->max_len / 2; size_t newlen = pool->alloc_len; if (pool->attached || len > pool->max_len - pool->len) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return 0; } do newlen = newlen < limit ? newlen * 2 : pool->max_len; while (len > newlen - pool->len); if (pool->secure) p = OPENSSL_secure_zalloc(newlen); else p = OPENSSL_zalloc(newlen); if (p == NULL) return 0; memcpy(p, pool->buffer, pool->len); if (pool->secure) OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len); else OPENSSL_clear_free(pool->buffer, pool->alloc_len); pool->buffer = p; pool->alloc_len = newlen; } return 1; } /* * Returns the number of bytes needed to fill the pool, assuming * the input has 1 / |entropy_factor| entropy bits per data bit. * In case of an error, 0 is returned. */ size_t ossl_rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor) { size_t bytes_needed; size_t entropy_needed = ossl_rand_pool_entropy_needed(pool); if (entropy_factor < 1) { ERR_raise(ERR_LIB_RAND, RAND_R_ARGUMENT_OUT_OF_RANGE); return 0; } bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor); if (bytes_needed > pool->max_len - pool->len) { /* not enough space left */ ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW); return 0; } if (pool->len < pool->min_len && bytes_needed < pool->min_len - pool->len) /* to meet the min_len requirement */ bytes_needed = pool->min_len - pool->len; /* * Make sure the buffer is large enough for the requested amount * of data. This guarantees that existing code patterns where * ossl_rand_pool_add_begin, ossl_rand_pool_add_end or ossl_rand_pool_add * are used to collect entropy data without any error handling * whatsoever, continue to be valid. * Furthermore if the allocation here fails once, make sure that * we don't fall back to a less secure or even blocking random source, * as that could happen by the existing code patterns. * This is not a concern for additional data, therefore that * is not needed if rand_pool_grow fails in other places. */ if (!rand_pool_grow(pool, bytes_needed)) { /* persistent error for this pool */ pool->max_len = pool->len = 0; return 0; } return bytes_needed; } /* Returns the remaining number of bytes available */ size_t ossl_rand_pool_bytes_remaining(RAND_POOL *pool) { return pool->max_len - pool->len; } /* * Add random bytes to the random pool. * * It is expected that the |buffer| contains |len| bytes of * random input which contains at least |entropy| bits of * randomness. * * Returns 1 if the added amount is adequate, otherwise 0 */ int ossl_rand_pool_add(RAND_POOL *pool, const unsigned char *buffer, size_t len, size_t entropy) { if (len > pool->max_len - pool->len) { ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG); return 0; } if (pool->buffer == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return 0; } if (len > 0) { /* * This is to protect us from accidentally passing the buffer * returned from ossl_rand_pool_add_begin. * The check for alloc_len makes sure we do not compare the * address of the end of the allocated memory to something * different, since that comparison would have an * indeterminate result. */ if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return 0; } /* * We have that only for cases when a pool is used to collect * additional data. * For entropy data, as long as the allocation request stays within * the limits given by ossl_rand_pool_bytes_needed this rand_pool_grow * below is guaranteed to succeed, thus no allocation happens. */ if (!rand_pool_grow(pool, len)) return 0; memcpy(pool->buffer + pool->len, buffer, len); pool->len += len; pool->entropy += entropy; } return 1; } /* * Start to add random bytes to the random pool in-place. * * Reserves the next |len| bytes for adding random bytes in-place * and returns a pointer to the buffer. * The caller is allowed to copy up to |len| bytes into the buffer. * If |len| == 0 this is considered a no-op and a NULL pointer * is returned without producing an error message. * * After updating the buffer, ossl_rand_pool_add_end() needs to be called * to finish the update operation (see next comment). */ unsigned char *ossl_rand_pool_add_begin(RAND_POOL *pool, size_t len) { if (len == 0) return NULL; if (len > pool->max_len - pool->len) { ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW); return NULL; } if (pool->buffer == NULL) { ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR); return NULL; } /* * As long as the allocation request stays within the limits given * by ossl_rand_pool_bytes_needed this rand_pool_grow below is guaranteed * to succeed, thus no allocation happens. * We have that only for cases when a pool is used to collect * additional data. Then the buffer might need to grow here, * and of course the caller is responsible to check the return * value of this function. */ if (!rand_pool_grow(pool, len)) return NULL; return pool->buffer + pool->len; } /* * Finish to add random bytes to the random pool in-place. * * Finishes an in-place update of the random pool started by * ossl_rand_pool_add_begin() (see previous comment). * It is expected that |len| bytes of random input have been added * to the buffer which contain at least |entropy| bits of randomness. * It is allowed to add less bytes than originally reserved. */ int ossl_rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy) { if (len > pool->alloc_len - pool->len) { ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW); return 0; } if (len > 0) { pool->len += len; pool->entropy += entropy; } return 1; }
11,777
28.081481
80
c
openssl
openssl-master/crypto/rand/randfile.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #if defined (__TANDEM) && defined (_SPT_MODEL_) /* * These definitions have to come first in SPT due to scoping of the * declarations in c99 associated with SPT use of stat. */ # include <sys/types.h> # include <sys/stat.h> #endif #include "internal/cryptlib.h" #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/buffer.h> #ifdef OPENSSL_SYS_VMS # include <unixio.h> #endif #include <sys/types.h> #ifndef OPENSSL_NO_POSIX_IO # include <sys/stat.h> # include <fcntl.h> # if defined(_WIN32) && !defined(_WIN32_WCE) # include <windows.h> # include <io.h> # define stat _stat # define chmod _chmod # define open _open # define fdopen _fdopen # define fstat _fstat # define fileno _fileno # endif #endif /* * Following should not be needed, and we could have been stricter * and demand S_IS*. But some systems just don't comply... Formally * below macros are "anatomically incorrect", because normally they * would look like ((m) & MASK == TYPE), but since MASK availability * is as questionable, we settle for this poor-man fallback... */ # if !defined(S_ISREG) # define S_ISREG(m) ((m) & S_IFREG) # endif #define RAND_BUF_SIZE 1024 #define RFILE ".rnd" #ifdef OPENSSL_SYS_VMS /* * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically) * to make sure the FILE* is a 32-bit pointer no matter what. We know that * stdio functions return this type (a study of stdio.h proves it). * * This declaration is a nasty hack to get around vms' extension to fopen for * passing in sharing options being disabled by /STANDARD=ANSI89 */ static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) = (__FILE_ptr32 (*)(const char *, const char *, ...))fopen; # define VMS_OPEN_ATTRS \ "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0" # define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS) #endif /* * Note that these functions are intended for seed files only. Entropy * devices and EGD sockets are handled in rand_unix.c If |bytes| is * -1 read the complete file; otherwise read the specified amount. */ int RAND_load_file(const char *file, long bytes) { /* * The load buffer size exceeds the chunk size by the comfortable amount * of 'RAND_DRBG_STRENGTH' bytes (not bits!). This is done on purpose * to avoid calling RAND_add() with a small final chunk. Instead, such * a small final chunk will be added together with the previous chunk * (unless it's the only one). */ #define RAND_LOAD_BUF_SIZE (RAND_BUF_SIZE + RAND_DRBG_STRENGTH) unsigned char buf[RAND_LOAD_BUF_SIZE]; #ifndef OPENSSL_NO_POSIX_IO struct stat sb; #endif int i, n, ret = 0; FILE *in; if (bytes == 0) return 0; if ((in = openssl_fopen(file, "rb")) == NULL) { ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE, "Filename=%s", file); return -1; } #ifndef OPENSSL_NO_POSIX_IO if (fstat(fileno(in), &sb) < 0) { ERR_raise_data(ERR_LIB_RAND, RAND_R_INTERNAL_ERROR, "Filename=%s", file); fclose(in); return -1; } if (bytes < 0) { if (S_ISREG(sb.st_mode)) bytes = sb.st_size; else bytes = RAND_DRBG_STRENGTH; } #endif /* * On VMS, setbuf() will only take 32-bit pointers, and a compilation * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here. * However, we trust that the C RTL will never give us a FILE pointer * above the first 4 GB of memory, so we simply turn off the warning * temporarily. */ #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma environment save # pragma message disable maylosedata2 #endif /* * Don't buffer, because even if |file| is regular file, we have * no control over the buffer, so why would we want a copy of its * contents lying around? */ setbuf(in, NULL); #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma environment restore #endif for (;;) { if (bytes > 0) n = (bytes <= RAND_LOAD_BUF_SIZE) ? (int)bytes : RAND_BUF_SIZE; else n = RAND_LOAD_BUF_SIZE; i = fread(buf, 1, n, in); #ifdef EINTR if (ferror(in) && errno == EINTR) { clearerr(in); if (i == 0) continue; } #endif if (i == 0) break; RAND_add(buf, i, (double)i); ret += i; /* If given a bytecount, and we did it, break. */ if (bytes > 0 && (bytes -= i) <= 0) break; } OPENSSL_cleanse(buf, sizeof(buf)); fclose(in); if (!RAND_status()) { ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file); return -1; } return ret; } int RAND_write_file(const char *file) { unsigned char buf[RAND_BUF_SIZE]; int ret = -1; FILE *out = NULL; #ifndef OPENSSL_NO_POSIX_IO struct stat sb; if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) { ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE, "Filename=%s", file); return -1; } #endif /* Collect enough random data. */ if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1) return -1; #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \ !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS) { # ifndef O_BINARY # define O_BINARY 0 # endif /* * chmod(..., 0600) is too late to protect the file, permissions * should be restrictive from the start */ int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600); if (fd != -1) out = fdopen(fd, "wb"); } #endif #ifdef OPENSSL_SYS_VMS /* * VMS NOTE: Prior versions of this routine created a _new_ version of * the rand file for each call into this routine, then deleted all * existing versions named ;-1, and finally renamed the current version * as ';1'. Under concurrent usage, this resulted in an RMS race * condition in rename() which could orphan files (see vms message help * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares * the top-level version of the rand file. Note that there may still be * conditions where the top-level rand file is locked. If so, this code * will then create a new version of the rand file. Without the delete * and rename code, this can result in ascending file versions that stop * at version 32767, and this routine will then return an error. The * remedy for this is to recode the calling application to avoid * concurrent use of the rand file, or synchronize usage at the * application level. Also consider whether or not you NEED a persistent * rand file in a concurrent use situation. */ out = openssl_fopen(file, "rb+"); #endif if (out == NULL) out = openssl_fopen(file, "wb"); if (out == NULL) { ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE, "Filename=%s", file); return -1; } #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO) /* * Yes it's late to do this (see above comment), but better than nothing. */ chmod(file, 0600); #endif ret = fwrite(buf, 1, RAND_BUF_SIZE, out); fclose(out); OPENSSL_cleanse(buf, RAND_BUF_SIZE); return ret; } const char *RAND_file_name(char *buf, size_t size) { char *s = NULL; size_t len; int use_randfile = 1; #if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE) DWORD envlen; WCHAR *var; /* Look up various environment variables. */ if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) { use_randfile = 0; if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0 && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE", NULL, 0)) == 0) envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0); } /* If we got a value, allocate space to hold it and then get it. */ if (envlen != 0) { int sz; WCHAR *val = _alloca(envlen * sizeof(WCHAR)); if (GetEnvironmentVariableW(var, val, envlen) < envlen && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0, NULL, NULL)) != 0) { s = _alloca(sz); if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz, NULL, NULL) == 0) s = NULL; } } #else if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') { use_randfile = 0; s = ossl_safe_getenv("HOME"); } #endif #ifdef DEFAULT_HOME if (!use_randfile && s == NULL) s = DEFAULT_HOME; #endif if (s == NULL || *s == '\0') return NULL; len = strlen(s); if (use_randfile) { if (len + 1 >= size) return NULL; strcpy(buf, s); } else { if (len + 1 + strlen(RFILE) + 1 >= size) return NULL; strcpy(buf, s); #ifndef OPENSSL_SYS_VMS strcat(buf, "/"); #endif strcat(buf, RFILE); } return buf; }
9,759
29.310559
79
c
openssl
openssl-master/crypto/rc2/rc2_cbc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_local.h" void RC2_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, RC2_KEY *ks, unsigned char *iv, int encrypt) { register unsigned long tin0, tin1; register unsigned long tout0, tout1, xor0, xor1; register long l = length; unsigned long tin[2]; if (encrypt) { c2l(iv, tout0); c2l(iv, tout1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); c2l(in, tin1); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; RC2_encrypt(tin, ks); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; l2c(tout1, out); } if (l != -8) { c2ln(in, tin0, tin1, l + 8); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; RC2_encrypt(tin, ks); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; l2c(tout1, out); } l2c(tout0, iv); l2c(tout1, iv); } else { c2l(iv, xor0); c2l(iv, xor1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; RC2_decrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2c(tout0, out); l2c(tout1, out); xor0 = tin0; xor1 = tin1; } if (l != -8) { c2l(in, tin0); tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; RC2_decrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2cn(tout0, tout1, out, l + 8); xor0 = tin0; xor1 = tin1; } l2c(xor0, iv); l2c(xor1, iv); } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; } void RC2_encrypt(unsigned long *d, RC2_KEY *key) { int i, n; register RC2_INT *p0, *p1; register RC2_INT x0, x1, x2, x3, t; unsigned long l; l = d[0]; x0 = (RC2_INT) l & 0xffff; x1 = (RC2_INT) (l >> 16L); l = d[1]; x2 = (RC2_INT) l & 0xffff; x3 = (RC2_INT) (l >> 16L); n = 3; i = 5; p0 = p1 = &(key->data[0]); for (;;) { t = (x0 + (x1 & ~x3) + (x2 & x3) + *(p0++)) & 0xffff; x0 = (t << 1) | (t >> 15); t = (x1 + (x2 & ~x0) + (x3 & x0) + *(p0++)) & 0xffff; x1 = (t << 2) | (t >> 14); t = (x2 + (x3 & ~x1) + (x0 & x1) + *(p0++)) & 0xffff; x2 = (t << 3) | (t >> 13); t = (x3 + (x0 & ~x2) + (x1 & x2) + *(p0++)) & 0xffff; x3 = (t << 5) | (t >> 11); if (--i == 0) { if (--n == 0) break; i = (n == 2) ? 6 : 5; x0 += p1[x3 & 0x3f]; x1 += p1[x0 & 0x3f]; x2 += p1[x1 & 0x3f]; x3 += p1[x2 & 0x3f]; } } d[0] = (unsigned long)(x0 & 0xffff) | ((unsigned long)(x1 & 0xffff) << 16L); d[1] = (unsigned long)(x2 & 0xffff) | ((unsigned long)(x3 & 0xffff) << 16L); } void RC2_decrypt(unsigned long *d, RC2_KEY *key) { int i, n; register RC2_INT *p0, *p1; register RC2_INT x0, x1, x2, x3, t; unsigned long l; l = d[0]; x0 = (RC2_INT) l & 0xffff; x1 = (RC2_INT) (l >> 16L); l = d[1]; x2 = (RC2_INT) l & 0xffff; x3 = (RC2_INT) (l >> 16L); n = 3; i = 5; p0 = &(key->data[63]); p1 = &(key->data[0]); for (;;) { t = ((x3 << 11) | (x3 >> 5)) & 0xffff; x3 = (t - (x0 & ~x2) - (x1 & x2) - *(p0--)) & 0xffff; t = ((x2 << 13) | (x2 >> 3)) & 0xffff; x2 = (t - (x3 & ~x1) - (x0 & x1) - *(p0--)) & 0xffff; t = ((x1 << 14) | (x1 >> 2)) & 0xffff; x1 = (t - (x2 & ~x0) - (x3 & x0) - *(p0--)) & 0xffff; t = ((x0 << 15) | (x0 >> 1)) & 0xffff; x0 = (t - (x1 & ~x3) - (x2 & x3) - *(p0--)) & 0xffff; if (--i == 0) { if (--n == 0) break; i = (n == 2) ? 6 : 5; x3 = (x3 - p1[x2 & 0x3f]) & 0xffff; x2 = (x2 - p1[x1 & 0x3f]) & 0xffff; x1 = (x1 - p1[x0 & 0x3f]) & 0xffff; x0 = (x0 - p1[x3 & 0x3f]) & 0xffff; } } d[0] = (unsigned long)(x0 & 0xffff) | ((unsigned long)(x1 & 0xffff) << 16L); d[1] = (unsigned long)(x2 & 0xffff) | ((unsigned long)(x3 & 0xffff) << 16L); }
5,089
26.365591
78
c
openssl
openssl-master/crypto/rc2/rc2_ecb.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_local.h" #include <openssl/opensslv.h> /*- * RC2 as implemented frm a posting from * Newsgroups: sci.crypt * Subject: Specification for Ron Rivests Cipher No.2 * Message-ID: <[email protected]> * Date: 11 Feb 1996 06:45:03 GMT */ void RC2_ecb_encrypt(const unsigned char *in, unsigned char *out, RC2_KEY *ks, int encrypt) { unsigned long l, d[2]; c2l(in, l); d[0] = l; c2l(in, l); d[1] = l; if (encrypt) RC2_encrypt(d, ks); else RC2_decrypt(d, ks); l = d[0]; l2c(l, out); l = d[1]; l2c(l, out); l = d[0] = d[1] = 0; }
1,128
23.021277
78
c
openssl
openssl-master/crypto/rc2/rc2_local.h
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #undef c2l #define c2l(c,l) (l =((unsigned long)(*((c)++))) , \ l|=((unsigned long)(*((c)++)))<< 8L, \ l|=((unsigned long)(*((c)++)))<<16L, \ l|=((unsigned long)(*((c)++)))<<24L) /* NOTE - c is not incremented as per c2l */ #undef c2ln #define c2ln(c,l1,l2,n) { \ c+=n; \ l1=l2=0; \ switch (n) { \ case 8: l2 =((unsigned long)(*(--(c))))<<24L; \ /* fall through */ \ case 7: l2|=((unsigned long)(*(--(c))))<<16L; \ /* fall through */ \ case 6: l2|=((unsigned long)(*(--(c))))<< 8L; \ /* fall through */ \ case 5: l2|=((unsigned long)(*(--(c)))); \ /* fall through */ \ case 4: l1 =((unsigned long)(*(--(c))))<<24L; \ /* fall through */ \ case 3: l1|=((unsigned long)(*(--(c))))<<16L; \ /* fall through */ \ case 2: l1|=((unsigned long)(*(--(c))))<< 8L; \ /* fall through */ \ case 1: l1|=((unsigned long)(*(--(c)))); \ } \ } #undef l2c #define l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ *((c)++)=(unsigned char)(((l)>>24L)&0xff)) /* NOTE - c is not incremented as per l2c */ #undef l2cn #define l2cn(l1,l2,c,n) { \ c+=n; \ switch (n) { \ case 8: *(--(c))=(unsigned char)(((l2)>>24L)&0xff); \ /* fall through */ \ case 7: *(--(c))=(unsigned char)(((l2)>>16L)&0xff); \ /* fall through */ \ case 6: *(--(c))=(unsigned char)(((l2)>> 8L)&0xff); \ /* fall through */ \ case 5: *(--(c))=(unsigned char)(((l2) )&0xff); \ /* fall through */ \ case 4: *(--(c))=(unsigned char)(((l1)>>24L)&0xff); \ /* fall through */ \ case 3: *(--(c))=(unsigned char)(((l1)>>16L)&0xff); \ /* fall through */ \ case 2: *(--(c))=(unsigned char)(((l1)>> 8L)&0xff); \ /* fall through */ \ case 1: *(--(c))=(unsigned char)(((l1) )&0xff); \ } \ }
3,657
52.014493
80
h
openssl
openssl-master/crypto/rc2/rc2_skey.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_local.h" static const unsigned char key_table[256] = { 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad, }; #if defined(_MSC_VER) && defined(_ARM_) # pragma optimize("g",off) #endif /* * It has come to my attention that there are 2 versions of the RC2 key * schedule. One which is normal, and another which has a hook to use a * reduced key length. BSAFE uses the latter version. What I previously * shipped is the same as specifying 1024 for the 'bits' parameter. Bsafe * uses a version where the bits parameter is the same as len*8 */ void RC2_set_key(RC2_KEY *key, int len, const unsigned char *data, int bits) { int i, j; unsigned char *k; RC2_INT *ki; unsigned int c, d; k = (unsigned char *)&(key->data[0]); *k = 0; /* for if there is a zero length key */ if (len > 128) len = 128; if (bits <= 0) bits = 1024; if (bits > 1024) bits = 1024; for (i = 0; i < len; i++) k[i] = data[i]; /* expand table */ d = k[len - 1]; j = 0; for (i = len; i < 128; i++, j++) { d = key_table[(k[j] + d) & 0xff]; k[i] = d; } /* hmm.... key reduction to 'bits' bits */ j = (bits + 7) >> 3; i = 128 - j; c = (0xff >> (-bits & 0x07)); d = key_table[k[i] & c]; k[i] = d; while (i--) { d = key_table[k[i + j] ^ d]; k[i] = d; } /* copy from bytes into RC2_INT's */ ki = &(key->data[63]); for (i = 127; i >= 0; i -= 2) *(ki--) = ((k[i] << 8) | k[i - 1]) & 0xffff; } #if defined(_MSC_VER) # pragma optimize("",on) #endif
3,694
34.190476
78
c
openssl
openssl-master/crypto/rc2/rc2cfb64.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_local.h" /* * The input and output encrypted as though 64bit cfb mode is being used. * The extra state information to record how much of the 64bit block we have * used is contained in *num; */ void RC2_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, RC2_KEY *schedule, unsigned char *ivec, int *num, int encrypt) { register unsigned long v0, v1, t; register int n = *num; register long l = length; unsigned long ti[2]; unsigned char *iv, c, cc; iv = (unsigned char *)ivec; if (encrypt) { while (l--) { if (n == 0) { c2l(iv, v0); ti[0] = v0; c2l(iv, v1); ti[1] = v1; RC2_encrypt((unsigned long *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2c(t, iv); t = ti[1]; l2c(t, iv); iv = (unsigned char *)ivec; } c = *(in++) ^ iv[n]; *(out++) = c; iv[n] = c; n = (n + 1) & 0x07; } } else { while (l--) { if (n == 0) { c2l(iv, v0); ti[0] = v0; c2l(iv, v1); ti[1] = v1; RC2_encrypt((unsigned long *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2c(t, iv); t = ti[1]; l2c(t, iv); iv = (unsigned char *)ivec; } cc = *(in++); c = iv[n]; iv[n] = cc; *(out++) = c ^ cc; n = (n + 1) & 0x07; } } v0 = v1 = ti[0] = ti[1] = t = c = cc = 0; *num = n; }
2,316
27.604938
78
c
openssl
openssl-master/crypto/rc2/rc2ofb64.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC2 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc2.h> #include "rc2_local.h" /* * The input and output encrypted as though 64bit ofb mode is being used. * The extra state information to record how much of the 64bit block we have * used is contained in *num; */ void RC2_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, RC2_KEY *schedule, unsigned char *ivec, int *num) { register unsigned long v0, v1, t; register int n = *num; register long l = length; unsigned char d[8]; register char *dp; unsigned long ti[2]; unsigned char *iv; int save = 0; iv = (unsigned char *)ivec; c2l(iv, v0); c2l(iv, v1); ti[0] = v0; ti[1] = v1; dp = (char *)d; l2c(v0, dp); l2c(v1, dp); while (l--) { if (n == 0) { RC2_encrypt((unsigned long *)ti, schedule); dp = (char *)d; t = ti[0]; l2c(t, dp); t = ti[1]; l2c(t, dp); save++; } *(out++) = *(in++) ^ d[n]; n = (n + 1) & 0x07; } if (save) { v0 = ti[0]; v1 = ti[1]; iv = (unsigned char *)ivec; l2c(v0, iv); l2c(v1, iv); } t = v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
1,752
24.779412
78
c
openssl
openssl-master/crypto/rc4/rc4_enc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC4 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc4.h> #include "rc4_local.h" /*- * RC4 as implemented from a posting from * Newsgroups: sci.crypt * Subject: RC4 Algorithm revealed. * Message-ID: <[email protected]> * Date: Wed, 14 Sep 1994 06:35:31 GMT */ void RC4(RC4_KEY *key, size_t len, const unsigned char *indata, unsigned char *outdata) { register RC4_INT *d; register RC4_INT x, y, tx, ty; size_t i; x = key->x; y = key->y; d = key->data; #define LOOP(in,out) \ x=((x+1)&0xff); \ tx=d[x]; \ y=(tx+y)&0xff; \ d[x]=ty=d[y]; \ d[y]=tx; \ (out) = d[(tx+ty)&0xff]^ (in); i = len >> 3; if (i) { for (;;) { LOOP(indata[0], outdata[0]); LOOP(indata[1], outdata[1]); LOOP(indata[2], outdata[2]); LOOP(indata[3], outdata[3]); LOOP(indata[4], outdata[4]); LOOP(indata[5], outdata[5]); LOOP(indata[6], outdata[6]); LOOP(indata[7], outdata[7]); indata += 8; outdata += 8; if (--i == 0) break; } } i = len & 0x07; if (i) { for (;;) { LOOP(indata[0], outdata[0]); if (--i == 0) break; LOOP(indata[1], outdata[1]); if (--i == 0) break; LOOP(indata[2], outdata[2]); if (--i == 0) break; LOOP(indata[3], outdata[3]); if (--i == 0) break; LOOP(indata[4], outdata[4]); if (--i == 0) break; LOOP(indata[5], outdata[5]); if (--i == 0) break; LOOP(indata[6], outdata[6]); if (--i == 0) break; } } key->x = x; key->y = y; }
2,385
24.934783
78
c
openssl
openssl-master/crypto/rc4/rc4_skey.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC4 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc4.h> #include "rc4_local.h" #include <openssl/opensslv.h> const char *RC4_options(void) { if (sizeof(RC4_INT) == 1) return "rc4(char)"; else return "rc4(int)"; } /*- * RC4 as implemented from a posting from * Newsgroups: sci.crypt * Subject: RC4 Algorithm revealed. * Message-ID: <[email protected]> * Date: Wed, 14 Sep 1994 06:35:31 GMT */ void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data) { register RC4_INT tmp; register int id1, id2; register RC4_INT *d; unsigned int i; d = &(key->data[0]); key->x = 0; key->y = 0; id1 = id2 = 0; #define SK_LOOP(d,n) { \ tmp=d[(n)]; \ id2 = (data[id1] + tmp + id2) & 0xff; \ if (++id1 == len) id1=0; \ d[(n)]=d[id2]; \ d[id2]=tmp; } for (i = 0; i < 256; i++) d[i] = i; for (i = 0; i < 256; i += 4) { SK_LOOP(d, i + 0); SK_LOOP(d, i + 1); SK_LOOP(d, i + 2); SK_LOOP(d, i + 3); } }
1,530
22.921875
78
c
openssl
openssl-master/crypto/rc5/rc5_ecb.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC5 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc5.h> #include "rc5_local.h" #include <openssl/opensslv.h> void RC5_32_ecb_encrypt(const unsigned char *in, unsigned char *out, RC5_32_KEY *ks, int encrypt) { unsigned long l, d[2]; c2l(in, l); d[0] = l; c2l(in, l); d[1] = l; if (encrypt) RC5_32_encrypt(d, ks); else RC5_32_decrypt(d, ks); l = d[0]; l2c(l, out); l = d[1]; l2c(l, out); l = d[0] = d[1] = 0; }
933
22.948718
78
c
openssl
openssl-master/crypto/rc5/rc5_enc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC5 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include <openssl/rc5.h> #include "rc5_local.h" void RC5_32_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, RC5_32_KEY *ks, unsigned char *iv, int encrypt) { register unsigned long tin0, tin1; register unsigned long tout0, tout1, xor0, xor1; register long l = length; unsigned long tin[2]; if (encrypt) { c2l(iv, tout0); c2l(iv, tout1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); c2l(in, tin1); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; RC5_32_encrypt(tin, ks); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; l2c(tout1, out); } if (l != -8) { c2ln(in, tin0, tin1, l + 8); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; RC5_32_encrypt(tin, ks); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; l2c(tout1, out); } l2c(tout0, iv); l2c(tout1, iv); } else { c2l(iv, xor0); c2l(iv, xor1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; RC5_32_decrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2c(tout0, out); l2c(tout1, out); xor0 = tin0; xor1 = tin1; } if (l != -8) { c2l(in, tin0); tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; RC5_32_decrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2cn(tout0, tout1, out, l + 8); xor0 = tin0; xor1 = tin1; } l2c(xor0, iv); l2c(xor1, iv); } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; } void RC5_32_encrypt(unsigned long *d, RC5_32_KEY *key) { RC5_32_INT a, b, *s; s = key->data; a = d[0] + s[0]; b = d[1] + s[1]; E_RC5_32(a, b, s, 2); E_RC5_32(a, b, s, 4); E_RC5_32(a, b, s, 6); E_RC5_32(a, b, s, 8); E_RC5_32(a, b, s, 10); E_RC5_32(a, b, s, 12); E_RC5_32(a, b, s, 14); E_RC5_32(a, b, s, 16); if (key->rounds == 12) { E_RC5_32(a, b, s, 18); E_RC5_32(a, b, s, 20); E_RC5_32(a, b, s, 22); E_RC5_32(a, b, s, 24); } else if (key->rounds == 16) { /* Do a full expansion to avoid a jump */ E_RC5_32(a, b, s, 18); E_RC5_32(a, b, s, 20); E_RC5_32(a, b, s, 22); E_RC5_32(a, b, s, 24); E_RC5_32(a, b, s, 26); E_RC5_32(a, b, s, 28); E_RC5_32(a, b, s, 30); E_RC5_32(a, b, s, 32); } d[0] = a; d[1] = b; } void RC5_32_decrypt(unsigned long *d, RC5_32_KEY *key) { RC5_32_INT a, b, *s; s = key->data; a = d[0]; b = d[1]; if (key->rounds == 16) { D_RC5_32(a, b, s, 32); D_RC5_32(a, b, s, 30); D_RC5_32(a, b, s, 28); D_RC5_32(a, b, s, 26); /* Do a full expansion to avoid a jump */ D_RC5_32(a, b, s, 24); D_RC5_32(a, b, s, 22); D_RC5_32(a, b, s, 20); D_RC5_32(a, b, s, 18); } else if (key->rounds == 12) { D_RC5_32(a, b, s, 24); D_RC5_32(a, b, s, 22); D_RC5_32(a, b, s, 20); D_RC5_32(a, b, s, 18); } D_RC5_32(a, b, s, 16); D_RC5_32(a, b, s, 14); D_RC5_32(a, b, s, 12); D_RC5_32(a, b, s, 10); D_RC5_32(a, b, s, 8); D_RC5_32(a, b, s, 6); D_RC5_32(a, b, s, 4); D_RC5_32(a, b, s, 2); d[0] = a - s[0]; d[1] = b - s[1]; }
4,371
25.179641
78
c
openssl
openssl-master/crypto/rc5/rc5_skey.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC5 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc5.h> #include "rc5_local.h" int RC5_32_set_key(RC5_32_KEY *key, int len, const unsigned char *data, int rounds) { RC5_32_INT L[64], l, ll, A, B, *S, k; int i, j, m, c, t, ii, jj; if (len > 255) return 0; if ((rounds != RC5_16_ROUNDS) && (rounds != RC5_12_ROUNDS) && (rounds != RC5_8_ROUNDS)) rounds = RC5_16_ROUNDS; key->rounds = rounds; S = &(key->data[0]); j = 0; for (i = 0; i <= (len - 8); i += 8) { c2l(data, l); L[j++] = l; c2l(data, l); L[j++] = l; } ii = len - i; if (ii) { k = len & 0x07; c2ln(data, l, ll, k); L[j + 0] = l; L[j + 1] = ll; } c = (len + 3) / 4; t = (rounds + 1) * 2; S[0] = RC5_32_P; for (i = 1; i < t; i++) S[i] = (S[i - 1] + RC5_32_Q) & RC5_32_MASK; j = (t > c) ? t : c; j *= 3; ii = jj = 0; A = B = 0; for (i = 0; i < j; i++) { k = (S[ii] + A + B) & RC5_32_MASK; A = S[ii] = ROTATE_l32(k, 3); m = (int)(A + B); k = (L[jj] + A + B) & RC5_32_MASK; B = L[jj] = ROTATE_l32(k, m); if (++ii >= t) ii = 0; if (++jj >= c) jj = 0; } return 1; }
1,743
22.890411
78
c
openssl
openssl-master/crypto/rc5/rc5cfb64.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC5 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc5.h> #include "rc5_local.h" /* * The input and output encrypted as though 64bit cfb mode is being used. * The extra state information to record how much of the 64bit block we have * used is contained in *num; */ void RC5_32_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, RC5_32_KEY *schedule, unsigned char *ivec, int *num, int encrypt) { register unsigned long v0, v1, t; register int n = *num; register long l = length; unsigned long ti[2]; unsigned char *iv, c, cc; iv = (unsigned char *)ivec; if (encrypt) { while (l--) { if (n == 0) { c2l(iv, v0); ti[0] = v0; c2l(iv, v1); ti[1] = v1; RC5_32_encrypt((unsigned long *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2c(t, iv); t = ti[1]; l2c(t, iv); iv = (unsigned char *)ivec; } c = *(in++) ^ iv[n]; *(out++) = c; iv[n] = c; n = (n + 1) & 0x07; } } else { while (l--) { if (n == 0) { c2l(iv, v0); ti[0] = v0; c2l(iv, v1); ti[1] = v1; RC5_32_encrypt((unsigned long *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2c(t, iv); t = ti[1]; l2c(t, iv); iv = (unsigned char *)ivec; } cc = *(in++); c = iv[n]; iv[n] = cc; *(out++) = c ^ cc; n = (n + 1) & 0x07; } } v0 = v1 = ti[0] = ti[1] = t = c = cc = 0; *num = n; }
2,334
27.82716
78
c
openssl
openssl-master/crypto/rc5/rc5ofb64.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC5 low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/rc5.h> #include "rc5_local.h" /* * The input and output encrypted as though 64bit ofb mode is being used. * The extra state information to record how much of the 64bit block we have * used is contained in *num; */ void RC5_32_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, RC5_32_KEY *schedule, unsigned char *ivec, int *num) { register unsigned long v0, v1, t; register int n = *num; register long l = length; unsigned char d[8]; register char *dp; unsigned long ti[2]; unsigned char *iv; int save = 0; iv = (unsigned char *)ivec; c2l(iv, v0); c2l(iv, v1); ti[0] = v0; ti[1] = v1; dp = (char *)d; l2c(v0, dp); l2c(v1, dp); while (l--) { if (n == 0) { RC5_32_encrypt((unsigned long *)ti, schedule); dp = (char *)d; t = ti[0]; l2c(t, dp); t = ti[1]; l2c(t, dp); save++; } *(out++) = *(in++) ^ d[n]; n = (n + 1) & 0x07; } if (save) { v0 = ti[0]; v1 = ti[1]; iv = (unsigned char *)ivec; l2c(v0, iv); l2c(v1, iv); } t = v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
1,767
25
78
c
openssl
openssl-master/crypto/ripemd/rmd_dgst.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RIPEMD160 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "rmd_local.h" #include <openssl/opensslv.h> #ifdef RMD160_ASM void ripemd160_block_x86(RIPEMD160_CTX *c, unsigned long *p, size_t num); # define ripemd160_block ripemd160_block_x86 #else void ripemd160_block(RIPEMD160_CTX *c, unsigned long *p, size_t num); #endif int RIPEMD160_Init(RIPEMD160_CTX *c) { memset(c, 0, sizeof(*c)); c->A = RIPEMD160_A; c->B = RIPEMD160_B; c->C = RIPEMD160_C; c->D = RIPEMD160_D; c->E = RIPEMD160_E; return 1; } #ifndef ripemd160_block_data_order # ifdef X # undef X # endif void ripemd160_block_data_order(RIPEMD160_CTX *ctx, const void *p, size_t num) { const unsigned char *data = p; register unsigned MD32_REG_T A, B, C, D, E; unsigned MD32_REG_T a, b, c, d, e, l; # ifndef MD32_XARRAY /* See comment in crypto/sha/sha_local.h for details. */ unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, XX8, XX9, XX10, XX11, XX12, XX13, XX14, XX15; # define X(i) XX##i # else RIPEMD160_LONG XX[16]; # define X(i) XX[i] # endif for (; num--;) { A = ctx->A; B = ctx->B; C = ctx->C; D = ctx->D; E = ctx->E; (void)HOST_c2l(data, l); X(0) = l; (void)HOST_c2l(data, l); X(1) = l; RIP1(A, B, C, D, E, WL00, SL00); (void)HOST_c2l(data, l); X(2) = l; RIP1(E, A, B, C, D, WL01, SL01); (void)HOST_c2l(data, l); X(3) = l; RIP1(D, E, A, B, C, WL02, SL02); (void)HOST_c2l(data, l); X(4) = l; RIP1(C, D, E, A, B, WL03, SL03); (void)HOST_c2l(data, l); X(5) = l; RIP1(B, C, D, E, A, WL04, SL04); (void)HOST_c2l(data, l); X(6) = l; RIP1(A, B, C, D, E, WL05, SL05); (void)HOST_c2l(data, l); X(7) = l; RIP1(E, A, B, C, D, WL06, SL06); (void)HOST_c2l(data, l); X(8) = l; RIP1(D, E, A, B, C, WL07, SL07); (void)HOST_c2l(data, l); X(9) = l; RIP1(C, D, E, A, B, WL08, SL08); (void)HOST_c2l(data, l); X(10) = l; RIP1(B, C, D, E, A, WL09, SL09); (void)HOST_c2l(data, l); X(11) = l; RIP1(A, B, C, D, E, WL10, SL10); (void)HOST_c2l(data, l); X(12) = l; RIP1(E, A, B, C, D, WL11, SL11); (void)HOST_c2l(data, l); X(13) = l; RIP1(D, E, A, B, C, WL12, SL12); (void)HOST_c2l(data, l); X(14) = l; RIP1(C, D, E, A, B, WL13, SL13); (void)HOST_c2l(data, l); X(15) = l; RIP1(B, C, D, E, A, WL14, SL14); RIP1(A, B, C, D, E, WL15, SL15); RIP2(E, A, B, C, D, WL16, SL16, KL1); RIP2(D, E, A, B, C, WL17, SL17, KL1); RIP2(C, D, E, A, B, WL18, SL18, KL1); RIP2(B, C, D, E, A, WL19, SL19, KL1); RIP2(A, B, C, D, E, WL20, SL20, KL1); RIP2(E, A, B, C, D, WL21, SL21, KL1); RIP2(D, E, A, B, C, WL22, SL22, KL1); RIP2(C, D, E, A, B, WL23, SL23, KL1); RIP2(B, C, D, E, A, WL24, SL24, KL1); RIP2(A, B, C, D, E, WL25, SL25, KL1); RIP2(E, A, B, C, D, WL26, SL26, KL1); RIP2(D, E, A, B, C, WL27, SL27, KL1); RIP2(C, D, E, A, B, WL28, SL28, KL1); RIP2(B, C, D, E, A, WL29, SL29, KL1); RIP2(A, B, C, D, E, WL30, SL30, KL1); RIP2(E, A, B, C, D, WL31, SL31, KL1); RIP3(D, E, A, B, C, WL32, SL32, KL2); RIP3(C, D, E, A, B, WL33, SL33, KL2); RIP3(B, C, D, E, A, WL34, SL34, KL2); RIP3(A, B, C, D, E, WL35, SL35, KL2); RIP3(E, A, B, C, D, WL36, SL36, KL2); RIP3(D, E, A, B, C, WL37, SL37, KL2); RIP3(C, D, E, A, B, WL38, SL38, KL2); RIP3(B, C, D, E, A, WL39, SL39, KL2); RIP3(A, B, C, D, E, WL40, SL40, KL2); RIP3(E, A, B, C, D, WL41, SL41, KL2); RIP3(D, E, A, B, C, WL42, SL42, KL2); RIP3(C, D, E, A, B, WL43, SL43, KL2); RIP3(B, C, D, E, A, WL44, SL44, KL2); RIP3(A, B, C, D, E, WL45, SL45, KL2); RIP3(E, A, B, C, D, WL46, SL46, KL2); RIP3(D, E, A, B, C, WL47, SL47, KL2); RIP4(C, D, E, A, B, WL48, SL48, KL3); RIP4(B, C, D, E, A, WL49, SL49, KL3); RIP4(A, B, C, D, E, WL50, SL50, KL3); RIP4(E, A, B, C, D, WL51, SL51, KL3); RIP4(D, E, A, B, C, WL52, SL52, KL3); RIP4(C, D, E, A, B, WL53, SL53, KL3); RIP4(B, C, D, E, A, WL54, SL54, KL3); RIP4(A, B, C, D, E, WL55, SL55, KL3); RIP4(E, A, B, C, D, WL56, SL56, KL3); RIP4(D, E, A, B, C, WL57, SL57, KL3); RIP4(C, D, E, A, B, WL58, SL58, KL3); RIP4(B, C, D, E, A, WL59, SL59, KL3); RIP4(A, B, C, D, E, WL60, SL60, KL3); RIP4(E, A, B, C, D, WL61, SL61, KL3); RIP4(D, E, A, B, C, WL62, SL62, KL3); RIP4(C, D, E, A, B, WL63, SL63, KL3); RIP5(B, C, D, E, A, WL64, SL64, KL4); RIP5(A, B, C, D, E, WL65, SL65, KL4); RIP5(E, A, B, C, D, WL66, SL66, KL4); RIP5(D, E, A, B, C, WL67, SL67, KL4); RIP5(C, D, E, A, B, WL68, SL68, KL4); RIP5(B, C, D, E, A, WL69, SL69, KL4); RIP5(A, B, C, D, E, WL70, SL70, KL4); RIP5(E, A, B, C, D, WL71, SL71, KL4); RIP5(D, E, A, B, C, WL72, SL72, KL4); RIP5(C, D, E, A, B, WL73, SL73, KL4); RIP5(B, C, D, E, A, WL74, SL74, KL4); RIP5(A, B, C, D, E, WL75, SL75, KL4); RIP5(E, A, B, C, D, WL76, SL76, KL4); RIP5(D, E, A, B, C, WL77, SL77, KL4); RIP5(C, D, E, A, B, WL78, SL78, KL4); RIP5(B, C, D, E, A, WL79, SL79, KL4); a = A; b = B; c = C; d = D; e = E; /* Do other half */ A = ctx->A; B = ctx->B; C = ctx->C; D = ctx->D; E = ctx->E; RIP5(A, B, C, D, E, WR00, SR00, KR0); RIP5(E, A, B, C, D, WR01, SR01, KR0); RIP5(D, E, A, B, C, WR02, SR02, KR0); RIP5(C, D, E, A, B, WR03, SR03, KR0); RIP5(B, C, D, E, A, WR04, SR04, KR0); RIP5(A, B, C, D, E, WR05, SR05, KR0); RIP5(E, A, B, C, D, WR06, SR06, KR0); RIP5(D, E, A, B, C, WR07, SR07, KR0); RIP5(C, D, E, A, B, WR08, SR08, KR0); RIP5(B, C, D, E, A, WR09, SR09, KR0); RIP5(A, B, C, D, E, WR10, SR10, KR0); RIP5(E, A, B, C, D, WR11, SR11, KR0); RIP5(D, E, A, B, C, WR12, SR12, KR0); RIP5(C, D, E, A, B, WR13, SR13, KR0); RIP5(B, C, D, E, A, WR14, SR14, KR0); RIP5(A, B, C, D, E, WR15, SR15, KR0); RIP4(E, A, B, C, D, WR16, SR16, KR1); RIP4(D, E, A, B, C, WR17, SR17, KR1); RIP4(C, D, E, A, B, WR18, SR18, KR1); RIP4(B, C, D, E, A, WR19, SR19, KR1); RIP4(A, B, C, D, E, WR20, SR20, KR1); RIP4(E, A, B, C, D, WR21, SR21, KR1); RIP4(D, E, A, B, C, WR22, SR22, KR1); RIP4(C, D, E, A, B, WR23, SR23, KR1); RIP4(B, C, D, E, A, WR24, SR24, KR1); RIP4(A, B, C, D, E, WR25, SR25, KR1); RIP4(E, A, B, C, D, WR26, SR26, KR1); RIP4(D, E, A, B, C, WR27, SR27, KR1); RIP4(C, D, E, A, B, WR28, SR28, KR1); RIP4(B, C, D, E, A, WR29, SR29, KR1); RIP4(A, B, C, D, E, WR30, SR30, KR1); RIP4(E, A, B, C, D, WR31, SR31, KR1); RIP3(D, E, A, B, C, WR32, SR32, KR2); RIP3(C, D, E, A, B, WR33, SR33, KR2); RIP3(B, C, D, E, A, WR34, SR34, KR2); RIP3(A, B, C, D, E, WR35, SR35, KR2); RIP3(E, A, B, C, D, WR36, SR36, KR2); RIP3(D, E, A, B, C, WR37, SR37, KR2); RIP3(C, D, E, A, B, WR38, SR38, KR2); RIP3(B, C, D, E, A, WR39, SR39, KR2); RIP3(A, B, C, D, E, WR40, SR40, KR2); RIP3(E, A, B, C, D, WR41, SR41, KR2); RIP3(D, E, A, B, C, WR42, SR42, KR2); RIP3(C, D, E, A, B, WR43, SR43, KR2); RIP3(B, C, D, E, A, WR44, SR44, KR2); RIP3(A, B, C, D, E, WR45, SR45, KR2); RIP3(E, A, B, C, D, WR46, SR46, KR2); RIP3(D, E, A, B, C, WR47, SR47, KR2); RIP2(C, D, E, A, B, WR48, SR48, KR3); RIP2(B, C, D, E, A, WR49, SR49, KR3); RIP2(A, B, C, D, E, WR50, SR50, KR3); RIP2(E, A, B, C, D, WR51, SR51, KR3); RIP2(D, E, A, B, C, WR52, SR52, KR3); RIP2(C, D, E, A, B, WR53, SR53, KR3); RIP2(B, C, D, E, A, WR54, SR54, KR3); RIP2(A, B, C, D, E, WR55, SR55, KR3); RIP2(E, A, B, C, D, WR56, SR56, KR3); RIP2(D, E, A, B, C, WR57, SR57, KR3); RIP2(C, D, E, A, B, WR58, SR58, KR3); RIP2(B, C, D, E, A, WR59, SR59, KR3); RIP2(A, B, C, D, E, WR60, SR60, KR3); RIP2(E, A, B, C, D, WR61, SR61, KR3); RIP2(D, E, A, B, C, WR62, SR62, KR3); RIP2(C, D, E, A, B, WR63, SR63, KR3); RIP1(B, C, D, E, A, WR64, SR64); RIP1(A, B, C, D, E, WR65, SR65); RIP1(E, A, B, C, D, WR66, SR66); RIP1(D, E, A, B, C, WR67, SR67); RIP1(C, D, E, A, B, WR68, SR68); RIP1(B, C, D, E, A, WR69, SR69); RIP1(A, B, C, D, E, WR70, SR70); RIP1(E, A, B, C, D, WR71, SR71); RIP1(D, E, A, B, C, WR72, SR72); RIP1(C, D, E, A, B, WR73, SR73); RIP1(B, C, D, E, A, WR74, SR74); RIP1(A, B, C, D, E, WR75, SR75); RIP1(E, A, B, C, D, WR76, SR76); RIP1(D, E, A, B, C, WR77, SR77); RIP1(C, D, E, A, B, WR78, SR78); RIP1(B, C, D, E, A, WR79, SR79); D = ctx->B + c + D; ctx->B = ctx->C + d + E; ctx->C = ctx->D + e + A; ctx->D = ctx->E + a + B; ctx->E = ctx->A + b + C; ctx->A = D; } } #endif
10,085
33.899654
78
c
openssl
openssl-master/crypto/ripemd/rmd_local.h
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/ripemd.h> /* * DO EXAMINE COMMENTS IN crypto/md5/md5_local.h & crypto/md5/md5_dgst.c * FOR EXPLANATIONS ON FOLLOWING "CODE." */ #ifdef RMD160_ASM # if defined(__i386) || defined(__i386__) || defined(_M_IX86) # define ripemd160_block_data_order ripemd160_block_asm_data_order # endif #endif void ripemd160_block_data_order(RIPEMD160_CTX *c, const void *p, size_t num); #define DATA_ORDER_IS_LITTLE_ENDIAN #define HASH_LONG RIPEMD160_LONG #define HASH_CTX RIPEMD160_CTX #define HASH_CBLOCK RIPEMD160_CBLOCK #define HASH_UPDATE RIPEMD160_Update #define HASH_TRANSFORM RIPEMD160_Transform #define HASH_FINAL RIPEMD160_Final #define HASH_MAKE_STRING(c,s) do { \ unsigned long ll; \ ll=(c)->A; (void)HOST_l2c(ll,(s)); \ ll=(c)->B; (void)HOST_l2c(ll,(s)); \ ll=(c)->C; (void)HOST_l2c(ll,(s)); \ ll=(c)->D; (void)HOST_l2c(ll,(s)); \ ll=(c)->E; (void)HOST_l2c(ll,(s)); \ } while (0) #define HASH_BLOCK_DATA_ORDER ripemd160_block_data_order #include "crypto/md32_common.h" /* * Transformed F2 and F4 are courtesy of Wei Dai */ #define F1(x,y,z) ((x) ^ (y) ^ (z)) #define F2(x,y,z) ((((y) ^ (z)) & (x)) ^ (z)) #define F3(x,y,z) (((~(y)) | (x)) ^ (z)) #define F4(x,y,z) ((((x) ^ (y)) & (z)) ^ (y)) #define F5(x,y,z) (((~(z)) | (y)) ^ (x)) #define RIPEMD160_A 0x67452301L #define RIPEMD160_B 0xEFCDAB89L #define RIPEMD160_C 0x98BADCFEL #define RIPEMD160_D 0x10325476L #define RIPEMD160_E 0xC3D2E1F0L #include "rmdconst.h" #define RIP1(a,b,c,d,e,w,s) { \ a+=F1(b,c,d)+X(w); \ a=ROTATE(a,s)+e; \ c=ROTATE(c,10); } #define RIP2(a,b,c,d,e,w,s,K) { \ a+=F2(b,c,d)+X(w)+K; \ a=ROTATE(a,s)+e; \ c=ROTATE(c,10); } #define RIP3(a,b,c,d,e,w,s,K) { \ a+=F3(b,c,d)+X(w)+K; \ a=ROTATE(a,s)+e; \ c=ROTATE(c,10); } #define RIP4(a,b,c,d,e,w,s,K) { \ a+=F4(b,c,d)+X(w)+K; \ a=ROTATE(a,s)+e; \ c=ROTATE(c,10); } #define RIP5(a,b,c,d,e,w,s,K) { \ a+=F5(b,c,d)+X(w)+K; \ a=ROTATE(a,s)+e; \ c=ROTATE(c,10); }
2,669
29.340909
77
h
openssl
openssl-master/crypto/ripemd/rmd_one.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RIPEMD160 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/ripemd.h> #include <openssl/crypto.h> unsigned char *RIPEMD160(const unsigned char *d, size_t n, unsigned char *md) { RIPEMD160_CTX c; static unsigned char m[RIPEMD160_DIGEST_LENGTH]; if (md == NULL) md = m; if (!RIPEMD160_Init(&c)) return NULL; RIPEMD160_Update(&c, d, n); RIPEMD160_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ return md; }
951
26.2
77
c
openssl
openssl-master/crypto/rsa/rsa_acvp_test_params.c
/* * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> /* memcpy */ #include <openssl/core_names.h> #include <openssl/param_build.h> #include "crypto/rsa.h" #include "rsa_local.h" int ossl_rsa_acvp_test_gen_params_new(OSSL_PARAM **dst, const OSSL_PARAM src[]) { const OSSL_PARAM *p, *s; OSSL_PARAM *d, *alloc = NULL; int ret = 1; static const OSSL_PARAM settable[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XP, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XP1, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XP2, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XQ, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XQ1, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_TEST_XQ2, NULL, 0), OSSL_PARAM_END }; /* Assume the first element is a required field if this feature is used */ p = OSSL_PARAM_locate_const(src, settable[0].key); if (p == NULL) return 1; /* Zeroing here means the terminator is always set at the end */ alloc = OPENSSL_zalloc(sizeof(settable)); if (alloc == NULL) return 0; d = alloc; for (s = settable; s->key != NULL; ++s) { /* If src contains a key from settable then copy the src to the dest */ p = OSSL_PARAM_locate_const(src, s->key); if (p != NULL) { *d = *s; /* shallow copy from the static settable[] */ d->data_size = p->data_size; d->data = OPENSSL_memdup(p->data, p->data_size); if (d->data == NULL) ret = 0; ++d; } } if (ret == 0) { ossl_rsa_acvp_test_gen_params_free(alloc); alloc = NULL; } if (*dst != NULL) ossl_rsa_acvp_test_gen_params_free(*dst); *dst = alloc; return ret; } void ossl_rsa_acvp_test_gen_params_free(OSSL_PARAM *dst) { OSSL_PARAM *p; if (dst == NULL) return; for (p = dst; p->key != NULL; ++p) { OPENSSL_free(p->data); p->data = NULL; } OPENSSL_free(dst); } int ossl_rsa_acvp_test_set_params(RSA *r, const OSSL_PARAM params[]) { RSA_ACVP_TEST *t; const OSSL_PARAM *p; if (r->acvp_test != NULL) { ossl_rsa_acvp_test_free(r->acvp_test); r->acvp_test = NULL; } t = OPENSSL_zalloc(sizeof(*t)); if (t == NULL) return 0; /* Set the input parameters */ if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XP1)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xp1)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XP2)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xp2)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XP)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xp)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XQ1)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xq1)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XQ2)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xq2)) goto err; if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_TEST_XQ)) != NULL && !OSSL_PARAM_get_BN(p, &t->Xq)) goto err; /* Setup the output parameters */ t->p1 = BN_new(); t->p2 = BN_new(); t->q1 = BN_new(); t->q2 = BN_new(); r->acvp_test = t; return 1; err: ossl_rsa_acvp_test_free(t); return 0; } int ossl_rsa_acvp_test_get_params(RSA *r, OSSL_PARAM params[]) { RSA_ACVP_TEST *t; OSSL_PARAM *p; if (r == NULL) return 0; t = r->acvp_test; if (t != NULL) { if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_RSA_TEST_P1)) != NULL && !OSSL_PARAM_set_BN(p, t->p1)) return 0; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_RSA_TEST_P2)) != NULL && !OSSL_PARAM_set_BN(p, t->p2)) return 0; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_RSA_TEST_Q1)) != NULL && !OSSL_PARAM_set_BN(p, t->q1)) return 0; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_RSA_TEST_Q2)) != NULL && !OSSL_PARAM_set_BN(p, t->q2)) return 0; } return 1; } void ossl_rsa_acvp_test_free(RSA_ACVP_TEST *t) { if (t != NULL) { BN_free(t->Xp1); BN_free(t->Xp2); BN_free(t->Xp); BN_free(t->Xq1); BN_free(t->Xq2); BN_free(t->Xq); BN_free(t->p1); BN_free(t->p2); BN_free(t->q1); BN_free(t->q2); OPENSSL_free(t); } }
4,967
28.571429
83
c
openssl
openssl-master/crypto/rsa/rsa_asn1.c
/* * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/x509.h> #include <openssl/asn1t.h> #include "rsa_local.h" /* * Override the default free and new methods, * and calculate helper products for multi-prime * RSA keys. */ static int rsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_NEW_PRE) { *pval = (ASN1_VALUE *)RSA_new(); if (*pval != NULL) return 2; return 0; } else if (operation == ASN1_OP_FREE_PRE) { RSA_free((RSA *)*pval); *pval = NULL; return 2; } else if (operation == ASN1_OP_D2I_POST) { if (((RSA *)*pval)->version != RSA_ASN1_VERSION_MULTI) { /* not a multi-prime key, skip */ return 1; } return (ossl_rsa_multip_calc_product((RSA *)*pval) == 1) ? 2 : 0; } return 1; } /* Based on definitions in RFC 8017 appendix A.1.2 */ ASN1_SEQUENCE(RSA_PRIME_INFO) = { ASN1_SIMPLE(RSA_PRIME_INFO, r, CBIGNUM), ASN1_SIMPLE(RSA_PRIME_INFO, d, CBIGNUM), ASN1_SIMPLE(RSA_PRIME_INFO, t, CBIGNUM), } ASN1_SEQUENCE_END(RSA_PRIME_INFO) ASN1_SEQUENCE_cb(RSAPrivateKey, rsa_cb) = { ASN1_EMBED(RSA, version, INT32), ASN1_SIMPLE(RSA, n, BIGNUM), ASN1_SIMPLE(RSA, e, BIGNUM), ASN1_SIMPLE(RSA, d, CBIGNUM), ASN1_SIMPLE(RSA, p, CBIGNUM), ASN1_SIMPLE(RSA, q, CBIGNUM), ASN1_SIMPLE(RSA, dmp1, CBIGNUM), ASN1_SIMPLE(RSA, dmq1, CBIGNUM), ASN1_SIMPLE(RSA, iqmp, CBIGNUM), ASN1_SEQUENCE_OF_OPT(RSA, prime_infos, RSA_PRIME_INFO) } ASN1_SEQUENCE_END_cb(RSA, RSAPrivateKey) ASN1_SEQUENCE_cb(RSAPublicKey, rsa_cb) = { ASN1_SIMPLE(RSA, n, BIGNUM), ASN1_SIMPLE(RSA, e, BIGNUM), } ASN1_SEQUENCE_END_cb(RSA, RSAPublicKey) /* Free up maskHash */ static int rsa_pss_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_FREE_PRE) { RSA_PSS_PARAMS *pss = (RSA_PSS_PARAMS *)*pval; X509_ALGOR_free(pss->maskHash); } return 1; } ASN1_SEQUENCE_cb(RSA_PSS_PARAMS, rsa_pss_cb) = { ASN1_EXP_OPT(RSA_PSS_PARAMS, hashAlgorithm, X509_ALGOR,0), ASN1_EXP_OPT(RSA_PSS_PARAMS, maskGenAlgorithm, X509_ALGOR,1), ASN1_EXP_OPT(RSA_PSS_PARAMS, saltLength, ASN1_INTEGER,2), ASN1_EXP_OPT(RSA_PSS_PARAMS, trailerField, ASN1_INTEGER,3) } ASN1_SEQUENCE_END_cb(RSA_PSS_PARAMS, RSA_PSS_PARAMS) IMPLEMENT_ASN1_FUNCTIONS(RSA_PSS_PARAMS) IMPLEMENT_ASN1_DUP_FUNCTION(RSA_PSS_PARAMS) /* Free up maskHash */ static int rsa_oaep_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_FREE_PRE) { RSA_OAEP_PARAMS *oaep = (RSA_OAEP_PARAMS *)*pval; X509_ALGOR_free(oaep->maskHash); } return 1; } ASN1_SEQUENCE_cb(RSA_OAEP_PARAMS, rsa_oaep_cb) = { ASN1_EXP_OPT(RSA_OAEP_PARAMS, hashFunc, X509_ALGOR, 0), ASN1_EXP_OPT(RSA_OAEP_PARAMS, maskGenFunc, X509_ALGOR, 1), ASN1_EXP_OPT(RSA_OAEP_PARAMS, pSourceFunc, X509_ALGOR, 2), } ASN1_SEQUENCE_END_cb(RSA_OAEP_PARAMS, RSA_OAEP_PARAMS) IMPLEMENT_ASN1_FUNCTIONS(RSA_OAEP_PARAMS) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(RSA, RSAPrivateKey, RSAPrivateKey) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(RSA, RSAPublicKey, RSAPublicKey) RSA *RSAPublicKey_dup(const RSA *rsa) { return ASN1_item_dup(ASN1_ITEM_rptr(RSAPublicKey), rsa); } RSA *RSAPrivateKey_dup(const RSA *rsa) { return ASN1_item_dup(ASN1_ITEM_rptr(RSAPrivateKey), rsa); }
4,093
30.736434
77
c
openssl
openssl-master/crypto/rsa/rsa_backend.c
/* * Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include <openssl/core_names.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/evp.h> #ifndef FIPS_MODULE # include <openssl/x509.h> # include "crypto/asn1.h" #endif #include "internal/sizes.h" #include "internal/param_build_set.h" #include "crypto/rsa.h" #include "rsa_local.h" /* * The intention with the "backend" source file is to offer backend support * for legacy backends (EVP_PKEY_ASN1_METHOD and EVP_PKEY_METHOD) and provider * implementations alike. */ DEFINE_STACK_OF(BIGNUM) static int collect_numbers(STACK_OF(BIGNUM) *numbers, const OSSL_PARAM params[], const char *names[]) { const OSSL_PARAM *p = NULL; int i; if (numbers == NULL) return 0; for (i = 0; names[i] != NULL; i++) { p = OSSL_PARAM_locate_const(params, names[i]); if (p != NULL) { BIGNUM *tmp = NULL; if (!OSSL_PARAM_get_BN(p, &tmp)) return 0; if (sk_BIGNUM_push(numbers, tmp) == 0) { BN_clear_free(tmp); return 0; } } } return 1; } int ossl_rsa_fromdata(RSA *rsa, const OSSL_PARAM params[], int include_private) { const OSSL_PARAM *param_n, *param_e, *param_d = NULL; BIGNUM *n = NULL, *e = NULL, *d = NULL; STACK_OF(BIGNUM) *factors = NULL, *exps = NULL, *coeffs = NULL; int is_private = 0; if (rsa == NULL) return 0; param_n = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_N); param_e = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_E); if (include_private) param_d = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_D); if ((param_n != NULL && !OSSL_PARAM_get_BN(param_n, &n)) || (param_e != NULL && !OSSL_PARAM_get_BN(param_e, &e)) || (param_d != NULL && !OSSL_PARAM_get_BN(param_d, &d))) goto err; is_private = (d != NULL); if (!RSA_set0_key(rsa, n, e, d)) goto err; n = e = d = NULL; if (is_private) { if (!collect_numbers(factors = sk_BIGNUM_new_null(), params, ossl_rsa_mp_factor_names) || !collect_numbers(exps = sk_BIGNUM_new_null(), params, ossl_rsa_mp_exp_names) || !collect_numbers(coeffs = sk_BIGNUM_new_null(), params, ossl_rsa_mp_coeff_names)) goto err; /* It's ok if this private key just has n, e and d */ if (sk_BIGNUM_num(factors) != 0 && !ossl_rsa_set0_all_params(rsa, factors, exps, coeffs)) goto err; } sk_BIGNUM_free(factors); sk_BIGNUM_free(exps); sk_BIGNUM_free(coeffs); return 1; err: BN_free(n); BN_free(e); BN_free(d); sk_BIGNUM_pop_free(factors, BN_free); sk_BIGNUM_pop_free(exps, BN_free); sk_BIGNUM_pop_free(coeffs, BN_free); return 0; } DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM) int ossl_rsa_todata(RSA *rsa, OSSL_PARAM_BLD *bld, OSSL_PARAM params[], int include_private) { int ret = 0; const BIGNUM *rsa_d = NULL, *rsa_n = NULL, *rsa_e = NULL; STACK_OF(BIGNUM_const) *factors = sk_BIGNUM_const_new_null(); STACK_OF(BIGNUM_const) *exps = sk_BIGNUM_const_new_null(); STACK_OF(BIGNUM_const) *coeffs = sk_BIGNUM_const_new_null(); if (rsa == NULL || factors == NULL || exps == NULL || coeffs == NULL) goto err; RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); ossl_rsa_get0_all_params(rsa, factors, exps, coeffs); if (!ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_RSA_N, rsa_n) || !ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_RSA_E, rsa_e)) goto err; /* Check private key data integrity */ if (include_private && rsa_d != NULL) { int numprimes = sk_BIGNUM_const_num(factors); int numexps = sk_BIGNUM_const_num(exps); int numcoeffs = sk_BIGNUM_const_num(coeffs); /* * It's permissible to have zero primes, i.e. no CRT params. * Otherwise, there must be at least two, as many exponents, * and one coefficient less. */ if (numprimes != 0 && (numprimes < 2 || numexps < 2 || numcoeffs < 1)) goto err; if (!ossl_param_build_set_bn(bld, params, OSSL_PKEY_PARAM_RSA_D, rsa_d) || !ossl_param_build_set_multi_key_bn(bld, params, ossl_rsa_mp_factor_names, factors) || !ossl_param_build_set_multi_key_bn(bld, params, ossl_rsa_mp_exp_names, exps) || !ossl_param_build_set_multi_key_bn(bld, params, ossl_rsa_mp_coeff_names, coeffs)) goto err; } #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) /* The acvp test results are not meant for export so check for bld == NULL */ if (bld == NULL) ossl_rsa_acvp_test_get_params(rsa, params); #endif ret = 1; err: sk_BIGNUM_const_free(factors); sk_BIGNUM_const_free(exps); sk_BIGNUM_const_free(coeffs); return ret; } int ossl_rsa_pss_params_30_todata(const RSA_PSS_PARAMS_30 *pss, OSSL_PARAM_BLD *bld, OSSL_PARAM params[]) { if (!ossl_rsa_pss_params_30_is_unrestricted(pss)) { int hashalg_nid = ossl_rsa_pss_params_30_hashalg(pss); int maskgenalg_nid = ossl_rsa_pss_params_30_maskgenalg(pss); int maskgenhashalg_nid = ossl_rsa_pss_params_30_maskgenhashalg(pss); int saltlen = ossl_rsa_pss_params_30_saltlen(pss); int default_hashalg_nid = ossl_rsa_pss_params_30_hashalg(NULL); int default_maskgenalg_nid = ossl_rsa_pss_params_30_maskgenalg(NULL); int default_maskgenhashalg_nid = ossl_rsa_pss_params_30_maskgenhashalg(NULL); const char *mdname = (hashalg_nid == default_hashalg_nid ? NULL : ossl_rsa_oaeppss_nid2name(hashalg_nid)); const char *mgfname = (maskgenalg_nid == default_maskgenalg_nid ? NULL : ossl_rsa_oaeppss_nid2name(maskgenalg_nid)); const char *mgf1mdname = (maskgenhashalg_nid == default_maskgenhashalg_nid ? NULL : ossl_rsa_oaeppss_nid2name(maskgenhashalg_nid)); const char *key_md = OSSL_PKEY_PARAM_RSA_DIGEST; const char *key_mgf = OSSL_PKEY_PARAM_RSA_MASKGENFUNC; const char *key_mgf1_md = OSSL_PKEY_PARAM_RSA_MGF1_DIGEST; const char *key_saltlen = OSSL_PKEY_PARAM_RSA_PSS_SALTLEN; /* * To ensure that the key isn't seen as unrestricted by the recipient, * we make sure that at least one PSS-related parameter is passed, even * if it has a default value; saltlen. */ if ((mdname != NULL && !ossl_param_build_set_utf8_string(bld, params, key_md, mdname)) || (mgfname != NULL && !ossl_param_build_set_utf8_string(bld, params, key_mgf, mgfname)) || (mgf1mdname != NULL && !ossl_param_build_set_utf8_string(bld, params, key_mgf1_md, mgf1mdname)) || (!ossl_param_build_set_int(bld, params, key_saltlen, saltlen))) return 0; } return 1; } int ossl_rsa_pss_params_30_fromdata(RSA_PSS_PARAMS_30 *pss_params, int *defaults_set, const OSSL_PARAM params[], OSSL_LIB_CTX *libctx) { const OSSL_PARAM *param_md, *param_mgf, *param_mgf1md, *param_saltlen; const OSSL_PARAM *param_propq; const char *propq = NULL; EVP_MD *md = NULL, *mgf1md = NULL; int saltlen; int ret = 0; if (pss_params == NULL) return 0; param_propq = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_DIGEST_PROPS); param_md = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_DIGEST); param_mgf = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_MASKGENFUNC); param_mgf1md = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_MGF1_DIGEST); param_saltlen = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_PSS_SALTLEN); if (param_propq != NULL) { if (param_propq->data_type == OSSL_PARAM_UTF8_STRING) propq = param_propq->data; } /* * If we get any of the parameters, we know we have at least some * restrictions, so we start by setting default values, and let each * parameter override their specific restriction data. */ if (!*defaults_set && (param_md != NULL || param_mgf != NULL || param_mgf1md != NULL || param_saltlen != NULL)) { if (!ossl_rsa_pss_params_30_set_defaults(pss_params)) return 0; *defaults_set = 1; } if (param_mgf != NULL) { int default_maskgenalg_nid = ossl_rsa_pss_params_30_maskgenalg(NULL); const char *mgfname = NULL; if (param_mgf->data_type == OSSL_PARAM_UTF8_STRING) mgfname = param_mgf->data; else if (!OSSL_PARAM_get_utf8_ptr(param_mgf, &mgfname)) return 0; if (OPENSSL_strcasecmp(param_mgf->data, ossl_rsa_mgf_nid2name(default_maskgenalg_nid)) != 0) return 0; } /* * We're only interested in the NIDs that correspond to the MDs, so the * exact propquery is unimportant in the EVP_MD_fetch() calls below. */ if (param_md != NULL) { const char *mdname = NULL; if (param_md->data_type == OSSL_PARAM_UTF8_STRING) mdname = param_md->data; else if (!OSSL_PARAM_get_utf8_ptr(param_mgf, &mdname)) goto err; if ((md = EVP_MD_fetch(libctx, mdname, propq)) == NULL || !ossl_rsa_pss_params_30_set_hashalg(pss_params, ossl_rsa_oaeppss_md2nid(md))) goto err; } if (param_mgf1md != NULL) { const char *mgf1mdname = NULL; if (param_mgf1md->data_type == OSSL_PARAM_UTF8_STRING) mgf1mdname = param_mgf1md->data; else if (!OSSL_PARAM_get_utf8_ptr(param_mgf, &mgf1mdname)) goto err; if ((mgf1md = EVP_MD_fetch(libctx, mgf1mdname, propq)) == NULL || !ossl_rsa_pss_params_30_set_maskgenhashalg( pss_params, ossl_rsa_oaeppss_md2nid(mgf1md))) goto err; } if (param_saltlen != NULL) { if (!OSSL_PARAM_get_int(param_saltlen, &saltlen) || !ossl_rsa_pss_params_30_set_saltlen(pss_params, saltlen)) goto err; } ret = 1; err: EVP_MD_free(md); EVP_MD_free(mgf1md); return ret; } int ossl_rsa_is_foreign(const RSA *rsa) { #ifndef FIPS_MODULE if (rsa->engine != NULL || RSA_get_method(rsa) != RSA_PKCS1_OpenSSL()) return 1; #endif return 0; } static ossl_inline int rsa_bn_dup_check(BIGNUM **out, const BIGNUM *f) { if (f != NULL && (*out = BN_dup(f)) == NULL) return 0; return 1; } RSA *ossl_rsa_dup(const RSA *rsa, int selection) { RSA *dupkey = NULL; #ifndef FIPS_MODULE int pnum, i; #endif /* Do not try to duplicate foreign RSA keys */ if (ossl_rsa_is_foreign(rsa)) return NULL; if ((dupkey = ossl_rsa_new_with_ctx(rsa->libctx)) == NULL) return NULL; /* public key */ if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) { if (!rsa_bn_dup_check(&dupkey->n, rsa->n)) goto err; if (!rsa_bn_dup_check(&dupkey->e, rsa->e)) goto err; } if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) { /* private key */ if (!rsa_bn_dup_check(&dupkey->d, rsa->d)) goto err; /* factors and crt params */ if (!rsa_bn_dup_check(&dupkey->p, rsa->p)) goto err; if (!rsa_bn_dup_check(&dupkey->q, rsa->q)) goto err; if (!rsa_bn_dup_check(&dupkey->dmp1, rsa->dmp1)) goto err; if (!rsa_bn_dup_check(&dupkey->dmq1, rsa->dmq1)) goto err; if (!rsa_bn_dup_check(&dupkey->iqmp, rsa->iqmp)) goto err; } dupkey->version = rsa->version; dupkey->flags = rsa->flags; /* we always copy the PSS parameters regardless of selection */ dupkey->pss_params = rsa->pss_params; #ifndef FIPS_MODULE /* multiprime */ if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0 && (pnum = sk_RSA_PRIME_INFO_num(rsa->prime_infos)) > 0) { dupkey->prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum); if (dupkey->prime_infos == NULL) goto err; for (i = 0; i < pnum; i++) { const RSA_PRIME_INFO *pinfo = NULL; RSA_PRIME_INFO *duppinfo = NULL; if ((duppinfo = OPENSSL_zalloc(sizeof(*duppinfo))) == NULL) goto err; /* push first so cleanup in error case works */ (void)sk_RSA_PRIME_INFO_push(dupkey->prime_infos, duppinfo); pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); if (!rsa_bn_dup_check(&duppinfo->r, pinfo->r)) goto err; if (!rsa_bn_dup_check(&duppinfo->d, pinfo->d)) goto err; if (!rsa_bn_dup_check(&duppinfo->t, pinfo->t)) goto err; } if (!ossl_rsa_multip_calc_product(dupkey)) goto err; } if (rsa->pss != NULL) { dupkey->pss = RSA_PSS_PARAMS_dup(rsa->pss); if (rsa->pss->maskGenAlgorithm != NULL && dupkey->pss->maskGenAlgorithm == NULL) { dupkey->pss->maskHash = ossl_x509_algor_mgf1_decode(rsa->pss->maskGenAlgorithm); if (dupkey->pss->maskHash == NULL) goto err; } } if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_RSA, &dupkey->ex_data, &rsa->ex_data)) goto err; #endif return dupkey; err: RSA_free(dupkey); return NULL; } #ifndef FIPS_MODULE RSA_PSS_PARAMS *ossl_rsa_pss_decode(const X509_ALGOR *alg) { RSA_PSS_PARAMS *pss; pss = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_PSS_PARAMS), alg->parameter); if (pss == NULL) return NULL; if (pss->maskGenAlgorithm != NULL) { pss->maskHash = ossl_x509_algor_mgf1_decode(pss->maskGenAlgorithm); if (pss->maskHash == NULL) { RSA_PSS_PARAMS_free(pss); return NULL; } } return pss; } static int ossl_rsa_sync_to_pss_params_30(RSA *rsa) { const RSA_PSS_PARAMS *legacy_pss = NULL; RSA_PSS_PARAMS_30 *pss = NULL; if (rsa != NULL && (legacy_pss = RSA_get0_pss_params(rsa)) != NULL && (pss = ossl_rsa_get0_pss_params_30(rsa)) != NULL) { const EVP_MD *md = NULL, *mgf1md = NULL; int md_nid, mgf1md_nid, saltlen, trailerField; RSA_PSS_PARAMS_30 pss_params; /* * We don't care about the validity of the fields here, we just * want to synchronise values. Verifying here makes it impossible * to even read a key with invalid values, making it hard to test * a bad situation. * * Other routines use ossl_rsa_pss_get_param(), so the values will * be checked, eventually. */ if (!ossl_rsa_pss_get_param_unverified(legacy_pss, &md, &mgf1md, &saltlen, &trailerField)) return 0; md_nid = EVP_MD_get_type(md); mgf1md_nid = EVP_MD_get_type(mgf1md); if (!ossl_rsa_pss_params_30_set_defaults(&pss_params) || !ossl_rsa_pss_params_30_set_hashalg(&pss_params, md_nid) || !ossl_rsa_pss_params_30_set_maskgenhashalg(&pss_params, mgf1md_nid) || !ossl_rsa_pss_params_30_set_saltlen(&pss_params, saltlen) || !ossl_rsa_pss_params_30_set_trailerfield(&pss_params, trailerField)) return 0; *pss = pss_params; } return 1; } int ossl_rsa_pss_get_param_unverified(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd, const EVP_MD **pmgf1md, int *psaltlen, int *ptrailerField) { RSA_PSS_PARAMS_30 pss_params; /* Get the defaults from the ONE place */ (void)ossl_rsa_pss_params_30_set_defaults(&pss_params); if (pss == NULL) return 0; *pmd = ossl_x509_algor_get_md(pss->hashAlgorithm); if (*pmd == NULL) return 0; *pmgf1md = ossl_x509_algor_get_md(pss->maskHash); if (*pmgf1md == NULL) return 0; if (pss->saltLength) *psaltlen = ASN1_INTEGER_get(pss->saltLength); else *psaltlen = ossl_rsa_pss_params_30_saltlen(&pss_params); if (pss->trailerField) *ptrailerField = ASN1_INTEGER_get(pss->trailerField); else *ptrailerField = ossl_rsa_pss_params_30_trailerfield(&pss_params); return 1; } int ossl_rsa_param_decode(RSA *rsa, const X509_ALGOR *alg) { RSA_PSS_PARAMS *pss; const ASN1_OBJECT *algoid; const void *algp; int algptype; X509_ALGOR_get0(&algoid, &algptype, &algp, alg); if (OBJ_obj2nid(algoid) != EVP_PKEY_RSA_PSS) return 1; if (algptype == V_ASN1_UNDEF) return 1; if (algptype != V_ASN1_SEQUENCE) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PSS_PARAMETERS); return 0; } if ((pss = ossl_rsa_pss_decode(alg)) == NULL || !ossl_rsa_set0_pss_params(rsa, pss)) { RSA_PSS_PARAMS_free(pss); return 0; } if (!ossl_rsa_sync_to_pss_params_30(rsa)) return 0; return 1; } RSA *ossl_rsa_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq) { const unsigned char *p; RSA *rsa; int pklen; const X509_ALGOR *alg; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &alg, p8inf)) return 0; rsa = d2i_RSAPrivateKey(NULL, &p, pklen); if (rsa == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_RSA_LIB); return NULL; } if (!ossl_rsa_param_decode(rsa, alg)) { RSA_free(rsa); return NULL; } RSA_clear_flags(rsa, RSA_FLAG_TYPE_MASK); switch (OBJ_obj2nid(alg->algorithm)) { case EVP_PKEY_RSA: RSA_set_flags(rsa, RSA_FLAG_TYPE_RSA); break; case EVP_PKEY_RSA_PSS: RSA_set_flags(rsa, RSA_FLAG_TYPE_RSASSAPSS); break; default: /* Leave the type bits zero */ break; } return rsa; } #endif
19,515
31.855219
92
c
openssl
openssl-master/crypto/rsa/rsa_chk.c
/* * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/bn.h> #include <openssl/err.h> #include "crypto/rsa.h" #include "rsa_local.h" #ifndef FIPS_MODULE static int rsa_validate_keypair_multiprime(const RSA *key, BN_GENCB *cb) { BIGNUM *i, *j, *k, *l, *m; BN_CTX *ctx; int ret = 1, ex_primes = 0, idx; RSA_PRIME_INFO *pinfo; if (key->p == NULL || key->q == NULL || key->n == NULL || key->e == NULL || key->d == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_VALUE_MISSING); return 0; } /* multi-prime? */ if (key->version == RSA_ASN1_VERSION_MULTI) { ex_primes = sk_RSA_PRIME_INFO_num(key->prime_infos); if (ex_primes <= 0 || (ex_primes + 2) > ossl_rsa_multip_cap(BN_num_bits(key->n))) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MULTI_PRIME_KEY); return 0; } } i = BN_new(); j = BN_new(); k = BN_new(); l = BN_new(); m = BN_new(); ctx = BN_CTX_new_ex(key->libctx); if (i == NULL || j == NULL || k == NULL || l == NULL || m == NULL || ctx == NULL) { ret = -1; ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); goto err; } if (BN_is_one(key->e)) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE); } if (!BN_is_odd(key->e)) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE); } /* p prime? */ if (BN_check_prime(key->p, ctx, cb) != 1) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_P_NOT_PRIME); } /* q prime? */ if (BN_check_prime(key->q, ctx, cb) != 1) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_Q_NOT_PRIME); } /* r_i prime? */ for (idx = 0; idx < ex_primes; idx++) { pinfo = sk_RSA_PRIME_INFO_value(key->prime_infos, idx); if (BN_check_prime(pinfo->r, ctx, cb) != 1) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_MP_R_NOT_PRIME); } } /* n = p*q * r_3...r_i? */ if (!BN_mul(i, key->p, key->q, ctx)) { ret = -1; goto err; } for (idx = 0; idx < ex_primes; idx++) { pinfo = sk_RSA_PRIME_INFO_value(key->prime_infos, idx); if (!BN_mul(i, i, pinfo->r, ctx)) { ret = -1; goto err; } } if (BN_cmp(i, key->n) != 0) { ret = 0; if (ex_primes) ERR_raise(ERR_LIB_RSA, RSA_R_N_DOES_NOT_EQUAL_PRODUCT_OF_PRIMES); else ERR_raise(ERR_LIB_RSA, RSA_R_N_DOES_NOT_EQUAL_P_Q); } /* d*e = 1 mod \lambda(n)? */ if (!BN_sub(i, key->p, BN_value_one())) { ret = -1; goto err; } if (!BN_sub(j, key->q, BN_value_one())) { ret = -1; goto err; } /* now compute k = \lambda(n) = LCM(i, j, r_3 - 1...) */ if (!BN_mul(l, i, j, ctx)) { ret = -1; goto err; } if (!BN_gcd(m, i, j, ctx)) { ret = -1; goto err; } if (!BN_div(m, NULL, l, m, ctx)) { /* remainder is 0 */ ret = -1; goto err; } for (idx = 0; idx < ex_primes; idx++) { pinfo = sk_RSA_PRIME_INFO_value(key->prime_infos, idx); if (!BN_sub(k, pinfo->r, BN_value_one())) { ret = -1; goto err; } if (!BN_mul(l, m, k, ctx)) { ret = -1; goto err; } if (!BN_gcd(m, m, k, ctx)) { ret = -1; goto err; } if (!BN_div(m, NULL, l, m, ctx)) { /* remainder is 0 */ ret = -1; goto err; } } if (!BN_mod_mul(i, key->d, key->e, m, ctx)) { ret = -1; goto err; } if (!BN_is_one(i)) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_D_E_NOT_CONGRUENT_TO_1); } if (key->dmp1 != NULL && key->dmq1 != NULL && key->iqmp != NULL) { /* dmp1 = d mod (p-1)? */ if (!BN_sub(i, key->p, BN_value_one())) { ret = -1; goto err; } if (!BN_mod(j, key->d, i, ctx)) { ret = -1; goto err; } if (BN_cmp(j, key->dmp1) != 0) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_DMP1_NOT_CONGRUENT_TO_D); } /* dmq1 = d mod (q-1)? */ if (!BN_sub(i, key->q, BN_value_one())) { ret = -1; goto err; } if (!BN_mod(j, key->d, i, ctx)) { ret = -1; goto err; } if (BN_cmp(j, key->dmq1) != 0) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_DMQ1_NOT_CONGRUENT_TO_D); } /* iqmp = q^-1 mod p? */ if (!BN_mod_inverse(i, key->q, key->p, ctx)) { ret = -1; goto err; } if (BN_cmp(i, key->iqmp) != 0) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_IQMP_NOT_INVERSE_OF_Q); } } for (idx = 0; idx < ex_primes; idx++) { pinfo = sk_RSA_PRIME_INFO_value(key->prime_infos, idx); /* d_i = d mod (r_i - 1)? */ if (!BN_sub(i, pinfo->r, BN_value_one())) { ret = -1; goto err; } if (!BN_mod(j, key->d, i, ctx)) { ret = -1; goto err; } if (BN_cmp(j, pinfo->d) != 0) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_MP_EXPONENT_NOT_CONGRUENT_TO_D); } /* t_i = R_i ^ -1 mod r_i ? */ if (!BN_mod_inverse(i, pinfo->pp, pinfo->r, ctx)) { ret = -1; goto err; } if (BN_cmp(i, pinfo->t) != 0) { ret = 0; ERR_raise(ERR_LIB_RSA, RSA_R_MP_COEFFICIENT_NOT_INVERSE_OF_R); } } err: BN_free(i); BN_free(j); BN_free(k); BN_free(l); BN_free(m); BN_CTX_free(ctx); return ret; } #endif /* FIPS_MODULE */ int ossl_rsa_validate_public(const RSA *key) { return ossl_rsa_sp800_56b_check_public(key); } int ossl_rsa_validate_private(const RSA *key) { return ossl_rsa_sp800_56b_check_private(key); } int ossl_rsa_validate_pairwise(const RSA *key) { #ifdef FIPS_MODULE return ossl_rsa_sp800_56b_check_keypair(key, NULL, -1, RSA_bits(key)); #else return rsa_validate_keypair_multiprime(key, NULL) > 0; #endif } int RSA_check_key(const RSA *key) { return RSA_check_key_ex(key, NULL); } int RSA_check_key_ex(const RSA *key, BN_GENCB *cb) { #ifdef FIPS_MODULE return ossl_rsa_validate_public(key) && ossl_rsa_validate_private(key) && ossl_rsa_validate_pairwise(key); #else return rsa_validate_keypair_multiprime(key, cb); #endif /* FIPS_MODULE */ }
7,050
25.01845
80
c
openssl
openssl-master/crypto/rsa/rsa_crpt.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include "crypto/bn.h" #include <openssl/rand.h> #include "rsa_local.h" int RSA_bits(const RSA *r) { return BN_num_bits(r->n); } int RSA_size(const RSA *r) { return BN_num_bytes(r->n); } int RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return rsa->meth->rsa_pub_enc(flen, from, to, rsa, padding); } int RSA_private_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return rsa->meth->rsa_priv_enc(flen, from, to, rsa, padding); } int RSA_private_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return rsa->meth->rsa_priv_dec(flen, from, to, rsa, padding); } int RSA_public_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return rsa->meth->rsa_pub_dec(flen, from, to, rsa, padding); } int RSA_flags(const RSA *r) { return r == NULL ? 0 : r->meth->flags; } void RSA_blinding_off(RSA *rsa) { BN_BLINDING_free(rsa->blinding); rsa->blinding = NULL; rsa->flags &= ~RSA_FLAG_BLINDING; rsa->flags |= RSA_FLAG_NO_BLINDING; } int RSA_blinding_on(RSA *rsa, BN_CTX *ctx) { int ret = 0; if (rsa->blinding != NULL) RSA_blinding_off(rsa); rsa->blinding = RSA_setup_blinding(rsa, ctx); if (rsa->blinding == NULL) goto err; rsa->flags |= RSA_FLAG_BLINDING; rsa->flags &= ~RSA_FLAG_NO_BLINDING; ret = 1; err: return ret; } static BIGNUM *rsa_get_public_exp(const BIGNUM *d, const BIGNUM *p, const BIGNUM *q, BN_CTX *ctx) { BIGNUM *ret = NULL, *r0, *r1, *r2; if (d == NULL || p == NULL || q == NULL) return NULL; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); if (r2 == NULL) goto err; if (!BN_sub(r1, p, BN_value_one())) goto err; if (!BN_sub(r2, q, BN_value_one())) goto err; if (!BN_mul(r0, r1, r2, ctx)) goto err; ret = BN_mod_inverse(NULL, d, r0, ctx); err: BN_CTX_end(ctx); return ret; } BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *in_ctx) { BIGNUM *e; BN_CTX *ctx; BN_BLINDING *ret = NULL; if (in_ctx == NULL) { if ((ctx = BN_CTX_new_ex(rsa->libctx)) == NULL) return 0; } else { ctx = in_ctx; } BN_CTX_start(ctx); e = BN_CTX_get(ctx); if (e == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); goto err; } if (rsa->e == NULL) { e = rsa_get_public_exp(rsa->d, rsa->p, rsa->q, ctx); if (e == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_NO_PUBLIC_EXPONENT); goto err; } } else { e = rsa->e; } { BIGNUM *n = BN_new(); if (n == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); goto err; } BN_with_flags(n, rsa->n, BN_FLG_CONSTTIME); ret = BN_BLINDING_create_param(NULL, e, n, ctx, rsa->meth->bn_mod_exp, rsa->_method_mod_n); /* We MUST free n before any further use of rsa->n */ BN_free(n); } if (ret == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); goto err; } BN_BLINDING_set_current_thread(ret); err: BN_CTX_end(ctx); if (ctx != in_ctx) BN_CTX_free(ctx); if (e != rsa->e) BN_free(e); return ret; }
4,113
22.375
78
c
openssl
openssl-master/crypto/rsa/rsa_depr.c
/* * Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * NB: This file contains deprecated functions (compatibility wrappers to the * "new" versions). */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslconf.h> #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/rsa.h> RSA *RSA_generate_key(int bits, unsigned long e_value, void (*callback) (int, int, void *), void *cb_arg) { int i; BN_GENCB *cb = BN_GENCB_new(); RSA *rsa = RSA_new(); BIGNUM *e = BN_new(); if (cb == NULL || rsa == NULL || e == NULL) goto err; /* * The problem is when building with 8, 16, or 32 BN_ULONG, unsigned long * can be larger */ for (i = 0; i < (int)sizeof(unsigned long) * 8; i++) { if (e_value & (1UL << i)) if (BN_set_bit(e, i) == 0) goto err; } BN_GENCB_set_old(cb, callback, cb_arg); if (RSA_generate_key_ex(rsa, bits, e, cb)) { BN_free(e); BN_GENCB_free(cb); return rsa; } err: BN_free(e); RSA_free(rsa); BN_GENCB_free(cb); return 0; }
1,545
23.539683
77
c
openssl
openssl-master/crypto/rsa/rsa_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/rsaerr.h> #include "crypto/rsaerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA RSA_str_reasons[] = { {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_ALGORITHM_MISMATCH), "algorithm mismatch"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_E_VALUE), "bad e value"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_FIXED_HEADER_DECRYPT), "bad fixed header decrypt"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_PAD_BYTE_COUNT), "bad pad byte count"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_SIGNATURE), "bad signature"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BLOCK_TYPE_IS_NOT_01), "block type is not 01"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BLOCK_TYPE_IS_NOT_02), "block type is not 02"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_GREATER_THAN_MOD_LEN), "data greater than mod len"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_LARGE), "data too large"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE), "data too large for key size"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_LARGE_FOR_MODULUS), "data too large for modulus"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_SMALL), "data too small"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE), "data too small for key size"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DIGEST_DOES_NOT_MATCH), "digest does not match"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DIGEST_NOT_ALLOWED), "digest not allowed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY), "digest too big for rsa key"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DMP1_NOT_CONGRUENT_TO_D), "dmp1 not congruent to d"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DMQ1_NOT_CONGRUENT_TO_D), "dmq1 not congruent to d"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_D_E_NOT_CONGRUENT_TO_1), "d e not congruent to 1"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_FIRST_OCTET_INVALID), "first octet invalid"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE), "illegal or unsupported padding mode"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_DIGEST), "invalid digest"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_DIGEST_LENGTH), "invalid digest length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_HEADER), "invalid header"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_KEYPAIR), "invalid keypair"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_KEY_LENGTH), "invalid key length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_LABEL), "invalid label"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_LENGTH), "invalid length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MESSAGE_LENGTH), "invalid message length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MGF1_MD), "invalid mgf1 md"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MODULUS), "invalid modulus"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MULTI_PRIME_KEY), "invalid multi prime key"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_OAEP_PARAMETERS), "invalid oaep parameters"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PADDING), "invalid padding"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PADDING_MODE), "invalid padding mode"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PSS_PARAMETERS), "invalid pss parameters"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PSS_SALTLEN), "invalid pss saltlen"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_REQUEST), "invalid request"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_SALT_LENGTH), "invalid salt length"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_STRENGTH), "invalid strength"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_TRAILER), "invalid trailer"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_X931_DIGEST), "invalid x931 digest"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_IQMP_NOT_INVERSE_OF_Q), "iqmp not inverse of q"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_KEY_PRIME_NUM_INVALID), "key prime num invalid"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_KEY_SIZE_TOO_SMALL), "key size too small"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_LAST_OCTET_INVALID), "last octet invalid"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MGF1_DIGEST_NOT_ALLOWED), "mgf1 digest not allowed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MISSING_PRIVATE_KEY), "missing private key"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MODULUS_TOO_LARGE), "modulus too large"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MP_COEFFICIENT_NOT_INVERSE_OF_R), "mp coefficient not inverse of r"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MP_EXPONENT_NOT_CONGRUENT_TO_D), "mp exponent not congruent to d"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MP_R_NOT_PRIME), "mp r not prime"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_NO_PUBLIC_EXPONENT), "no public exponent"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_NULL_BEFORE_BLOCK_MISSING), "null before block missing"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_N_DOES_NOT_EQUAL_PRODUCT_OF_PRIMES), "n does not equal product of primes"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_N_DOES_NOT_EQUAL_P_Q), "n does not equal p q"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_OAEP_DECODING_ERROR), "oaep decoding error"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE), "operation not supported for this keytype"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PADDING_CHECK_FAILED), "padding check failed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PAIRWISE_TEST_FAILURE), "pairwise test failure"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PKCS_DECODING_ERROR), "pkcs decoding error"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PSS_SALTLEN_TOO_SMALL), "pss saltlen too small"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PUB_EXPONENT_OUT_OF_RANGE), "pub exponent out of range"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_P_NOT_PRIME), "p not prime"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_Q_NOT_PRIME), "q not prime"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_RANDOMNESS_SOURCE_STRENGTH_INSUFFICIENT), "randomness source strength insufficient"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED), "rsa operations not supported"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_SLEN_CHECK_FAILED), "salt length check failed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_SLEN_RECOVERY_FAILED), "salt length recovery failed"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_SSLV3_ROLLBACK_ATTACK), "sslv3 rollback attack"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD), "the asn1 object identifier is not known for this md"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_ALGORITHM_TYPE), "unknown algorithm type"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_DIGEST), "unknown digest"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_MASK_DIGEST), "unknown mask digest"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_PADDING_TYPE), "unknown padding type"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_ENCRYPTION_TYPE), "unsupported encryption type"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_LABEL_SOURCE), "unsupported label source"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_MASK_ALGORITHM), "unsupported mask algorithm"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_MASK_PARAMETER), "unsupported mask parameter"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_SIGNATURE_TYPE), "unsupported signature type"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_VALUE_MISSING), "value missing"}, {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_WRONG_SIGNATURE_LENGTH), "wrong signature length"}, {0, NULL} }; #endif int ossl_err_load_RSA_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(RSA_str_reasons[0].error) == NULL) ERR_load_strings_const(RSA_str_reasons); #endif return 1; }
8,043
47.167665
89
c
openssl
openssl-master/crypto/rsa/rsa_gen.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * NB: these functions have been "upgraded", the deprecated versions (which * are compatibility wrappers using these functions) are in rsa_depr.c. - * Geoff */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/self_test.h> #include "prov/providercommon.h" #include "rsa_local.h" static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg); static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb, int pairwise_test); /* * NB: this wrapper would normally be placed in rsa_lib.c and the static * implementation would probably be in rsa_eay.c. Nonetheless, is kept here * so that we don't introduce a new linker dependency. Eg. any application * that wasn't previously linking object code related to key-generation won't * have to now just because key-generation is part of RSA_METHOD. */ int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { if (rsa->meth->rsa_keygen != NULL) return rsa->meth->rsa_keygen(rsa, bits, e_value, cb); return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM, e_value, cb); } int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb) { #ifndef FIPS_MODULE /* multi-prime is only supported with the builtin key generation */ if (rsa->meth->rsa_multi_prime_keygen != NULL) { return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes, e_value, cb); } else if (rsa->meth->rsa_keygen != NULL) { /* * However, if rsa->meth implements only rsa_keygen, then we * have to honour it in 2-prime case and assume that it wouldn't * know what to do with multi-prime key generated by builtin * subroutine... */ if (primes == 2) return rsa->meth->rsa_keygen(rsa, bits, e_value, cb); else return 0; } #endif /* FIPS_MODULE */ return rsa_keygen(rsa->libctx, rsa, bits, primes, e_value, cb, 0); } #ifndef FIPS_MODULE static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *prime; int n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0; int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0; RSA_PRIME_INFO *pinfo = NULL; STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL; BN_CTX *ctx = NULL; BN_ULONG bitst = 0; unsigned long error = 0; int ok = -1; if (bits < RSA_MIN_MODULUS_BITS) { ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } if (e_value == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE); return 0; } /* A bad value for e can cause infinite loops */ if (!ossl_rsa_check_public_exponent(e_value)) { ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE); return 0; } if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) { ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID); return 0; } ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); if (r2 == NULL) goto err; /* divide bits into 'primes' pieces evenly */ quo = bits / primes; rmd = bits % primes; for (i = 0; i < primes; i++) bitsr[i] = (i < rmd) ? quo + 1 : quo; rsa->dirty_cnt++; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->d, BN_FLG_CONSTTIME); if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->p, BN_FLG_CONSTTIME); if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->q, BN_FLG_CONSTTIME); if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME); if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME); if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME); /* initialize multi-prime components */ if (primes > RSA_DEFAULT_PRIME_NUM) { rsa->version = RSA_ASN1_VERSION_MULTI; prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2); if (prime_infos == NULL) goto err; if (rsa->prime_infos != NULL) { /* could this happen? */ sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos, ossl_rsa_multip_info_free); } rsa->prime_infos = prime_infos; /* prime_info from 2 to |primes| -1 */ for (i = 2; i < primes; i++) { pinfo = ossl_rsa_multip_info_new(); if (pinfo == NULL) goto err; (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo); } } if (BN_copy(rsa->e, e_value) == NULL) goto err; /* generate p, q and other primes (if any) */ for (i = 0; i < primes; i++) { adj = 0; retries = 0; if (i == 0) { prime = rsa->p; } else if (i == 1) { prime = rsa->q; } else { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); prime = pinfo->r; } BN_set_flags(prime, BN_FLG_CONSTTIME); for (;;) { redo: if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL, cb, ctx)) goto err; /* * prime should not be equal to p, q, r_3... * (those primes prior to this one) */ { int j; for (j = 0; j < i; j++) { BIGNUM *prev_prime; if (j == 0) prev_prime = rsa->p; else if (j == 1) prev_prime = rsa->q; else prev_prime = sk_RSA_PRIME_INFO_value(prime_infos, j - 2)->r; if (!BN_cmp(prime, prev_prime)) { goto redo; } } } if (!BN_sub(r2, prime, BN_value_one())) goto err; ERR_set_mark(); BN_set_flags(r2, BN_FLG_CONSTTIME); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } bitse += bitsr[i]; /* calculate n immediately to see if it's sufficient */ if (i == 1) { /* we get at least 2 primes */ if (!BN_mul(r1, rsa->p, rsa->q, ctx)) goto err; } else if (i != 0) { /* modulus n = p * q * r_3 * r_4 ... */ if (!BN_mul(r1, rsa->n, prime, ctx)) goto err; } else { /* i == 0, do nothing */ if (!BN_GENCB_call(cb, 3, i)) goto err; continue; } /* * if |r1|, product of factors so far, is not as long as expected * (by checking the first 4 bits are less than 0x9 or greater than * 0xF). If so, re-generate the last prime. * * NOTE: This actually can't happen in two-prime case, because of * the way factors are generated. * * Besides, another consideration is, for multi-prime case, even the * length modulus is as long as expected, the modulus could start at * 0x8, which could be utilized to distinguish a multi-prime private * key by using the modulus in a certificate. This is also covered * by checking the length should not be less than 0x9. */ if (!BN_rshift(r2, r1, bitse - 4)) goto err; bitst = BN_get_word(r2); if (bitst < 0x9 || bitst > 0xF) { /* * For keys with more than 4 primes, we attempt longer factor to * meet length requirement. * * Otherwise, we just re-generate the prime with the same length. * * This strategy has the following goals: * * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key * 2. stay the same logic with normal 2-prime key */ bitse -= bitsr[i]; if (!BN_GENCB_call(cb, 2, n++)) goto err; if (primes > 4) { if (bitst < 0x9) adj++; else adj--; } else if (retries == 4) { /* * re-generate all primes from scratch, mainly used * in 4 prime case to avoid long loop. Max retry times * is set to 4. */ i = -1; bitse = 0; continue; } retries++; goto redo; } /* save product of primes for further use, for multi-prime only */ if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL) goto err; if (BN_copy(rsa->n, r1) == NULL) goto err; if (!BN_GENCB_call(cb, 3, i)) goto err; } if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* calculate d */ /* p - 1 */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* q - 1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* (p - 1)(q - 1) */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* multi-prime */ for (i = 2; i < primes; i++) { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); /* save r_i - 1 to pinfo->d temporarily */ if (!BN_sub(pinfo->d, pinfo->r, BN_value_one())) goto err; if (!BN_mul(r0, r0, pinfo->d, ctx)) goto err; } { BIGNUM *pr0 = BN_new(); if (pr0 == NULL) goto err; BN_with_flags(pr0, r0, BN_FLG_CONSTTIME); if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) { BN_free(pr0); goto err; /* d */ } /* We MUST free pr0 before any further use of r0 */ BN_free(pr0); } { BIGNUM *d = BN_new(); if (d == NULL) goto err; BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME); /* calculate d mod (p-1) and d mod (q - 1) */ if (!BN_mod(rsa->dmp1, d, r1, ctx) || !BN_mod(rsa->dmq1, d, r2, ctx)) { BN_free(d); goto err; } /* calculate CRT exponents */ for (i = 2; i < primes; i++) { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); /* pinfo->d == r_i - 1 */ if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) { BN_free(d); goto err; } } /* We MUST free d before any further use of rsa->d */ BN_free(d); } { BIGNUM *p = BN_new(); if (p == NULL) goto err; BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME); /* calculate inverse of q mod p */ if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) { BN_free(p); goto err; } /* calculate CRT coefficient for other primes */ for (i = 2; i < primes; i++) { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME); if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) { BN_free(p); goto err; } } /* We MUST free p before any further use of rsa->p */ BN_free(p); } ok = 1; err: if (ok == -1) { ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); ok = 0; } BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; } #endif /* FIPS_MODULE */ static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb, int pairwise_test) { int ok = 0; #ifdef FIPS_MODULE ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb); pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */ #else /* * Only multi-prime keys or insecure keys with a small key length or a * public exponent <= 2^16 will use the older rsa_multiprime_keygen(). */ if (primes == 2 && bits >= 2048 && (e_value == NULL || BN_num_bits(e_value) > 16)) ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb); else ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb); #endif /* FIPS_MODULE */ if (pairwise_test && ok > 0) { OSSL_CALLBACK *stcb = NULL; void *stcbarg = NULL; OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg); ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg); if (!ok) { ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT); /* Clear intermediate results */ BN_clear_free(rsa->d); BN_clear_free(rsa->p); BN_clear_free(rsa->q); BN_clear_free(rsa->dmp1); BN_clear_free(rsa->dmq1); BN_clear_free(rsa->iqmp); rsa->d = NULL; rsa->p = NULL; rsa->q = NULL; rsa->dmp1 = NULL; rsa->dmq1 = NULL; rsa->iqmp = NULL; } } return ok; } /* * For RSA key generation it is not known whether the key pair will be used * for key transport or signatures. FIPS 140-2 IG 9.9 states that in this case * either a signature verification OR an encryption operation may be used to * perform the pairwise consistency check. The simpler encrypt/decrypt operation * has been chosen for this case. */ static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg) { int ret = 0; unsigned int ciphertxt_len; unsigned char *ciphertxt = NULL; const unsigned char plaintxt[16] = {0}; unsigned char *decoded = NULL; unsigned int decoded_len; unsigned int plaintxt_len = (unsigned int)sizeof(plaintxt_len); int padding = RSA_PKCS1_PADDING; OSSL_SELF_TEST *st = NULL; st = OSSL_SELF_TEST_new(cb, cbarg); if (st == NULL) goto err; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT, OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1); ciphertxt_len = RSA_size(rsa); /* * RSA_private_encrypt() and RSA_private_decrypt() requires the 'to' * parameter to be a maximum of RSA_size() - allocate space for both. */ ciphertxt = OPENSSL_zalloc(ciphertxt_len * 2); if (ciphertxt == NULL) goto err; decoded = ciphertxt + ciphertxt_len; ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa, padding); if (ciphertxt_len <= 0) goto err; if (ciphertxt_len == plaintxt_len && memcmp(ciphertxt, plaintxt, plaintxt_len) == 0) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt); decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa, padding); if (decoded_len != plaintxt_len || memcmp(decoded, plaintxt, decoded_len) != 0) goto err; ret = 1; err: OSSL_SELF_TEST_onend(st, ret); OSSL_SELF_TEST_free(st); OPENSSL_free(ciphertxt); return ret; }
17,017
31.048964
81
c
openssl
openssl-master/crypto/rsa/rsa_local.h
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_RSA_LOCAL_H #define OSSL_CRYPTO_RSA_LOCAL_H #include "internal/refcount.h" #include "crypto/rsa.h" #define RSA_MAX_PRIME_NUM 5 typedef struct rsa_prime_info_st { BIGNUM *r; BIGNUM *d; BIGNUM *t; /* save product of primes prior to this one */ BIGNUM *pp; BN_MONT_CTX *m; } RSA_PRIME_INFO; DECLARE_ASN1_ITEM(RSA_PRIME_INFO) DEFINE_STACK_OF(RSA_PRIME_INFO) #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) struct rsa_acvp_test_st { /* optional inputs */ BIGNUM *Xp1; BIGNUM *Xp2; BIGNUM *Xq1; BIGNUM *Xq2; BIGNUM *Xp; BIGNUM *Xq; /* optional outputs */ BIGNUM *p1; BIGNUM *p2; BIGNUM *q1; BIGNUM *q2; }; #endif struct rsa_st { /* * #legacy * The first field is used to pickup errors where this is passed * instead of an EVP_PKEY. It is always zero. * THIS MUST REMAIN THE FIRST FIELD. */ int dummy_zero; OSSL_LIB_CTX *libctx; int32_t version; const RSA_METHOD *meth; /* functional reference if 'meth' is ENGINE-provided */ ENGINE *engine; BIGNUM *n; BIGNUM *e; BIGNUM *d; BIGNUM *p; BIGNUM *q; BIGNUM *dmp1; BIGNUM *dmq1; BIGNUM *iqmp; /* * If a PSS only key this contains the parameter restrictions. * There are two structures for the same thing, used in different cases. */ /* This is used uniquely by OpenSSL provider implementations. */ RSA_PSS_PARAMS_30 pss_params; #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) RSA_ACVP_TEST *acvp_test; #endif #ifndef FIPS_MODULE /* This is used uniquely by rsa_ameth.c and rsa_pmeth.c. */ RSA_PSS_PARAMS *pss; /* for multi-prime RSA, defined in RFC 8017 */ STACK_OF(RSA_PRIME_INFO) *prime_infos; /* Be careful using this if the RSA structure is shared */ CRYPTO_EX_DATA ex_data; #endif CRYPTO_REF_COUNT references; int flags; /* Used to cache montgomery values */ BN_MONT_CTX *_method_mod_n; BN_MONT_CTX *_method_mod_p; BN_MONT_CTX *_method_mod_q; BN_BLINDING *blinding; BN_BLINDING *mt_blinding; CRYPTO_RWLOCK *lock; int dirty_cnt; }; struct rsa_meth_st { char *name; int (*rsa_pub_enc) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); int (*rsa_pub_dec) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); int (*rsa_priv_enc) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); int (*rsa_priv_dec) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); /* Can be null */ int (*rsa_mod_exp) (BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); /* Can be null */ int (*bn_mod_exp) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); /* called at new */ int (*init) (RSA *rsa); /* called at free */ int (*finish) (RSA *rsa); /* RSA_METHOD_FLAG_* things */ int flags; /* may be needed! */ char *app_data; /* * New sign and verify functions: some libraries don't allow arbitrary * data to be signed/verified: this allows them to be used. Note: for * this to work the RSA_public_decrypt() and RSA_private_encrypt() should * *NOT* be used. RSA_sign(), RSA_verify() should be used instead. */ int (*rsa_sign) (int type, const unsigned char *m, unsigned int m_length, unsigned char *sigret, unsigned int *siglen, const RSA *rsa); int (*rsa_verify) (int dtype, const unsigned char *m, unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa); /* * If this callback is NULL, the builtin software RSA key-gen will be * used. This is for behavioural compatibility whilst the code gets * rewired, but one day it would be nice to assume there are no such * things as "builtin software" implementations. */ int (*rsa_keygen) (RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); int (*rsa_multi_prime_keygen) (RSA *rsa, int bits, int primes, BIGNUM *e, BN_GENCB *cb); }; /* Macros to test if a pkey or ctx is for a PSS key */ #define pkey_is_pss(pkey) (pkey->ameth->pkey_id == EVP_PKEY_RSA_PSS) #define pkey_ctx_is_pss(ctx) (ctx->pmeth->pkey_id == EVP_PKEY_RSA_PSS) RSA_PSS_PARAMS *ossl_rsa_pss_params_create(const EVP_MD *sigmd, const EVP_MD *mgf1md, int saltlen); int ossl_rsa_pss_get_param(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd, const EVP_MD **pmgf1md, int *psaltlen); /* internal function to clear and free multi-prime parameters */ void ossl_rsa_multip_info_free_ex(RSA_PRIME_INFO *pinfo); void ossl_rsa_multip_info_free(RSA_PRIME_INFO *pinfo); RSA_PRIME_INFO *ossl_rsa_multip_info_new(void); int ossl_rsa_multip_calc_product(RSA *rsa); int ossl_rsa_multip_cap(int bits); int ossl_rsa_sp800_56b_validate_strength(int nbits, int strength); int ossl_rsa_check_pminusq_diff(BIGNUM *diff, const BIGNUM *p, const BIGNUM *q, int nbits); int ossl_rsa_get_lcm(BN_CTX *ctx, const BIGNUM *p, const BIGNUM *q, BIGNUM *lcm, BIGNUM *gcd, BIGNUM *p1, BIGNUM *q1, BIGNUM *p1q1); int ossl_rsa_check_public_exponent(const BIGNUM *e); int ossl_rsa_check_private_exponent(const RSA *rsa, int nbits, BN_CTX *ctx); int ossl_rsa_check_prime_factor(BIGNUM *p, BIGNUM *e, int nbits, BN_CTX *ctx); int ossl_rsa_check_prime_factor_range(const BIGNUM *p, int nbits, BN_CTX *ctx); int ossl_rsa_check_crt_components(const RSA *rsa, BN_CTX *ctx); int ossl_rsa_sp800_56b_pairwise_test(RSA *rsa, BN_CTX *ctx); int ossl_rsa_sp800_56b_check_public(const RSA *rsa); int ossl_rsa_sp800_56b_check_private(const RSA *rsa); int ossl_rsa_sp800_56b_check_keypair(const RSA *rsa, const BIGNUM *efixed, int strength, int nbits); int ossl_rsa_sp800_56b_generate_key(RSA *rsa, int nbits, const BIGNUM *efixed, BN_GENCB *cb); int ossl_rsa_sp800_56b_derive_params_from_pq(RSA *rsa, int nbits, const BIGNUM *e, BN_CTX *ctx); int ossl_rsa_fips186_4_gen_prob_primes(RSA *rsa, RSA_ACVP_TEST *test, int nbits, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb); int ossl_rsa_padding_add_PKCS1_type_2_ex(OSSL_LIB_CTX *libctx, unsigned char *to, int tlen, const unsigned char *from, int flen); #endif /* OSSL_CRYPTO_RSA_LOCAL_H */
7,285
35.984772
81
h
openssl
openssl-master/crypto/rsa/rsa_meth.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include "rsa_local.h" #include <openssl/err.h> RSA_METHOD *RSA_meth_new(const char *name, int flags) { RSA_METHOD *meth = OPENSSL_zalloc(sizeof(*meth)); if (meth != NULL) { meth->flags = flags; meth->name = OPENSSL_strdup(name); if (meth->name != NULL) return meth; OPENSSL_free(meth); } return NULL; } void RSA_meth_free(RSA_METHOD *meth) { if (meth != NULL) { OPENSSL_free(meth->name); OPENSSL_free(meth); } } RSA_METHOD *RSA_meth_dup(const RSA_METHOD *meth) { RSA_METHOD *ret = OPENSSL_malloc(sizeof(*ret)); if (ret != NULL) { memcpy(ret, meth, sizeof(*meth)); ret->name = OPENSSL_strdup(meth->name); if (ret->name != NULL) return ret; OPENSSL_free(ret); } return NULL; } const char *RSA_meth_get0_name(const RSA_METHOD *meth) { return meth->name; } int RSA_meth_set1_name(RSA_METHOD *meth, const char *name) { char *tmpname = OPENSSL_strdup(name); if (tmpname == NULL) return 0; OPENSSL_free(meth->name); meth->name = tmpname; return 1; } int RSA_meth_get_flags(const RSA_METHOD *meth) { return meth->flags; } int RSA_meth_set_flags(RSA_METHOD *meth, int flags) { meth->flags = flags; return 1; } void *RSA_meth_get0_app_data(const RSA_METHOD *meth) { return meth->app_data; } int RSA_meth_set0_app_data(RSA_METHOD *meth, void *app_data) { meth->app_data = app_data; return 1; } int (*RSA_meth_get_pub_enc(const RSA_METHOD *meth)) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return meth->rsa_pub_enc; } int RSA_meth_set_pub_enc(RSA_METHOD *meth, int (*pub_enc) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)) { meth->rsa_pub_enc = pub_enc; return 1; } int (*RSA_meth_get_pub_dec(const RSA_METHOD *meth)) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return meth->rsa_pub_dec; } int RSA_meth_set_pub_dec(RSA_METHOD *meth, int (*pub_dec) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)) { meth->rsa_pub_dec = pub_dec; return 1; } int (*RSA_meth_get_priv_enc(const RSA_METHOD *meth)) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return meth->rsa_priv_enc; } int RSA_meth_set_priv_enc(RSA_METHOD *meth, int (*priv_enc) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)) { meth->rsa_priv_enc = priv_enc; return 1; } int (*RSA_meth_get_priv_dec(const RSA_METHOD *meth)) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { return meth->rsa_priv_dec; } int RSA_meth_set_priv_dec(RSA_METHOD *meth, int (*priv_dec) (int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)) { meth->rsa_priv_dec = priv_dec; return 1; } /* Can be null */ int (*RSA_meth_get_mod_exp(const RSA_METHOD *meth)) (BIGNUM *r0, const BIGNUM *i, RSA *rsa, BN_CTX *ctx) { return meth->rsa_mod_exp; } int RSA_meth_set_mod_exp(RSA_METHOD *meth, int (*mod_exp) (BIGNUM *r0, const BIGNUM *i, RSA *rsa, BN_CTX *ctx)) { meth->rsa_mod_exp = mod_exp; return 1; } /* Can be null */ int (*RSA_meth_get_bn_mod_exp(const RSA_METHOD *meth)) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { return meth->bn_mod_exp; } int RSA_meth_set_bn_mod_exp(RSA_METHOD *meth, int (*bn_mod_exp) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)) { meth->bn_mod_exp = bn_mod_exp; return 1; } /* called at new */ int (*RSA_meth_get_init(const RSA_METHOD *meth)) (RSA *rsa) { return meth->init; } int RSA_meth_set_init(RSA_METHOD *meth, int (*init) (RSA *rsa)) { meth->init = init; return 1; } /* called at free */ int (*RSA_meth_get_finish(const RSA_METHOD *meth)) (RSA *rsa) { return meth->finish; } int RSA_meth_set_finish(RSA_METHOD *meth, int (*finish) (RSA *rsa)) { meth->finish = finish; return 1; } int (*RSA_meth_get_sign(const RSA_METHOD *meth)) (int type, const unsigned char *m, unsigned int m_length, unsigned char *sigret, unsigned int *siglen, const RSA *rsa) { return meth->rsa_sign; } int RSA_meth_set_sign(RSA_METHOD *meth, int (*sign) (int type, const unsigned char *m, unsigned int m_length, unsigned char *sigret, unsigned int *siglen, const RSA *rsa)) { meth->rsa_sign = sign; return 1; } int (*RSA_meth_get_verify(const RSA_METHOD *meth)) (int dtype, const unsigned char *m, unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa) { return meth->rsa_verify; } int RSA_meth_set_verify(RSA_METHOD *meth, int (*verify) (int dtype, const unsigned char *m, unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa)) { meth->rsa_verify = verify; return 1; } int (*RSA_meth_get_keygen(const RSA_METHOD *meth)) (RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb) { return meth->rsa_keygen; } int RSA_meth_set_keygen(RSA_METHOD *meth, int (*keygen) (RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)) { meth->rsa_keygen = keygen; return 1; } int (*RSA_meth_get_multi_prime_keygen(const RSA_METHOD *meth)) (RSA *rsa, int bits, int primes, BIGNUM *e, BN_GENCB *cb) { return meth->rsa_multi_prime_keygen; } int RSA_meth_set_multi_prime_keygen(RSA_METHOD *meth, int (*keygen) (RSA *rsa, int bits, int primes, BIGNUM *e, BN_GENCB *cb)) { meth->rsa_multi_prime_keygen = keygen; return 1; }
7,456
24.713793
79
c
openssl
openssl-master/crypto/rsa/rsa_mp.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 BaishanCloud. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/bn.h> #include <openssl/err.h> #include "rsa_local.h" void ossl_rsa_multip_info_free_ex(RSA_PRIME_INFO *pinfo) { /* free pp and pinfo only */ BN_clear_free(pinfo->pp); OPENSSL_free(pinfo); } void ossl_rsa_multip_info_free(RSA_PRIME_INFO *pinfo) { /* free an RSA_PRIME_INFO structure */ BN_clear_free(pinfo->r); BN_clear_free(pinfo->d); BN_clear_free(pinfo->t); ossl_rsa_multip_info_free_ex(pinfo); } RSA_PRIME_INFO *ossl_rsa_multip_info_new(void) { RSA_PRIME_INFO *pinfo; /* create an RSA_PRIME_INFO structure */ if ((pinfo = OPENSSL_zalloc(sizeof(RSA_PRIME_INFO))) == NULL) return NULL; if ((pinfo->r = BN_secure_new()) == NULL) goto err; if ((pinfo->d = BN_secure_new()) == NULL) goto err; if ((pinfo->t = BN_secure_new()) == NULL) goto err; if ((pinfo->pp = BN_secure_new()) == NULL) goto err; return pinfo; err: BN_free(pinfo->r); BN_free(pinfo->d); BN_free(pinfo->t); BN_free(pinfo->pp); OPENSSL_free(pinfo); return NULL; } /* Refill products of primes */ int ossl_rsa_multip_calc_product(RSA *rsa) { RSA_PRIME_INFO *pinfo; BIGNUM *p1 = NULL, *p2 = NULL; BN_CTX *ctx = NULL; int i, rv = 0, ex_primes; if ((ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos)) <= 0) { /* invalid */ goto err; } if ((ctx = BN_CTX_new()) == NULL) goto err; /* calculate pinfo->pp = p * q for first 'extra' prime */ p1 = rsa->p; p2 = rsa->q; for (i = 0; i < ex_primes; i++) { pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); if (pinfo->pp == NULL) { pinfo->pp = BN_secure_new(); if (pinfo->pp == NULL) goto err; } if (!BN_mul(pinfo->pp, p1, p2, ctx)) goto err; /* save previous one */ p1 = pinfo->pp; p2 = pinfo->r; } rv = 1; err: BN_CTX_free(ctx); return rv; } int ossl_rsa_multip_cap(int bits) { int cap = 5; if (bits < 1024) cap = 2; else if (bits < 4096) cap = 3; else if (bits < 8192) cap = 4; if (cap > RSA_MAX_PRIME_NUM) cap = RSA_MAX_PRIME_NUM; return cap; }
2,658
22.324561
74
c
openssl
openssl-master/crypto/rsa/rsa_mp_names.c
/* * Copyright 2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core_names.h> #include "crypto/rsa.h" /* * The following tables are constants used during RSA parameter building * operations. It is easier to point to one of these fixed strings than have * to dynamically add and generate the names on the fly. */ /* * A fixed table of names for the RSA prime factors starting with * P,Q and up to 8 additional primes. */ const char *ossl_rsa_mp_factor_names[] = { OSSL_PKEY_PARAM_RSA_FACTOR1, OSSL_PKEY_PARAM_RSA_FACTOR2, #ifndef FIPS_MODULE OSSL_PKEY_PARAM_RSA_FACTOR3, OSSL_PKEY_PARAM_RSA_FACTOR4, OSSL_PKEY_PARAM_RSA_FACTOR5, OSSL_PKEY_PARAM_RSA_FACTOR6, OSSL_PKEY_PARAM_RSA_FACTOR7, OSSL_PKEY_PARAM_RSA_FACTOR8, OSSL_PKEY_PARAM_RSA_FACTOR9, OSSL_PKEY_PARAM_RSA_FACTOR10, #endif NULL }; /* * A fixed table of names for the RSA exponents starting with * DP,DQ and up to 8 additional exponents. */ const char *ossl_rsa_mp_exp_names[] = { OSSL_PKEY_PARAM_RSA_EXPONENT1, OSSL_PKEY_PARAM_RSA_EXPONENT2, #ifndef FIPS_MODULE OSSL_PKEY_PARAM_RSA_EXPONENT3, OSSL_PKEY_PARAM_RSA_EXPONENT4, OSSL_PKEY_PARAM_RSA_EXPONENT5, OSSL_PKEY_PARAM_RSA_EXPONENT6, OSSL_PKEY_PARAM_RSA_EXPONENT7, OSSL_PKEY_PARAM_RSA_EXPONENT8, OSSL_PKEY_PARAM_RSA_EXPONENT9, OSSL_PKEY_PARAM_RSA_EXPONENT10, #endif NULL }; /* * A fixed table of names for the RSA coefficients starting with * QINV and up to 8 additional exponents. */ const char *ossl_rsa_mp_coeff_names[] = { OSSL_PKEY_PARAM_RSA_COEFFICIENT1, #ifndef FIPS_MODULE OSSL_PKEY_PARAM_RSA_COEFFICIENT2, OSSL_PKEY_PARAM_RSA_COEFFICIENT3, OSSL_PKEY_PARAM_RSA_COEFFICIENT4, OSSL_PKEY_PARAM_RSA_COEFFICIENT5, OSSL_PKEY_PARAM_RSA_COEFFICIENT6, OSSL_PKEY_PARAM_RSA_COEFFICIENT7, OSSL_PKEY_PARAM_RSA_COEFFICIENT8, OSSL_PKEY_PARAM_RSA_COEFFICIENT9, #endif NULL };
2,209
27.701299
76
c
openssl
openssl-master/crypto/rsa/rsa_none.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/rsa.h> int RSA_padding_add_none(unsigned char *to, int tlen, const unsigned char *from, int flen) { if (flen > tlen) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return 0; } if (flen < tlen) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE); return 0; } memcpy(to, from, (unsigned int)flen); return 1; } int RSA_padding_check_none(unsigned char *to, int tlen, const unsigned char *from, int flen, int num) { if (flen > tlen) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE); return -1; } memset(to, 0, tlen - flen); memcpy(to + tlen - flen, from, flen); return tlen; }
1,281
24.64
74
c
openssl
openssl-master/crypto/rsa/rsa_oaep.c
/* * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* EME-OAEP as defined in RFC 2437 (PKCS #1 v2.0) */ /* * See Victor Shoup, "OAEP reconsidered," Nov. 2000, <URL: * http://www.shoup.net/papers/oaep.ps.Z> for problems with the security * proof for the original OAEP scheme, which EME-OAEP is based on. A new * proof can be found in E. Fujisaki, T. Okamoto, D. Pointcheval, J. Stern, * "RSA-OEAP is Still Alive!", Dec. 2000, <URL: * http://eprint.iacr.org/2000/061/>. The new proof has stronger requirements * for the underlying permutation: "partial-one-wayness" instead of * one-wayness. For the RSA function, this is an equivalent notion. */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "internal/constant_time.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/sha.h> #include "rsa_local.h" int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen, const unsigned char *from, int flen, const unsigned char *param, int plen) { return ossl_rsa_padding_add_PKCS1_OAEP_mgf1_ex(NULL, to, tlen, from, flen, param, plen, NULL, NULL); } /* * Perform the padding as per NIST 800-56B 7.2.2.3 * from (K) is the key material. * param (A) is the additional input. * Step numbers are included here but not in the constant time inverse below * to avoid complicating an already difficult enough function. */ int ossl_rsa_padding_add_PKCS1_OAEP_mgf1_ex(OSSL_LIB_CTX *libctx, unsigned char *to, int tlen, const unsigned char *from, int flen, const unsigned char *param, int plen, const EVP_MD *md, const EVP_MD *mgf1md) { int rv = 0; int i, emlen = tlen - 1; unsigned char *db, *seed; unsigned char *dbmask = NULL; unsigned char seedmask[EVP_MAX_MD_SIZE]; int mdlen, dbmask_len = 0; if (md == NULL) { #ifndef FIPS_MODULE md = EVP_sha1(); #else ERR_raise(ERR_LIB_RSA, ERR_R_PASSED_NULL_PARAMETER); return 0; #endif } if (mgf1md == NULL) mgf1md = md; mdlen = EVP_MD_get_size(md); if (mdlen <= 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_LENGTH); return 0; } /* step 2b: check KLen > nLen - 2 HLen - 2 */ if (flen > emlen - 2 * mdlen - 1) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return 0; } if (emlen < 2 * mdlen + 1) { ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } /* step 3i: EM = 00000000 || maskedMGF || maskedDB */ to[0] = 0; seed = to + 1; db = to + mdlen + 1; /* step 3a: hash the additional input */ if (!EVP_Digest((void *)param, plen, db, NULL, md, NULL)) goto err; /* step 3b: zero bytes array of length nLen - KLen - 2 HLen -2 */ memset(db + mdlen, 0, emlen - flen - 2 * mdlen - 1); /* step 3c: DB = HA || PS || 00000001 || K */ db[emlen - flen - mdlen - 1] = 0x01; memcpy(db + emlen - flen - mdlen, from, (unsigned int)flen); /* step 3d: generate random byte string */ if (RAND_bytes_ex(libctx, seed, mdlen, 0) <= 0) goto err; dbmask_len = emlen - mdlen; dbmask = OPENSSL_malloc(dbmask_len); if (dbmask == NULL) goto err; /* step 3e: dbMask = MGF(mgfSeed, nLen - HLen - 1) */ if (PKCS1_MGF1(dbmask, dbmask_len, seed, mdlen, mgf1md) < 0) goto err; /* step 3f: maskedDB = DB XOR dbMask */ for (i = 0; i < dbmask_len; i++) db[i] ^= dbmask[i]; /* step 3g: mgfSeed = MGF(maskedDB, HLen) */ if (PKCS1_MGF1(seedmask, mdlen, db, dbmask_len, mgf1md) < 0) goto err; /* stepo 3h: maskedMGFSeed = mgfSeed XOR mgfSeedMask */ for (i = 0; i < mdlen; i++) seed[i] ^= seedmask[i]; rv = 1; err: OPENSSL_cleanse(seedmask, sizeof(seedmask)); OPENSSL_clear_free(dbmask, dbmask_len); return rv; } int RSA_padding_add_PKCS1_OAEP_mgf1(unsigned char *to, int tlen, const unsigned char *from, int flen, const unsigned char *param, int plen, const EVP_MD *md, const EVP_MD *mgf1md) { return ossl_rsa_padding_add_PKCS1_OAEP_mgf1_ex(NULL, to, tlen, from, flen, param, plen, md, mgf1md); } int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen, const unsigned char *from, int flen, int num, const unsigned char *param, int plen) { return RSA_padding_check_PKCS1_OAEP_mgf1(to, tlen, from, flen, num, param, plen, NULL, NULL); } int RSA_padding_check_PKCS1_OAEP_mgf1(unsigned char *to, int tlen, const unsigned char *from, int flen, int num, const unsigned char *param, int plen, const EVP_MD *md, const EVP_MD *mgf1md) { int i, dblen = 0, mlen = -1, one_index = 0, msg_index; unsigned int good = 0, found_one_byte, mask; const unsigned char *maskedseed, *maskeddb; /* * |em| is the encoded message, zero-padded to exactly |num| bytes: em = * Y || maskedSeed || maskedDB */ unsigned char *db = NULL, *em = NULL, seed[EVP_MAX_MD_SIZE], phash[EVP_MAX_MD_SIZE]; int mdlen; if (md == NULL) { #ifndef FIPS_MODULE md = EVP_sha1(); #else ERR_raise(ERR_LIB_RSA, ERR_R_PASSED_NULL_PARAMETER); return -1; #endif } if (mgf1md == NULL) mgf1md = md; mdlen = EVP_MD_get_size(md); if (tlen <= 0 || flen <= 0) return -1; /* * |num| is the length of the modulus; |flen| is the length of the * encoded message. Therefore, for any |from| that was obtained by * decrypting a ciphertext, we must have |flen| <= |num|. Similarly, * |num| >= 2 * |mdlen| + 2 must hold for the modulus irrespective of * the ciphertext, see PKCS #1 v2.2, section 7.1.2. * This does not leak any side-channel information. */ if (num < flen || num < 2 * mdlen + 2) { ERR_raise(ERR_LIB_RSA, RSA_R_OAEP_DECODING_ERROR); return -1; } dblen = num - mdlen - 1; db = OPENSSL_malloc(dblen); if (db == NULL) goto cleanup; em = OPENSSL_malloc(num); if (em == NULL) goto cleanup; /* * Caller is encouraged to pass zero-padded message created with * BN_bn2binpad. Trouble is that since we can't read out of |from|'s * bounds, it's impossible to have an invariant memory access pattern * in case |from| was not zero-padded in advance. */ for (from += flen, em += num, i = 0; i < num; i++) { mask = ~constant_time_is_zero(flen); flen -= 1 & mask; from -= 1 & mask; *--em = *from & mask; } /* * The first byte must be zero, however we must not leak if this is * true. See James H. Manger, "A Chosen Ciphertext Attack on RSA * Optimal Asymmetric Encryption Padding (OAEP) [...]", CRYPTO 2001). */ good = constant_time_is_zero(em[0]); maskedseed = em + 1; maskeddb = em + 1 + mdlen; if (PKCS1_MGF1(seed, mdlen, maskeddb, dblen, mgf1md)) goto cleanup; for (i = 0; i < mdlen; i++) seed[i] ^= maskedseed[i]; if (PKCS1_MGF1(db, dblen, seed, mdlen, mgf1md)) goto cleanup; for (i = 0; i < dblen; i++) db[i] ^= maskeddb[i]; if (!EVP_Digest((void *)param, plen, phash, NULL, md, NULL)) goto cleanup; good &= constant_time_is_zero(CRYPTO_memcmp(db, phash, mdlen)); found_one_byte = 0; for (i = mdlen; i < dblen; i++) { /* * Padding consists of a number of 0-bytes, followed by a 1. */ unsigned int equals1 = constant_time_eq(db[i], 1); unsigned int equals0 = constant_time_is_zero(db[i]); one_index = constant_time_select_int(~found_one_byte & equals1, i, one_index); found_one_byte |= equals1; good &= (found_one_byte | equals0); } good &= found_one_byte; /* * At this point |good| is zero unless the plaintext was valid, * so plaintext-awareness ensures timing side-channels are no longer a * concern. */ msg_index = one_index + 1; mlen = dblen - msg_index; /* * For good measure, do this check in constant time as well. */ good &= constant_time_ge(tlen, mlen); /* * Move the result in-place by |dblen|-|mdlen|-1-|mlen| bytes to the left. * Then if |good| move |mlen| bytes from |db|+|mdlen|+1 to |to|. * Otherwise leave |to| unchanged. * Copy the memory back in a way that does not reveal the size of * the data being copied via a timing side channel. This requires copying * parts of the buffer multiple times based on the bits set in the real * length. Clear bits do a non-copy with identical access pattern. * The loop below has overall complexity of O(N*log(N)). */ tlen = constant_time_select_int(constant_time_lt(dblen - mdlen - 1, tlen), dblen - mdlen - 1, tlen); for (msg_index = 1; msg_index < dblen - mdlen - 1; msg_index <<= 1) { mask = ~constant_time_eq(msg_index & (dblen - mdlen - 1 - mlen), 0); for (i = mdlen + 1; i < dblen - msg_index; i++) db[i] = constant_time_select_8(mask, db[i + msg_index], db[i]); } for (i = 0; i < tlen; i++) { mask = good & constant_time_lt(i, mlen); to[i] = constant_time_select_8(mask, db[i + mdlen + 1], to[i]); } #ifndef FIPS_MODULE /* * To avoid chosen ciphertext attacks, the error message should not * reveal which kind of decoding error happened. * * This trick doesn't work in the FIPS provider because libcrypto manages * the error stack. Instead we opt not to put an error on the stack at all * in case of padding failure in the FIPS provider. */ ERR_raise(ERR_LIB_RSA, RSA_R_OAEP_DECODING_ERROR); err_clear_last_constant_time(1 & good); #endif cleanup: OPENSSL_cleanse(seed, sizeof(seed)); OPENSSL_clear_free(db, dblen); OPENSSL_clear_free(em, num); return constant_time_select_int(good, mlen, -1); } /* * Mask Generation Function corresponding to section 7.2.2.2 of NIST SP 800-56B. * The variables are named differently to NIST: * mask (T) and len (maskLen)are the returned mask. * seed (mgfSeed). * The range checking steps inm the process are performed outside. */ int PKCS1_MGF1(unsigned char *mask, long len, const unsigned char *seed, long seedlen, const EVP_MD *dgst) { long i, outlen = 0; unsigned char cnt[4]; EVP_MD_CTX *c = EVP_MD_CTX_new(); unsigned char md[EVP_MAX_MD_SIZE]; int mdlen; int rv = -1; if (c == NULL) goto err; mdlen = EVP_MD_get_size(dgst); if (mdlen < 0) goto err; /* step 4 */ for (i = 0; outlen < len; i++) { /* step 4a: D = I2BS(counter, 4) */ cnt[0] = (unsigned char)((i >> 24) & 255); cnt[1] = (unsigned char)((i >> 16) & 255); cnt[2] = (unsigned char)((i >> 8)) & 255; cnt[3] = (unsigned char)(i & 255); /* step 4b: T =T || hash(mgfSeed || D) */ if (!EVP_DigestInit_ex(c, dgst, NULL) || !EVP_DigestUpdate(c, seed, seedlen) || !EVP_DigestUpdate(c, cnt, 4)) goto err; if (outlen + mdlen <= len) { if (!EVP_DigestFinal_ex(c, mask + outlen, NULL)) goto err; outlen += mdlen; } else { if (!EVP_DigestFinal_ex(c, md, NULL)) goto err; memcpy(mask + outlen, md, len - outlen); outlen = len; } } rv = 0; err: OPENSSL_cleanse(md, sizeof(md)); EVP_MD_CTX_free(c); return rv; }
12,707
33.345946
80
c
openssl
openssl-master/crypto/rsa/rsa_pk1.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "internal/constant_time.h" #include <stdio.h> #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/rand.h> /* Just for the SSL_MAX_MASTER_KEY_LENGTH value */ #include <openssl/prov_ssl.h> #include <openssl/evp.h> #include <openssl/sha.h> #include <openssl/hmac.h> #include "internal/cryptlib.h" #include "crypto/rsa.h" #include "rsa_local.h" int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen, const unsigned char *from, int flen) { int j; unsigned char *p; if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return 0; } p = (unsigned char *)to; *(p++) = 0; *(p++) = 1; /* Private Key BT (Block Type) */ /* pad out with 0xff data */ j = tlen - 3 - flen; memset(p, 0xff, j); p += j; *(p++) = '\0'; memcpy(p, from, (unsigned int)flen); return 1; } int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, const unsigned char *from, int flen, int num) { int i, j; const unsigned char *p; p = from; /* * The format is * 00 || 01 || PS || 00 || D * PS - padding string, at least 8 bytes of FF * D - data. */ if (num < RSA_PKCS1_PADDING_SIZE) return -1; /* Accept inputs with and without the leading 0-byte. */ if (num == flen) { if ((*p++) != 0x00) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING); return -1; } flen--; } if ((num != (flen + 1)) || (*(p++) != 0x01)) { ERR_raise(ERR_LIB_RSA, RSA_R_BLOCK_TYPE_IS_NOT_01); return -1; } /* scan over padding data */ j = flen - 1; /* one for type. */ for (i = 0; i < j; i++) { if (*p != 0xff) { /* should decrypt to 0xff */ if (*p == 0) { p++; break; } else { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_FIXED_HEADER_DECRYPT); return -1; } } p++; } if (i == j) { ERR_raise(ERR_LIB_RSA, RSA_R_NULL_BEFORE_BLOCK_MISSING); return -1; } if (i < 8) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_PAD_BYTE_COUNT); return -1; } i++; /* Skip over the '\0' */ j -= i; if (j > tlen) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE); return -1; } memcpy(to, p, (unsigned int)j); return j; } int ossl_rsa_padding_add_PKCS1_type_2_ex(OSSL_LIB_CTX *libctx, unsigned char *to, int tlen, const unsigned char *from, int flen) { int i, j; unsigned char *p; if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return 0; } else if (flen < 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_LENGTH); return 0; } p = (unsigned char *)to; *(p++) = 0; *(p++) = 2; /* Public Key BT (Block Type) */ /* pad out with non-zero random data */ j = tlen - 3 - flen; if (RAND_bytes_ex(libctx, p, j, 0) <= 0) return 0; for (i = 0; i < j; i++) { if (*p == '\0') do { if (RAND_bytes_ex(libctx, p, 1, 0) <= 0) return 0; } while (*p == '\0'); p++; } *(p++) = '\0'; memcpy(p, from, (unsigned int)flen); return 1; } int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, const unsigned char *from, int flen) { return ossl_rsa_padding_add_PKCS1_type_2_ex(NULL, to, tlen, from, flen); } int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen, const unsigned char *from, int flen, int num) { int i; /* |em| is the encoded message, zero-padded to exactly |num| bytes */ unsigned char *em = NULL; unsigned int good, found_zero_byte, mask; int zero_index = 0, msg_index, mlen = -1; if (tlen <= 0 || flen <= 0) return -1; /* * PKCS#1 v1.5 decryption. See "PKCS #1 v2.2: RSA Cryptography Standard", * section 7.2.2. */ if (flen > num || num < RSA_PKCS1_PADDING_SIZE) { ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR); return -1; } em = OPENSSL_malloc(num); if (em == NULL) return -1; /* * Caller is encouraged to pass zero-padded message created with * BN_bn2binpad. Trouble is that since we can't read out of |from|'s * bounds, it's impossible to have an invariant memory access pattern * in case |from| was not zero-padded in advance. */ for (from += flen, em += num, i = 0; i < num; i++) { mask = ~constant_time_is_zero(flen); flen -= 1 & mask; from -= 1 & mask; *--em = *from & mask; } good = constant_time_is_zero(em[0]); good &= constant_time_eq(em[1], 2); /* scan over padding data */ found_zero_byte = 0; for (i = 2; i < num; i++) { unsigned int equals0 = constant_time_is_zero(em[i]); zero_index = constant_time_select_int(~found_zero_byte & equals0, i, zero_index); found_zero_byte |= equals0; } /* * PS must be at least 8 bytes long, and it starts two bytes into |em|. * If we never found a 0-byte, then |zero_index| is 0 and the check * also fails. */ good &= constant_time_ge(zero_index, 2 + 8); /* * Skip the zero byte. This is incorrect if we never found a zero-byte * but in this case we also do not copy the message out. */ msg_index = zero_index + 1; mlen = num - msg_index; /* * For good measure, do this check in constant time as well. */ good &= constant_time_ge(tlen, mlen); /* * Move the result in-place by |num|-RSA_PKCS1_PADDING_SIZE-|mlen| bytes to the left. * Then if |good| move |mlen| bytes from |em|+RSA_PKCS1_PADDING_SIZE to |to|. * Otherwise leave |to| unchanged. * Copy the memory back in a way that does not reveal the size of * the data being copied via a timing side channel. This requires copying * parts of the buffer multiple times based on the bits set in the real * length. Clear bits do a non-copy with identical access pattern. * The loop below has overall complexity of O(N*log(N)). */ tlen = constant_time_select_int(constant_time_lt(num - RSA_PKCS1_PADDING_SIZE, tlen), num - RSA_PKCS1_PADDING_SIZE, tlen); for (msg_index = 1; msg_index < num - RSA_PKCS1_PADDING_SIZE; msg_index <<= 1) { mask = ~constant_time_eq(msg_index & (num - RSA_PKCS1_PADDING_SIZE - mlen), 0); for (i = RSA_PKCS1_PADDING_SIZE; i < num - msg_index; i++) em[i] = constant_time_select_8(mask, em[i + msg_index], em[i]); } for (i = 0; i < tlen; i++) { mask = good & constant_time_lt(i, mlen); to[i] = constant_time_select_8(mask, em[i + RSA_PKCS1_PADDING_SIZE], to[i]); } OPENSSL_clear_free(em, num); #ifndef FIPS_MODULE /* * This trick doesn't work in the FIPS provider because libcrypto manages * the error stack. Instead we opt not to put an error on the stack at all * in case of padding failure in the FIPS provider. */ ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR); err_clear_last_constant_time(1 & good); #endif return constant_time_select_int(good, mlen, -1); } static int ossl_rsa_prf(OSSL_LIB_CTX *ctx, unsigned char *to, int tlen, const char *label, int llen, const unsigned char *kdk, uint16_t bitlen) { int pos; int ret = -1; uint16_t iter = 0; unsigned char be_iter[sizeof(iter)]; unsigned char be_bitlen[sizeof(bitlen)]; HMAC_CTX *hmac = NULL; EVP_MD *md = NULL; unsigned char hmac_out[SHA256_DIGEST_LENGTH]; unsigned int md_len; if (tlen * 8 != bitlen) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); return ret; } be_bitlen[0] = (bitlen >> 8) & 0xff; be_bitlen[1] = bitlen & 0xff; hmac = HMAC_CTX_new(); if (hmac == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } /* * we use hardcoded hash so that migrating between versions that use * different hash doesn't provide a Bleichenbacher oracle: * if the attacker can see that different versions return different * messages for the same ciphertext, they'll know that the message is * synthetically generated, which means that the padding check failed */ md = EVP_MD_fetch(ctx, "sha256", NULL); if (md == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } if (HMAC_Init_ex(hmac, kdk, SHA256_DIGEST_LENGTH, md, NULL) <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } for (pos = 0; pos < tlen; pos += SHA256_DIGEST_LENGTH, iter++) { if (HMAC_Init_ex(hmac, NULL, 0, NULL, NULL) <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } be_iter[0] = (iter >> 8) & 0xff; be_iter[1] = iter & 0xff; if (HMAC_Update(hmac, be_iter, sizeof(be_iter)) <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } if (HMAC_Update(hmac, (unsigned char *)label, llen) <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } if (HMAC_Update(hmac, be_bitlen, sizeof(be_bitlen)) <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } /* * HMAC_Final requires the output buffer to fit the whole MAC * value, so we need to use the intermediate buffer for the last * unaligned block */ md_len = SHA256_DIGEST_LENGTH; if (pos + SHA256_DIGEST_LENGTH > tlen) { if (HMAC_Final(hmac, hmac_out, &md_len) <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } memcpy(to + pos, hmac_out, tlen - pos); } else { if (HMAC_Final(hmac, to + pos, &md_len) <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); goto err; } } } ret = 0; err: HMAC_CTX_free(hmac); EVP_MD_free(md); return ret; } /* * ossl_rsa_padding_check_PKCS1_type_2() checks and removes the PKCS#1 type 2 * padding from a decrypted RSA message. Unlike the * RSA_padding_check_PKCS1_type_2() it will not return an error in case it * detects a padding error, rather it will return a deterministically generated * random message. In other words it will perform an implicit rejection * of an invalid padding. This means that the returned value does not indicate * if the padding of the encrypted message was correct or not, making * side channel attacks like the ones described by Bleichenbacher impossible * without access to the full decrypted value and a brute-force search of * remaining padding bytes */ int ossl_rsa_padding_check_PKCS1_type_2(OSSL_LIB_CTX *ctx, unsigned char *to, int tlen, const unsigned char *from, int flen, int num, unsigned char *kdk) { /* * We need to generate a random length for the synthetic message, to avoid * bias towards zero and avoid non-constant timeness of DIV, we prepare * 128 values to check if they are not too large for the used key size, * and use 0 in case none of them are small enough, as 2^-128 is a good enough * safety margin */ #define MAX_LEN_GEN_TRIES 128 unsigned char *synthetic = NULL; int synthetic_length; uint16_t len_candidate; unsigned char candidate_lengths[MAX_LEN_GEN_TRIES * sizeof(len_candidate)]; uint16_t len_mask; uint16_t max_sep_offset; int synth_msg_index = 0; int ret = -1; int i, j; unsigned int good, found_zero_byte; int zero_index = 0, msg_index; /* * If these checks fail then either the message in publicly invalid, or * we've been called incorrectly. We can fail immediately. * Since this code is called only internally by openssl, those are just * sanity checks */ if (num != flen || tlen <= 0 || flen <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); return -1; } /* Generate a random message to return in case the padding checks fail */ synthetic = OPENSSL_malloc(flen); if (synthetic == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE); return -1; } if (ossl_rsa_prf(ctx, synthetic, flen, "message", 7, kdk, flen * 8) < 0) goto err; /* decide how long the random message should be */ if (ossl_rsa_prf(ctx, candidate_lengths, sizeof(candidate_lengths), "length", 6, kdk, MAX_LEN_GEN_TRIES * sizeof(len_candidate) * 8) < 0) goto err; /* * max message size is the size of the modulus size less 2 bytes for * version and padding type and a minimum of 8 bytes padding */ len_mask = max_sep_offset = flen - 2 - 8; /* * we want a mask so lets propagate the high bit to all positions less * significant than it */ len_mask |= len_mask >> 1; len_mask |= len_mask >> 2; len_mask |= len_mask >> 4; len_mask |= len_mask >> 8; synthetic_length = 0; for (i = 0; i < MAX_LEN_GEN_TRIES * (int)sizeof(len_candidate); i += sizeof(len_candidate)) { len_candidate = (candidate_lengths[i] << 8) | candidate_lengths[i + 1]; len_candidate &= len_mask; synthetic_length = constant_time_select_int( constant_time_lt(len_candidate, max_sep_offset), len_candidate, synthetic_length); } synth_msg_index = flen - synthetic_length; /* we have alternative message ready, check the real one */ good = constant_time_is_zero(from[0]); good &= constant_time_eq(from[1], 2); /* then look for the padding|message separator (the first zero byte) */ found_zero_byte = 0; for (i = 2; i < flen; i++) { unsigned int equals0 = constant_time_is_zero(from[i]); zero_index = constant_time_select_int(~found_zero_byte & equals0, i, zero_index); found_zero_byte |= equals0; } /* * padding must be at least 8 bytes long, and it starts two bytes into * |from|. If we never found a 0-byte, then |zero_index| is 0 and the check * also fails. */ good &= constant_time_ge(zero_index, 2 + 8); /* * Skip the zero byte. This is incorrect if we never found a zero-byte * but in this case we also do not copy the message out. */ msg_index = zero_index + 1; /* * old code returned an error in case the decrypted message wouldn't fit * into the |to|, since that would leak information, return the synthetic * message instead */ good &= constant_time_ge(tlen, num - msg_index); msg_index = constant_time_select_int(good, msg_index, synth_msg_index); /* * since at this point the |msg_index| does not provide the signal * indicating if the padding check failed or not, we don't have to worry * about leaking the length of returned message, we still need to ensure * that we read contents of both buffers so that cache accesses don't leak * the value of |good| */ for (i = msg_index, j = 0; i < flen && j < tlen; i++, j++) to[j] = constant_time_select_8(good, from[i], synthetic[i]); ret = j; err: /* * the only time ret < 0 is when the ciphertext is publicly invalid * or we were called with invalid parameters, so we don't have to perform * a side-channel secure raising of the error */ if (ret < 0) ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); OPENSSL_free(synthetic); return ret; } /* * ossl_rsa_padding_check_PKCS1_type_2_TLS() checks and removes the PKCS1 type 2 * padding from a decrypted RSA message in a TLS signature. The result is stored * in the buffer pointed to by |to| which should be |tlen| bytes long. |tlen| * must be at least SSL_MAX_MASTER_KEY_LENGTH. The original decrypted message * should be stored in |from| which must be |flen| bytes in length and padded * such that |flen == RSA_size()|. The TLS protocol version that the client * originally requested should be passed in |client_version|. Some buggy clients * can exist which use the negotiated version instead of the originally * requested protocol version. If it is necessary to work around this bug then * the negotiated protocol version can be passed in |alt_version|, otherwise 0 * should be passed. * * If the passed message is publicly invalid or some other error that can be * treated in non-constant time occurs then -1 is returned. On success the * length of the decrypted data is returned. This will always be * SSL_MAX_MASTER_KEY_LENGTH. If an error occurs that should be treated in * constant time then this function will appear to return successfully, but the * decrypted data will be randomly generated (as per * https://tools.ietf.org/html/rfc5246#section-7.4.7.1). */ int ossl_rsa_padding_check_PKCS1_type_2_TLS(OSSL_LIB_CTX *libctx, unsigned char *to, size_t tlen, const unsigned char *from, size_t flen, int client_version, int alt_version) { unsigned int i, good, version_good; unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH]; /* * If these checks fail then either the message in publicly invalid, or * we've been called incorrectly. We can fail immediately. */ if (flen < RSA_PKCS1_PADDING_SIZE + SSL_MAX_MASTER_KEY_LENGTH || tlen < SSL_MAX_MASTER_KEY_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR); return -1; } /* * Generate a random premaster secret to use in the event that we fail * to decrypt. */ if (RAND_priv_bytes_ex(libctx, rand_premaster_secret, sizeof(rand_premaster_secret), 0) <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); return -1; } good = constant_time_is_zero(from[0]); good &= constant_time_eq(from[1], 2); /* Check we have the expected padding data */ for (i = 2; i < flen - SSL_MAX_MASTER_KEY_LENGTH - 1; i++) good &= ~constant_time_is_zero_8(from[i]); good &= constant_time_is_zero_8(from[flen - SSL_MAX_MASTER_KEY_LENGTH - 1]); /* * If the version in the decrypted pre-master secret is correct then * version_good will be 0xff, otherwise it'll be zero. The * Klima-Pokorny-Rosa extension of Bleichenbacher's attack * (http://eprint.iacr.org/2003/052/) exploits the version number * check as a "bad version oracle". Thus version checks are done in * constant time and are treated like any other decryption error. */ version_good = constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH], (client_version >> 8) & 0xff); version_good &= constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1], client_version & 0xff); /* * The premaster secret must contain the same version number as the * ClientHello to detect version rollback attacks (strangely, the * protocol does not offer such protection for DH ciphersuites). * However, buggy clients exist that send the negotiated protocol * version instead if the server does not support the requested * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set then we tolerate * such clients. In that case alt_version will be non-zero and set to * the negotiated version. */ if (alt_version > 0) { unsigned int workaround_good; workaround_good = constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH], (alt_version >> 8) & 0xff); workaround_good &= constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1], alt_version & 0xff); version_good |= workaround_good; } good &= version_good; /* * Now copy the result over to the to buffer if good, or random data if * not good. */ for (i = 0; i < SSL_MAX_MASTER_KEY_LENGTH; i++) { to[i] = constant_time_select_8(good, from[flen - SSL_MAX_MASTER_KEY_LENGTH + i], rand_premaster_secret[i]); } /* * We must not leak whether a decryption failure occurs because of * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246, * section 7.4.7.1). The code follows that advice of the TLS RFC and * generates a random premaster secret for the case that the decrypt * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1 * So, whether we actually succeeded or not, return success. */ return SSL_MAX_MASTER_KEY_LENGTH; }
22,210
33.329212
89
c
openssl
openssl-master/crypto/rsa/rsa_prn.c
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/rsa.h> #include <openssl/evp.h> #ifndef OPENSSL_NO_STDIO int RSA_print_fp(FILE *fp, const RSA *x, int off) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_RSA, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = RSA_print(b, x, off); BIO_free(b); return ret; } #endif int RSA_print(BIO *bp, const RSA *x, int off) { EVP_PKEY *pk; int ret; pk = EVP_PKEY_new(); if (pk == NULL) return 0; ret = EVP_PKEY_set1_RSA(pk, (RSA *)x); if (ret) ret = EVP_PKEY_print_private(bp, pk, off, NULL); EVP_PKEY_free(pk); return ret; }
1,194
22.431373
74
c
openssl
openssl-master/crypto/rsa/rsa_pss.c
/* * Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/sha.h> #include "rsa_local.h" static const unsigned char zeroes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; #if defined(_MSC_VER) && defined(_ARM_) # pragma optimize("g", off) #endif int RSA_verify_PKCS1_PSS(RSA *rsa, const unsigned char *mHash, const EVP_MD *Hash, const unsigned char *EM, int sLen) { return RSA_verify_PKCS1_PSS_mgf1(rsa, mHash, Hash, NULL, EM, sLen); } int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash, const EVP_MD *Hash, const EVP_MD *mgf1Hash, const unsigned char *EM, int sLen) { int i; int ret = 0; int hLen, maskedDBLen, MSBits, emLen; const unsigned char *H; unsigned char *DB = NULL; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); unsigned char H_[EVP_MAX_MD_SIZE]; if (ctx == NULL) goto err; if (mgf1Hash == NULL) mgf1Hash = Hash; hLen = EVP_MD_get_size(Hash); if (hLen < 0) goto err; /*- * Negative sLen has special meanings: * -1 sLen == hLen * -2 salt length is autorecovered from signature * -3 salt length is maximized * -4 salt length is autorecovered from signature * -N reserved */ if (sLen == RSA_PSS_SALTLEN_DIGEST) { sLen = hLen; } else if (sLen < RSA_PSS_SALTLEN_AUTO_DIGEST_MAX) { ERR_raise(ERR_LIB_RSA, RSA_R_SLEN_CHECK_FAILED); goto err; } MSBits = (BN_num_bits(rsa->n) - 1) & 0x7; emLen = RSA_size(rsa); if (EM[0] & (0xFF << MSBits)) { ERR_raise(ERR_LIB_RSA, RSA_R_FIRST_OCTET_INVALID); goto err; } if (MSBits == 0) { EM++; emLen--; } if (emLen < hLen + 2) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE); goto err; } if (sLen == RSA_PSS_SALTLEN_MAX) { sLen = emLen - hLen - 2; } else if (sLen > emLen - hLen - 2) { /* sLen can be small negative */ ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE); goto err; } if (EM[emLen - 1] != 0xbc) { ERR_raise(ERR_LIB_RSA, RSA_R_LAST_OCTET_INVALID); goto err; } maskedDBLen = emLen - hLen - 1; H = EM + maskedDBLen; DB = OPENSSL_malloc(maskedDBLen); if (DB == NULL) goto err; if (PKCS1_MGF1(DB, maskedDBLen, H, hLen, mgf1Hash) < 0) goto err; for (i = 0; i < maskedDBLen; i++) DB[i] ^= EM[i]; if (MSBits) DB[0] &= 0xFF >> (8 - MSBits); for (i = 0; DB[i] == 0 && i < (maskedDBLen - 1); i++) ; if (DB[i++] != 0x1) { ERR_raise(ERR_LIB_RSA, RSA_R_SLEN_RECOVERY_FAILED); goto err; } if (sLen != RSA_PSS_SALTLEN_AUTO && sLen != RSA_PSS_SALTLEN_AUTO_DIGEST_MAX && (maskedDBLen - i) != sLen) { ERR_raise_data(ERR_LIB_RSA, RSA_R_SLEN_CHECK_FAILED, "expected: %d retrieved: %d", sLen, maskedDBLen - i); goto err; } if (!EVP_DigestInit_ex(ctx, Hash, NULL) || !EVP_DigestUpdate(ctx, zeroes, sizeof(zeroes)) || !EVP_DigestUpdate(ctx, mHash, hLen)) goto err; if (maskedDBLen - i) { if (!EVP_DigestUpdate(ctx, DB + i, maskedDBLen - i)) goto err; } if (!EVP_DigestFinal_ex(ctx, H_, NULL)) goto err; if (memcmp(H_, H, hLen)) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); ret = 0; } else { ret = 1; } err: OPENSSL_free(DB); EVP_MD_CTX_free(ctx); return ret; } int RSA_padding_add_PKCS1_PSS(RSA *rsa, unsigned char *EM, const unsigned char *mHash, const EVP_MD *Hash, int sLen) { return RSA_padding_add_PKCS1_PSS_mgf1(rsa, EM, mHash, Hash, NULL, sLen); } int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM, const unsigned char *mHash, const EVP_MD *Hash, const EVP_MD *mgf1Hash, int sLen) { int i; int ret = 0; int hLen, maskedDBLen, MSBits, emLen; unsigned char *H, *salt = NULL, *p; EVP_MD_CTX *ctx = NULL; int sLenMax = -1; if (mgf1Hash == NULL) mgf1Hash = Hash; hLen = EVP_MD_get_size(Hash); if (hLen < 0) goto err; /*- * Negative sLen has special meanings: * -1 sLen == hLen * -2 salt length is maximized * -3 same as above (on signing) * -4 salt length is min(hLen, maximum salt length) * -N reserved */ /* FIPS 186-4 section 5 "The RSA Digital Signature Algorithm", subsection * 5.5 "PKCS #1" says: "For RSASSA-PSS […] the length (in bytes) of the * salt (sLen) shall satisfy 0 <= sLen <= hLen, where hLen is the length of * the hash function output block (in bytes)." * * Provide a way to use at most the digest length, so that the default does * not violate FIPS 186-4. */ if (sLen == RSA_PSS_SALTLEN_DIGEST) { sLen = hLen; } else if (sLen == RSA_PSS_SALTLEN_MAX_SIGN || sLen == RSA_PSS_SALTLEN_AUTO) { sLen = RSA_PSS_SALTLEN_MAX; } else if (sLen == RSA_PSS_SALTLEN_AUTO_DIGEST_MAX) { sLen = RSA_PSS_SALTLEN_MAX; sLenMax = hLen; } else if (sLen < RSA_PSS_SALTLEN_AUTO_DIGEST_MAX) { ERR_raise(ERR_LIB_RSA, RSA_R_SLEN_CHECK_FAILED); goto err; } MSBits = (BN_num_bits(rsa->n) - 1) & 0x7; emLen = RSA_size(rsa); if (MSBits == 0) { *EM++ = 0; emLen--; } if (emLen < hLen + 2) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); goto err; } if (sLen == RSA_PSS_SALTLEN_MAX) { sLen = emLen - hLen - 2; if (sLenMax >= 0 && sLen > sLenMax) sLen = sLenMax; } else if (sLen > emLen - hLen - 2) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); goto err; } if (sLen > 0) { salt = OPENSSL_malloc(sLen); if (salt == NULL) goto err; if (RAND_bytes_ex(rsa->libctx, salt, sLen, 0) <= 0) goto err; } maskedDBLen = emLen - hLen - 1; H = EM + maskedDBLen; ctx = EVP_MD_CTX_new(); if (ctx == NULL) goto err; if (!EVP_DigestInit_ex(ctx, Hash, NULL) || !EVP_DigestUpdate(ctx, zeroes, sizeof(zeroes)) || !EVP_DigestUpdate(ctx, mHash, hLen)) goto err; if (sLen && !EVP_DigestUpdate(ctx, salt, sLen)) goto err; if (!EVP_DigestFinal_ex(ctx, H, NULL)) goto err; /* Generate dbMask in place then perform XOR on it */ if (PKCS1_MGF1(EM, maskedDBLen, H, hLen, mgf1Hash)) goto err; p = EM; /* * Initial PS XORs with all zeroes which is a NOP so just update pointer. * Note from a test above this value is guaranteed to be non-negative. */ p += emLen - sLen - hLen - 2; *p++ ^= 0x1; if (sLen > 0) { for (i = 0; i < sLen; i++) *p++ ^= salt[i]; } if (MSBits) EM[0] &= 0xFF >> (8 - MSBits); /* H is already in place so just set final 0xbc */ EM[emLen - 1] = 0xbc; ret = 1; err: EVP_MD_CTX_free(ctx); OPENSSL_clear_free(salt, (size_t)sLen); /* salt != NULL implies sLen > 0 */ return ret; } /* * The defaults for PSS restrictions are defined in RFC 8017, A.2.3 RSASSA-PSS * (https://tools.ietf.org/html/rfc8017#appendix-A.2.3): * * If the default values of the hashAlgorithm, maskGenAlgorithm, and * trailerField fields of RSASSA-PSS-params are used, then the algorithm * identifier will have the following value: * * rSASSA-PSS-Default-Identifier RSASSA-AlgorithmIdentifier ::= { * algorithm id-RSASSA-PSS, * parameters RSASSA-PSS-params : { * hashAlgorithm sha1, * maskGenAlgorithm mgf1SHA1, * saltLength 20, * trailerField trailerFieldBC * } * } * * RSASSA-AlgorithmIdentifier ::= AlgorithmIdentifier { * {PKCS1Algorithms} * } */ static const RSA_PSS_PARAMS_30 default_RSASSA_PSS_params = { NID_sha1, /* default hashAlgorithm */ { NID_mgf1, /* default maskGenAlgorithm */ NID_sha1 /* default MGF1 hash */ }, 20, /* default saltLength */ 1 /* default trailerField (0xBC) */ }; int ossl_rsa_pss_params_30_set_defaults(RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return 0; *rsa_pss_params = default_RSASSA_PSS_params; return 1; } int ossl_rsa_pss_params_30_is_unrestricted(const RSA_PSS_PARAMS_30 *rsa_pss_params) { static RSA_PSS_PARAMS_30 pss_params_cmp = { 0, }; return rsa_pss_params == NULL || memcmp(rsa_pss_params, &pss_params_cmp, sizeof(*rsa_pss_params)) == 0; } int ossl_rsa_pss_params_30_copy(RSA_PSS_PARAMS_30 *to, const RSA_PSS_PARAMS_30 *from) { memcpy(to, from, sizeof(*to)); return 1; } int ossl_rsa_pss_params_30_set_hashalg(RSA_PSS_PARAMS_30 *rsa_pss_params, int hashalg_nid) { if (rsa_pss_params == NULL) return 0; rsa_pss_params->hash_algorithm_nid = hashalg_nid; return 1; } int ossl_rsa_pss_params_30_set_maskgenhashalg(RSA_PSS_PARAMS_30 *rsa_pss_params, int maskgenhashalg_nid) { if (rsa_pss_params == NULL) return 0; rsa_pss_params->mask_gen.hash_algorithm_nid = maskgenhashalg_nid; return 1; } int ossl_rsa_pss_params_30_set_saltlen(RSA_PSS_PARAMS_30 *rsa_pss_params, int saltlen) { if (rsa_pss_params == NULL) return 0; rsa_pss_params->salt_len = saltlen; return 1; } int ossl_rsa_pss_params_30_set_trailerfield(RSA_PSS_PARAMS_30 *rsa_pss_params, int trailerfield) { if (rsa_pss_params == NULL) return 0; rsa_pss_params->trailer_field = trailerfield; return 1; } int ossl_rsa_pss_params_30_hashalg(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.hash_algorithm_nid; return rsa_pss_params->hash_algorithm_nid; } int ossl_rsa_pss_params_30_maskgenalg(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.mask_gen.algorithm_nid; return rsa_pss_params->mask_gen.algorithm_nid; } int ossl_rsa_pss_params_30_maskgenhashalg(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.hash_algorithm_nid; return rsa_pss_params->mask_gen.hash_algorithm_nid; } int ossl_rsa_pss_params_30_saltlen(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.salt_len; return rsa_pss_params->salt_len; } int ossl_rsa_pss_params_30_trailerfield(const RSA_PSS_PARAMS_30 *rsa_pss_params) { if (rsa_pss_params == NULL) return default_RSASSA_PSS_params.trailer_field; return rsa_pss_params->trailer_field; } #if defined(_MSC_VER) # pragma optimize("",on) #endif
12,053
28.985075
83
c
openssl
openssl-master/crypto/rsa/rsa_saos.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/objects.h> #include <openssl/x509.h> int RSA_sign_ASN1_OCTET_STRING(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, RSA *rsa) { ASN1_OCTET_STRING sig; int i, j, ret = 1; unsigned char *p, *s; sig.type = V_ASN1_OCTET_STRING; sig.length = m_len; sig.data = (unsigned char *)m; i = i2d_ASN1_OCTET_STRING(&sig, NULL); j = RSA_size(rsa); if (i > (j - RSA_PKCS1_PADDING_SIZE)) { ERR_raise(ERR_LIB_RSA, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY); return 0; } s = OPENSSL_malloc((unsigned int)j + 1); if (s == NULL) return 0; p = s; i2d_ASN1_OCTET_STRING(&sig, &p); i = RSA_private_encrypt(i, s, sigret, rsa, RSA_PKCS1_PADDING); if (i <= 0) ret = 0; else *siglen = i; OPENSSL_clear_free(s, (unsigned int)j + 1); return ret; } int RSA_verify_ASN1_OCTET_STRING(int dtype, const unsigned char *m, unsigned int m_len, unsigned char *sigbuf, unsigned int siglen, RSA *rsa) { int i, ret = 0; unsigned char *s; const unsigned char *p; ASN1_OCTET_STRING *sig = NULL; if (siglen != (unsigned int)RSA_size(rsa)) { ERR_raise(ERR_LIB_RSA, RSA_R_WRONG_SIGNATURE_LENGTH); return 0; } s = OPENSSL_malloc((unsigned int)siglen); if (s == NULL) goto err; i = RSA_public_decrypt((int)siglen, sigbuf, s, rsa, RSA_PKCS1_PADDING); if (i <= 0) goto err; p = s; sig = d2i_ASN1_OCTET_STRING(NULL, &p, (long)i); if (sig == NULL) goto err; if (((unsigned int)sig->length != m_len) || (memcmp(m, sig->data, m_len) != 0)) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); } else { ret = 1; } err: ASN1_OCTET_STRING_free(sig); OPENSSL_clear_free(s, (unsigned int)siglen); return ret; }
2,628
26.385417
75
c
openssl
openssl-master/crypto/rsa/rsa_schemes.c
/* * Copyright 2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core.h> #include <openssl/core_names.h> #include <openssl/evp.h> #include <openssl/obj_mac.h> #include "internal/nelem.h" #include "crypto/rsa.h" static int meth2nid(const void *meth, int (*meth_is_a)(const void *meth, const char *name), const OSSL_ITEM *items, size_t items_n) { size_t i; if (meth != NULL) for (i = 0; i < items_n; i++) if (meth_is_a(meth, items[i].ptr)) return (int)items[i].id; return NID_undef; } static const char *nid2name(int meth, const OSSL_ITEM *items, size_t items_n) { size_t i; for (i = 0; i < items_n; i++) if (meth == (int)items[i].id) return items[i].ptr; return NULL; } /* * The list of permitted hash functions are taken from * https://tools.ietf.org/html/rfc8017#appendix-A.2.1: * * OAEP-PSSDigestAlgorithms ALGORITHM-IDENTIFIER ::= { * { OID id-sha1 PARAMETERS NULL }| * { OID id-sha224 PARAMETERS NULL }| * { OID id-sha256 PARAMETERS NULL }| * { OID id-sha384 PARAMETERS NULL }| * { OID id-sha512 PARAMETERS NULL }| * { OID id-sha512-224 PARAMETERS NULL }| * { OID id-sha512-256 PARAMETERS NULL }, * ... -- Allows for future expansion -- * } */ static const OSSL_ITEM oaeppss_name_nid_map[] = { { NID_sha1, OSSL_DIGEST_NAME_SHA1 }, { NID_sha224, OSSL_DIGEST_NAME_SHA2_224 }, { NID_sha256, OSSL_DIGEST_NAME_SHA2_256 }, { NID_sha384, OSSL_DIGEST_NAME_SHA2_384 }, { NID_sha512, OSSL_DIGEST_NAME_SHA2_512 }, { NID_sha512_224, OSSL_DIGEST_NAME_SHA2_512_224 }, { NID_sha512_256, OSSL_DIGEST_NAME_SHA2_512_256 }, }; static int md_is_a(const void *md, const char *name) { return EVP_MD_is_a(md, name); } int ossl_rsa_oaeppss_md2nid(const EVP_MD *md) { return meth2nid(md, md_is_a, oaeppss_name_nid_map, OSSL_NELEM(oaeppss_name_nid_map)); } const char *ossl_rsa_oaeppss_nid2name(int md) { return nid2name(md, oaeppss_name_nid_map, OSSL_NELEM(oaeppss_name_nid_map)); } const char *ossl_rsa_mgf_nid2name(int mgf) { if (mgf == NID_mgf1) return SN_mgf1; return NULL; }
2,582
28.689655
80
c
openssl
openssl-master/crypto/rsa/rsa_sign.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/objects.h> #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MD2 # include <openssl/md2.h> /* uses MD2_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_MD4 # include <openssl/md4.h> /* uses MD4_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_MD5 # include <openssl/md5.h> /* uses MD5_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_MDC2 # include <openssl/mdc2.h> /* uses MDC2_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_RMD160 # include <openssl/ripemd.h> /* uses RIPEMD160_DIGEST_LENGTH */ # endif #endif #include <openssl/sha.h> /* uses SHA???_DIGEST_LENGTH */ #include "crypto/rsa.h" #include "rsa_local.h" /* * The general purpose ASN1 code is not available inside the FIPS provider. * To remove the dependency RSASSA-PKCS1-v1_5 DigestInfo encodings can be * treated as a special case by pregenerating the required ASN1 encoding. * This encoding will also be shared by the default provider. * * The EMSA-PKCS1-v1_5 encoding method includes an ASN.1 value of type * DigestInfo, where the type DigestInfo has the syntax * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithm, * digest OCTET STRING * } * * DigestAlgorithm ::= AlgorithmIdentifier { * {PKCS1-v1-5DigestAlgorithms} * } * * The AlgorithmIdentifier is a sequence containing the digest OID and * parameters (a value of type NULL). * * The ENCODE_DIGESTINFO_SHA() and ENCODE_DIGESTINFO_MD() macros define an * initialized array containing the DER encoded DigestInfo for the specified * SHA or MD digest. The content of the OCTET STRING is not included. * |name| is the digest name. * |n| is last byte in the encoded OID for the digest. * |sz| is the digest length in bytes. It must not be greater than 110. */ #define ASN1_SEQUENCE 0x30 #define ASN1_OCTET_STRING 0x04 #define ASN1_NULL 0x05 #define ASN1_OID 0x06 /* SHA OIDs are of the form: (2 16 840 1 101 3 4 2 |n|) */ #define ENCODE_DIGESTINFO_SHA(name, n, sz) \ static const unsigned char digestinfo_##name##_der[] = { \ ASN1_SEQUENCE, 0x11 + sz, \ ASN1_SEQUENCE, 0x0d, \ ASN1_OID, 0x09, 2 * 40 + 16, 0x86, 0x48, 1, 101, 3, 4, 2, n, \ ASN1_NULL, 0x00, \ ASN1_OCTET_STRING, sz \ }; /* MD2, MD4 and MD5 OIDs are of the form: (1 2 840 113549 2 |n|) */ #define ENCODE_DIGESTINFO_MD(name, n, sz) \ static const unsigned char digestinfo_##name##_der[] = { \ ASN1_SEQUENCE, 0x10 + sz, \ ASN1_SEQUENCE, 0x0c, \ ASN1_OID, 0x08, 1 * 40 + 2, 0x86, 0x48, 0x86, 0xf7, 0x0d, 2, n, \ ASN1_NULL, 0x00, \ ASN1_OCTET_STRING, sz \ }; #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MD2 ENCODE_DIGESTINFO_MD(md2, 0x02, MD2_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD4 ENCODE_DIGESTINFO_MD(md4, 0x03, MD4_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD5 ENCODE_DIGESTINFO_MD(md5, 0x05, MD5_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MDC2 /* MDC-2 (2 5 8 3 101) */ static const unsigned char digestinfo_mdc2_der[] = { ASN1_SEQUENCE, 0x0c + MDC2_DIGEST_LENGTH, ASN1_SEQUENCE, 0x08, ASN1_OID, 0x04, 2 * 40 + 5, 8, 3, 101, ASN1_NULL, 0x00, ASN1_OCTET_STRING, MDC2_DIGEST_LENGTH }; # endif # ifndef OPENSSL_NO_RMD160 /* RIPEMD160 (1 3 36 3 2 1) */ static const unsigned char digestinfo_ripemd160_der[] = { ASN1_SEQUENCE, 0x0d + RIPEMD160_DIGEST_LENGTH, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, 1 * 40 + 3, 36, 3, 2, 1, ASN1_NULL, 0x00, ASN1_OCTET_STRING, RIPEMD160_DIGEST_LENGTH }; # endif #endif /* FIPS_MODULE */ /* SHA-1 (1 3 14 3 2 26) */ static const unsigned char digestinfo_sha1_der[] = { ASN1_SEQUENCE, 0x0d + SHA_DIGEST_LENGTH, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, 1 * 40 + 3, 14, 3, 2, 26, ASN1_NULL, 0x00, ASN1_OCTET_STRING, SHA_DIGEST_LENGTH }; ENCODE_DIGESTINFO_SHA(sha256, 0x01, SHA256_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha384, 0x02, SHA384_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha512, 0x03, SHA512_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha224, 0x04, SHA224_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha512_224, 0x05, SHA224_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha512_256, 0x06, SHA256_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_224, 0x07, SHA224_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_256, 0x08, SHA256_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_384, 0x09, SHA384_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_512, 0x0a, SHA512_DIGEST_LENGTH) #define MD_CASE(name) \ case NID_##name: \ *len = sizeof(digestinfo_##name##_der); \ return digestinfo_##name##_der; const unsigned char *ossl_rsa_digestinfo_encoding(int md_nid, size_t *len) { switch (md_nid) { #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MDC2 MD_CASE(mdc2) # endif # ifndef OPENSSL_NO_MD2 MD_CASE(md2) # endif # ifndef OPENSSL_NO_MD4 MD_CASE(md4) # endif # ifndef OPENSSL_NO_MD5 MD_CASE(md5) # endif # ifndef OPENSSL_NO_RMD160 MD_CASE(ripemd160) # endif #endif /* FIPS_MODULE */ MD_CASE(sha1) MD_CASE(sha224) MD_CASE(sha256) MD_CASE(sha384) MD_CASE(sha512) MD_CASE(sha512_224) MD_CASE(sha512_256) MD_CASE(sha3_224) MD_CASE(sha3_256) MD_CASE(sha3_384) MD_CASE(sha3_512) default: return NULL; } } #define MD_NID_CASE(name, sz) \ case NID_##name: \ return sz; static int digest_sz_from_nid(int nid) { switch (nid) { #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MDC2 MD_NID_CASE(mdc2, MDC2_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD2 MD_NID_CASE(md2, MD2_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD4 MD_NID_CASE(md4, MD4_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD5 MD_NID_CASE(md5, MD5_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_RMD160 MD_NID_CASE(ripemd160, RIPEMD160_DIGEST_LENGTH) # endif #endif /* FIPS_MODULE */ MD_NID_CASE(sha1, SHA_DIGEST_LENGTH) MD_NID_CASE(sha224, SHA224_DIGEST_LENGTH) MD_NID_CASE(sha256, SHA256_DIGEST_LENGTH) MD_NID_CASE(sha384, SHA384_DIGEST_LENGTH) MD_NID_CASE(sha512, SHA512_DIGEST_LENGTH) MD_NID_CASE(sha512_224, SHA224_DIGEST_LENGTH) MD_NID_CASE(sha512_256, SHA256_DIGEST_LENGTH) MD_NID_CASE(sha3_224, SHA224_DIGEST_LENGTH) MD_NID_CASE(sha3_256, SHA256_DIGEST_LENGTH) MD_NID_CASE(sha3_384, SHA384_DIGEST_LENGTH) MD_NID_CASE(sha3_512, SHA512_DIGEST_LENGTH) default: return 0; } } /* Size of an SSL signature: MD5+SHA1 */ #define SSL_SIG_LENGTH 36 /* * Encodes a DigestInfo prefix of hash |type| and digest |m|, as * described in EMSA-PKCS1-v1_5-ENCODE, RFC 3447 section 9.2 step 2. This * encodes the DigestInfo (T and tLen) but does not add the padding. * * On success, it returns one and sets |*out| to a newly allocated buffer * containing the result and |*out_len| to its length. The caller must free * |*out| with OPENSSL_free(). Otherwise, it returns zero. */ static int encode_pkcs1(unsigned char **out, size_t *out_len, int type, const unsigned char *m, size_t m_len) { size_t di_prefix_len, dig_info_len; const unsigned char *di_prefix; unsigned char *dig_info; if (type == NID_undef) { ERR_raise(ERR_LIB_RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE); return 0; } di_prefix = ossl_rsa_digestinfo_encoding(type, &di_prefix_len); if (di_prefix == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD); return 0; } dig_info_len = di_prefix_len + m_len; dig_info = OPENSSL_malloc(dig_info_len); if (dig_info == NULL) return 0; memcpy(dig_info, di_prefix, di_prefix_len); memcpy(dig_info + di_prefix_len, m, m_len); *out = dig_info; *out_len = dig_info_len; return 1; } int RSA_sign(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, RSA *rsa) { int encrypt_len, ret = 0; size_t encoded_len = 0; unsigned char *tmps = NULL; const unsigned char *encoded = NULL; #ifndef FIPS_MODULE if (rsa->meth->rsa_sign != NULL) return rsa->meth->rsa_sign(type, m, m_len, sigret, siglen, rsa) > 0; #endif /* FIPS_MODULE */ /* Compute the encoded digest. */ if (type == NID_md5_sha1) { /* * NID_md5_sha1 corresponds to the MD5/SHA1 combination in TLS 1.1 and * earlier. It has no DigestInfo wrapper but otherwise is * RSASSA-PKCS1-v1_5. */ if (m_len != SSL_SIG_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MESSAGE_LENGTH); return 0; } encoded_len = SSL_SIG_LENGTH; encoded = m; } else { if (!encode_pkcs1(&tmps, &encoded_len, type, m, m_len)) goto err; encoded = tmps; } if (encoded_len + RSA_PKCS1_PADDING_SIZE > (size_t)RSA_size(rsa)) { ERR_raise(ERR_LIB_RSA, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY); goto err; } encrypt_len = RSA_private_encrypt((int)encoded_len, encoded, sigret, rsa, RSA_PKCS1_PADDING); if (encrypt_len <= 0) goto err; *siglen = encrypt_len; ret = 1; err: OPENSSL_clear_free(tmps, encoded_len); return ret; } /* * Verify an RSA signature in |sigbuf| using |rsa|. * |type| is the NID of the digest algorithm to use. * If |rm| is NULL, it verifies the signature for digest |m|, otherwise * it recovers the digest from the signature, writing the digest to |rm| and * the length to |*prm_len|. * * It returns one on successful verification or zero otherwise. */ int ossl_rsa_verify(int type, const unsigned char *m, unsigned int m_len, unsigned char *rm, size_t *prm_len, const unsigned char *sigbuf, size_t siglen, RSA *rsa) { int len, ret = 0; size_t decrypt_len, encoded_len = 0; unsigned char *decrypt_buf = NULL, *encoded = NULL; if (siglen != (size_t)RSA_size(rsa)) { ERR_raise(ERR_LIB_RSA, RSA_R_WRONG_SIGNATURE_LENGTH); return 0; } /* Recover the encoded digest. */ decrypt_buf = OPENSSL_malloc(siglen); if (decrypt_buf == NULL) goto err; len = RSA_public_decrypt((int)siglen, sigbuf, decrypt_buf, rsa, RSA_PKCS1_PADDING); if (len <= 0) goto err; decrypt_len = len; #ifndef FIPS_MODULE if (type == NID_md5_sha1) { /* * NID_md5_sha1 corresponds to the MD5/SHA1 combination in TLS 1.1 and * earlier. It has no DigestInfo wrapper but otherwise is * RSASSA-PKCS1-v1_5. */ if (decrypt_len != SSL_SIG_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } if (rm != NULL) { memcpy(rm, decrypt_buf, SSL_SIG_LENGTH); *prm_len = SSL_SIG_LENGTH; } else { if (m_len != SSL_SIG_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MESSAGE_LENGTH); goto err; } if (memcmp(decrypt_buf, m, SSL_SIG_LENGTH) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } } } else if (type == NID_mdc2 && decrypt_len == 2 + 16 && decrypt_buf[0] == 0x04 && decrypt_buf[1] == 0x10) { /* * Oddball MDC2 case: signature can be OCTET STRING. check for correct * tag and length octets. */ if (rm != NULL) { memcpy(rm, decrypt_buf + 2, 16); *prm_len = 16; } else { if (m_len != 16) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MESSAGE_LENGTH); goto err; } if (memcmp(m, decrypt_buf + 2, 16) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } } } else #endif /* FIPS_MODULE */ { /* * If recovering the digest, extract a digest-sized output from the end * of |decrypt_buf| for |encode_pkcs1|, then compare the decryption * output as in a standard verification. */ if (rm != NULL) { len = digest_sz_from_nid(type); if (len <= 0) goto err; m_len = (unsigned int)len; if (m_len > decrypt_len) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_DIGEST_LENGTH); goto err; } m = decrypt_buf + decrypt_len - m_len; } /* Construct the encoded digest and ensure it matches. */ if (!encode_pkcs1(&encoded, &encoded_len, type, m, m_len)) goto err; if (encoded_len != decrypt_len || memcmp(encoded, decrypt_buf, encoded_len) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } /* Output the recovered digest. */ if (rm != NULL) { memcpy(rm, m, m_len); *prm_len = m_len; } } ret = 1; err: OPENSSL_clear_free(encoded, encoded_len); OPENSSL_clear_free(decrypt_buf, siglen); return ret; } int RSA_verify(int type, const unsigned char *m, unsigned int m_len, const unsigned char *sigbuf, unsigned int siglen, RSA *rsa) { if (rsa->meth->rsa_verify != NULL) return rsa->meth->rsa_verify(type, m, m_len, sigbuf, siglen, rsa); return ossl_rsa_verify(type, m, m_len, NULL, NULL, sigbuf, siglen, rsa); }
14,795
31.590308
80
c
openssl
openssl-master/crypto/rsa/rsa_sp800_56b_check.c
/* * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2018-2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/bn.h> #include "crypto/bn.h" #include "rsa_local.h" /* * Part of the RSA keypair test. * Check the Chinese Remainder Theorem components are valid. * * See SP800-5bBr1 * 6.4.1.2.3: rsakpv1-crt Step 7 * 6.4.1.3.3: rsakpv2-crt Step 7 */ int ossl_rsa_check_crt_components(const RSA *rsa, BN_CTX *ctx) { int ret = 0; BIGNUM *r = NULL, *p1 = NULL, *q1 = NULL; /* check if only some of the crt components are set */ if (rsa->dmp1 == NULL || rsa->dmq1 == NULL || rsa->iqmp == NULL) { if (rsa->dmp1 != NULL || rsa->dmq1 != NULL || rsa->iqmp != NULL) return 0; return 1; /* return ok if all components are NULL */ } BN_CTX_start(ctx); r = BN_CTX_get(ctx); p1 = BN_CTX_get(ctx); q1 = BN_CTX_get(ctx); if (q1 != NULL) { BN_set_flags(r, BN_FLG_CONSTTIME); BN_set_flags(p1, BN_FLG_CONSTTIME); BN_set_flags(q1, BN_FLG_CONSTTIME); ret = 1; } else { ret = 0; } ret = ret /* p1 = p -1 */ && (BN_copy(p1, rsa->p) != NULL) && BN_sub_word(p1, 1) /* q1 = q - 1 */ && (BN_copy(q1, rsa->q) != NULL) && BN_sub_word(q1, 1) /* (a) 1 < dP < (p – 1). */ && (BN_cmp(rsa->dmp1, BN_value_one()) > 0) && (BN_cmp(rsa->dmp1, p1) < 0) /* (b) 1 < dQ < (q - 1). */ && (BN_cmp(rsa->dmq1, BN_value_one()) > 0) && (BN_cmp(rsa->dmq1, q1) < 0) /* (c) 1 < qInv < p */ && (BN_cmp(rsa->iqmp, BN_value_one()) > 0) && (BN_cmp(rsa->iqmp, rsa->p) < 0) /* (d) 1 = (dP . e) mod (p - 1)*/ && BN_mod_mul(r, rsa->dmp1, rsa->e, p1, ctx) && BN_is_one(r) /* (e) 1 = (dQ . e) mod (q - 1) */ && BN_mod_mul(r, rsa->dmq1, rsa->e, q1, ctx) && BN_is_one(r) /* (f) 1 = (qInv . q) mod p */ && BN_mod_mul(r, rsa->iqmp, rsa->q, rsa->p, ctx) && BN_is_one(r); BN_clear(r); BN_clear(p1); BN_clear(q1); BN_CTX_end(ctx); return ret; } /* * Part of the RSA keypair test. * Check that (√2)(2^(nbits/2 - 1) <= p <= 2^(nbits/2) - 1 * * See SP800-5bBr1 6.4.1.2.1 Part 5 (c) & (g) - used for both p and q. * * (√2)(2^(nbits/2 - 1) = (√2/2)(2^(nbits/2)) */ int ossl_rsa_check_prime_factor_range(const BIGNUM *p, int nbits, BN_CTX *ctx) { int ret = 0; BIGNUM *low; int shift; nbits >>= 1; shift = nbits - BN_num_bits(&ossl_bn_inv_sqrt_2); /* Upper bound check */ if (BN_num_bits(p) != nbits) return 0; BN_CTX_start(ctx); low = BN_CTX_get(ctx); if (low == NULL) goto err; /* set low = (√2)(2^(nbits/2 - 1) */ if (!BN_copy(low, &ossl_bn_inv_sqrt_2)) goto err; if (shift >= 0) { /* * We don't have all the bits. ossl_bn_inv_sqrt_2 contains a rounded up * value, so there is a very low probability that we'll reject a valid * value. */ if (!BN_lshift(low, low, shift)) goto err; } else if (!BN_rshift(low, low, -shift)) { goto err; } if (BN_cmp(p, low) <= 0) goto err; ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Part of the RSA keypair test. * Check the prime factor (for either p or q) * i.e: p is prime AND GCD(p - 1, e) = 1 * * See SP800-56Br1 6.4.1.2.3 Step 5 (a to d) & (e to h). */ int ossl_rsa_check_prime_factor(BIGNUM *p, BIGNUM *e, int nbits, BN_CTX *ctx) { int ret = 0; BIGNUM *p1 = NULL, *gcd = NULL; /* (Steps 5 a-b) prime test */ if (BN_check_prime(p, ctx, NULL) != 1 /* (Step 5c) (√2)(2^(nbits/2 - 1) <= p <= 2^(nbits/2 - 1) */ || ossl_rsa_check_prime_factor_range(p, nbits, ctx) != 1) return 0; BN_CTX_start(ctx); p1 = BN_CTX_get(ctx); gcd = BN_CTX_get(ctx); if (gcd != NULL) { BN_set_flags(p1, BN_FLG_CONSTTIME); BN_set_flags(gcd, BN_FLG_CONSTTIME); ret = 1; } else { ret = 0; } ret = ret /* (Step 5d) GCD(p-1, e) = 1 */ && (BN_copy(p1, p) != NULL) && BN_sub_word(p1, 1) && BN_gcd(gcd, p1, e, ctx) && BN_is_one(gcd); BN_clear(p1); BN_CTX_end(ctx); return ret; } /* * See SP800-56Br1 6.4.1.2.3 Part 6(a-b) Check the private exponent d * satisfies: * (Step 6a) 2^(nBit/2) < d < LCM(p–1, q–1). * (Step 6b) 1 = (d*e) mod LCM(p–1, q–1) */ int ossl_rsa_check_private_exponent(const RSA *rsa, int nbits, BN_CTX *ctx) { int ret; BIGNUM *r, *p1, *q1, *lcm, *p1q1, *gcd; /* (Step 6a) 2^(nbits/2) < d */ if (BN_num_bits(rsa->d) <= (nbits >> 1)) return 0; BN_CTX_start(ctx); r = BN_CTX_get(ctx); p1 = BN_CTX_get(ctx); q1 = BN_CTX_get(ctx); lcm = BN_CTX_get(ctx); p1q1 = BN_CTX_get(ctx); gcd = BN_CTX_get(ctx); if (gcd != NULL) { BN_set_flags(r, BN_FLG_CONSTTIME); BN_set_flags(p1, BN_FLG_CONSTTIME); BN_set_flags(q1, BN_FLG_CONSTTIME); BN_set_flags(lcm, BN_FLG_CONSTTIME); BN_set_flags(p1q1, BN_FLG_CONSTTIME); BN_set_flags(gcd, BN_FLG_CONSTTIME); ret = 1; } else { ret = 0; } ret = (ret /* LCM(p - 1, q - 1) */ && (ossl_rsa_get_lcm(ctx, rsa->p, rsa->q, lcm, gcd, p1, q1, p1q1) == 1) /* (Step 6a) d < LCM(p - 1, q - 1) */ && (BN_cmp(rsa->d, lcm) < 0) /* (Step 6b) 1 = (e . d) mod LCM(p - 1, q - 1) */ && BN_mod_mul(r, rsa->e, rsa->d, lcm, ctx) && BN_is_one(r)); BN_clear(r); BN_clear(p1); BN_clear(q1); BN_clear(lcm); BN_clear(gcd); BN_CTX_end(ctx); return ret; } /* * Check exponent is odd. * For FIPS also check the bit length is in the range [17..256] */ int ossl_rsa_check_public_exponent(const BIGNUM *e) { #ifdef FIPS_MODULE int bitlen; bitlen = BN_num_bits(e); return (BN_is_odd(e) && bitlen > 16 && bitlen < 257); #else /* Allow small exponents larger than 1 for legacy purposes */ return BN_is_odd(e) && BN_cmp(e, BN_value_one()) > 0; #endif /* FIPS_MODULE */ } /* * SP800-56Br1 6.4.1.2.1 (Step 5i): |p - q| > 2^(nbits/2 - 100) * i.e- numbits(p-q-1) > (nbits/2 -100) */ int ossl_rsa_check_pminusq_diff(BIGNUM *diff, const BIGNUM *p, const BIGNUM *q, int nbits) { int bitlen = (nbits >> 1) - 100; if (!BN_sub(diff, p, q)) return -1; BN_set_negative(diff, 0); if (BN_is_zero(diff)) return 0; if (!BN_sub_word(diff, 1)) return -1; return (BN_num_bits(diff) > bitlen); } /* * return LCM(p-1, q-1) * * Caller should ensure that lcm, gcd, p1, q1, p1q1 are flagged with * BN_FLG_CONSTTIME. */ int ossl_rsa_get_lcm(BN_CTX *ctx, const BIGNUM *p, const BIGNUM *q, BIGNUM *lcm, BIGNUM *gcd, BIGNUM *p1, BIGNUM *q1, BIGNUM *p1q1) { return BN_sub(p1, p, BN_value_one()) /* p-1 */ && BN_sub(q1, q, BN_value_one()) /* q-1 */ && BN_mul(p1q1, p1, q1, ctx) /* (p-1)(q-1) */ && BN_gcd(gcd, p1, q1, ctx) && BN_div(lcm, NULL, p1q1, gcd, ctx); /* LCM((p-1, q-1)) */ } /* * SP800-56Br1 6.4.2.2 Partial Public Key Validation for RSA refers to * SP800-89 5.3.3 (Explicit) Partial Public Key Validation for RSA * caveat is that the modulus must be as specified in SP800-56Br1 */ int ossl_rsa_sp800_56b_check_public(const RSA *rsa) { int ret = 0, status; int nbits; BN_CTX *ctx = NULL; BIGNUM *gcd = NULL; if (rsa->n == NULL || rsa->e == NULL) return 0; nbits = BN_num_bits(rsa->n); #ifdef FIPS_MODULE /* * (Step a): modulus must be 2048 or 3072 (caveat from SP800-56Br1) * NOTE: changed to allow keys >= 2048 */ if (!ossl_rsa_sp800_56b_validate_strength(nbits, -1)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_KEY_LENGTH); return 0; } #endif if (!BN_is_odd(rsa->n)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MODULUS); return 0; } /* (Steps b-c): 2^16 < e < 2^256, n and e must be odd */ if (!ossl_rsa_check_public_exponent(rsa->e)) { ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE); return 0; } ctx = BN_CTX_new_ex(rsa->libctx); gcd = BN_new(); if (ctx == NULL || gcd == NULL) goto err; /* (Steps d-f): * The modulus is composite, but not a power of a prime. * The modulus has no factors smaller than 752. */ if (!BN_gcd(gcd, rsa->n, ossl_bn_get0_small_factors(), ctx) || !BN_is_one(gcd)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MODULUS); goto err; } ret = ossl_bn_miller_rabin_is_prime(rsa->n, 0, ctx, NULL, 1, &status); #ifdef FIPS_MODULE if (ret != 1 || status != BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME) { #else if (ret != 1 || (status != BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME && (nbits >= RSA_MIN_MODULUS_BITS || status != BN_PRIMETEST_COMPOSITE_WITH_FACTOR))) { #endif ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MODULUS); ret = 0; goto err; } ret = 1; err: BN_free(gcd); BN_CTX_free(ctx); return ret; } /* * Perform validation of the RSA private key to check that 0 < D < N. */ int ossl_rsa_sp800_56b_check_private(const RSA *rsa) { if (rsa->d == NULL || rsa->n == NULL) return 0; return BN_cmp(rsa->d, BN_value_one()) >= 0 && BN_cmp(rsa->d, rsa->n) < 0; } /* * RSA key pair validation. * * SP800-56Br1. * 6.4.1.2 "RSAKPV1 Family: RSA Key - Pair Validation with a Fixed Exponent" * 6.4.1.3 "RSAKPV2 Family: RSA Key - Pair Validation with a Random Exponent" * * It uses: * 6.4.1.2.3 "rsakpv1 - crt" * 6.4.1.3.3 "rsakpv2 - crt" */ int ossl_rsa_sp800_56b_check_keypair(const RSA *rsa, const BIGNUM *efixed, int strength, int nbits) { int ret = 0; BN_CTX *ctx = NULL; BIGNUM *r = NULL; if (rsa->p == NULL || rsa->q == NULL || rsa->e == NULL || rsa->d == NULL || rsa->n == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_REQUEST); return 0; } /* (Step 1): Check Ranges */ if (!ossl_rsa_sp800_56b_validate_strength(nbits, strength)) return 0; /* If the exponent is known */ if (efixed != NULL) { /* (2): Check fixed exponent matches public exponent. */ if (BN_cmp(efixed, rsa->e) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_REQUEST); return 0; } } /* (Step 1.c): e is odd integer 65537 <= e < 2^256 */ if (!ossl_rsa_check_public_exponent(rsa->e)) { /* exponent out of range */ ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE); return 0; } /* (Step 3.b): check the modulus */ if (nbits != BN_num_bits(rsa->n)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_KEYPAIR); return 0; } ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) return 0; BN_CTX_start(ctx); r = BN_CTX_get(ctx); if (r == NULL || !BN_mul(r, rsa->p, rsa->q, ctx)) goto err; /* (Step 4.c): Check n = pq */ if (BN_cmp(rsa->n, r) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_REQUEST); goto err; } /* (Step 5): check prime factors p & q */ ret = ossl_rsa_check_prime_factor(rsa->p, rsa->e, nbits, ctx) && ossl_rsa_check_prime_factor(rsa->q, rsa->e, nbits, ctx) && (ossl_rsa_check_pminusq_diff(r, rsa->p, rsa->q, nbits) > 0) /* (Step 6): Check the private exponent d */ && ossl_rsa_check_private_exponent(rsa, nbits, ctx) /* 6.4.1.2.3 (Step 7): Check the CRT components */ && ossl_rsa_check_crt_components(rsa, ctx); if (ret != 1) ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_KEYPAIR); err: BN_clear(r); BN_CTX_end(ctx); BN_CTX_free(ctx); return ret; }
12,508
27.559361
80
c
openssl
openssl-master/crypto/rsa/rsa_sp800_56b_gen.c
/* * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2018-2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/core.h> #include <openssl/evp.h> #include <openssl/rand.h> #include "crypto/bn.h" #include "crypto/security_bits.h" #include "rsa_local.h" #define RSA_FIPS1864_MIN_KEYGEN_KEYSIZE 2048 #define RSA_FIPS1864_MIN_KEYGEN_STRENGTH 112 /* * Generate probable primes 'p' & 'q'. See FIPS 186-4 Section B.3.6 * "Generation of Probable Primes with Conditions Based on Auxiliary Probable * Primes". * * Params: * rsa Object used to store primes p & q. * test Object used for CAVS testing only.that contains.. * p1, p2 The returned auxiliary primes for p. * If NULL they are not returned. * Xpout An optionally returned random number used during generation of p. * Xp An optional passed in value (that is random number used during * generation of p). * Xp1, Xp2 Optionally passed in randomly generated numbers from which * auxiliary primes p1 & p2 are calculated. If NULL these values * are generated internally. * q1, q2 The returned auxiliary primes for q. * If NULL they are not returned. * Xqout An optionally returned random number used during generation of q. * Xq An optional passed in value (that is random number used during * generation of q). * Xq1, Xq2 Optionally passed in randomly generated numbers from which * auxiliary primes q1 & q2 are calculated. If NULL these values * are generated internally. * nbits The key size in bits (The size of the modulus n). * e The public exponent. * ctx A BN_CTX object. * cb An optional BIGNUM callback. * Returns: 1 if successful, or 0 otherwise. * Notes: * p1, p2, q1, q2, Xpout, Xqout are returned if they are not NULL. * Xp, Xp1, Xp2, Xq, Xq1, Xq2 are optionally passed in. * (Required for CAVS testing). */ int ossl_rsa_fips186_4_gen_prob_primes(RSA *rsa, RSA_ACVP_TEST *test, int nbits, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0, ok; /* Temp allocated BIGNUMS */ BIGNUM *Xpo = NULL, *Xqo = NULL, *tmp = NULL; /* Intermediate BIGNUMS that can be returned for testing */ BIGNUM *p1 = NULL, *p2 = NULL; BIGNUM *q1 = NULL, *q2 = NULL; /* Intermediate BIGNUMS that can be input for testing */ BIGNUM *Xpout = NULL, *Xqout = NULL; BIGNUM *Xp = NULL, *Xp1 = NULL, *Xp2 = NULL; BIGNUM *Xq = NULL, *Xq1 = NULL, *Xq2 = NULL; #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) if (test != NULL) { Xp1 = test->Xp1; Xp2 = test->Xp2; Xq1 = test->Xq1; Xq2 = test->Xq2; Xp = test->Xp; Xq = test->Xq; p1 = test->p1; p2 = test->p2; q1 = test->q1; q2 = test->q2; } #endif /* (Step 1) Check key length * NOTE: SP800-131A Rev1 Disallows key lengths of < 2048 bits for RSA * Signature Generation and Key Agree/Transport. */ if (nbits < RSA_FIPS1864_MIN_KEYGEN_KEYSIZE) { ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } if (!ossl_rsa_check_public_exponent(e)) { ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE); return 0; } /* (Step 3) Determine strength and check rand generator strength is ok - * this step is redundant because the generator always returns a higher * strength than is required. */ BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); Xpo = (Xpout != NULL) ? Xpout : BN_CTX_get(ctx); Xqo = (Xqout != NULL) ? Xqout : BN_CTX_get(ctx); if (tmp == NULL || Xpo == NULL || Xqo == NULL) goto err; BN_set_flags(Xpo, BN_FLG_CONSTTIME); BN_set_flags(Xqo, BN_FLG_CONSTTIME); if (rsa->p == NULL) rsa->p = BN_secure_new(); if (rsa->q == NULL) rsa->q = BN_secure_new(); if (rsa->p == NULL || rsa->q == NULL) goto err; BN_set_flags(rsa->p, BN_FLG_CONSTTIME); BN_set_flags(rsa->q, BN_FLG_CONSTTIME); /* (Step 4) Generate p, Xp */ if (!ossl_bn_rsa_fips186_4_gen_prob_primes(rsa->p, Xpo, p1, p2, Xp, Xp1, Xp2, nbits, e, ctx, cb)) goto err; for (;;) { /* (Step 5) Generate q, Xq*/ if (!ossl_bn_rsa_fips186_4_gen_prob_primes(rsa->q, Xqo, q1, q2, Xq, Xq1, Xq2, nbits, e, ctx, cb)) goto err; /* (Step 6) |Xp - Xq| > 2^(nbitlen/2 - 100) */ ok = ossl_rsa_check_pminusq_diff(tmp, Xpo, Xqo, nbits); if (ok < 0) goto err; if (ok == 0) continue; /* (Step 6) |p - q| > 2^(nbitlen/2 - 100) */ ok = ossl_rsa_check_pminusq_diff(tmp, rsa->p, rsa->q, nbits); if (ok < 0) goto err; if (ok == 0) continue; break; /* successfully finished */ } rsa->dirty_cnt++; ret = 1; err: /* Zeroize any internally generated values that are not returned */ if (Xpo != Xpout) BN_clear(Xpo); if (Xqo != Xqout) BN_clear(Xqo); BN_clear(tmp); BN_CTX_end(ctx); return ret; } /* * Validates the RSA key size based on the target strength. * See SP800-56Br1 6.3.1.1 (Steps 1a-1b) * * Params: * nbits The key size in bits. * strength The target strength in bits. -1 means the target * strength is unknown. * Returns: 1 if the key size matches the target strength, or 0 otherwise. */ int ossl_rsa_sp800_56b_validate_strength(int nbits, int strength) { int s = (int)ossl_ifc_ffc_compute_security_bits(nbits); #ifdef FIPS_MODULE if (s < RSA_FIPS1864_MIN_KEYGEN_STRENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MODULUS); return 0; } #endif if (strength != -1 && s != strength) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_STRENGTH); return 0; } return 1; } /* * Validate that the random bit generator is of sufficient strength to generate * a key of the specified length. */ static int rsa_validate_rng_strength(EVP_RAND_CTX *rng, int nbits) { if (rng == NULL) return 0; #ifdef FIPS_MODULE /* * This should become mainstream once similar tests are added to the other * key generations and once there is a way to disable these checks. */ if (EVP_RAND_get_strength(rng) < ossl_ifc_ffc_compute_security_bits(nbits)) { ERR_raise(ERR_LIB_RSA, RSA_R_RANDOMNESS_SOURCE_STRENGTH_INSUFFICIENT); return 0; } #endif return 1; } /* * * Using p & q, calculate other required parameters such as n, d. * as well as the CRT parameters dP, dQ, qInv. * * See SP800-56Br1 * 6.3.1.1 rsakpg1 - basic (Steps 3-4) * 6.3.1.3 rsakpg1 - crt (Step 5) * * Params: * rsa An rsa object. * nbits The key size. * e The public exponent. * ctx A BN_CTX object. * Notes: * There is a small chance that the generated d will be too small. * Returns: -1 = error, * 0 = d is too small, * 1 = success. */ int ossl_rsa_sp800_56b_derive_params_from_pq(RSA *rsa, int nbits, const BIGNUM *e, BN_CTX *ctx) { int ret = -1; BIGNUM *p1, *q1, *lcm, *p1q1, *gcd; BN_CTX_start(ctx); p1 = BN_CTX_get(ctx); q1 = BN_CTX_get(ctx); lcm = BN_CTX_get(ctx); p1q1 = BN_CTX_get(ctx); gcd = BN_CTX_get(ctx); if (gcd == NULL) goto err; BN_set_flags(p1, BN_FLG_CONSTTIME); BN_set_flags(q1, BN_FLG_CONSTTIME); BN_set_flags(lcm, BN_FLG_CONSTTIME); BN_set_flags(p1q1, BN_FLG_CONSTTIME); BN_set_flags(gcd, BN_FLG_CONSTTIME); /* LCM((p-1, q-1)) */ if (ossl_rsa_get_lcm(ctx, rsa->p, rsa->q, lcm, gcd, p1, q1, p1q1) != 1) goto err; /* copy e */ BN_free(rsa->e); rsa->e = BN_dup(e); if (rsa->e == NULL) goto err; BN_clear_free(rsa->d); /* (Step 3) d = (e^-1) mod (LCM(p-1, q-1)) */ rsa->d = BN_secure_new(); if (rsa->d == NULL) goto err; BN_set_flags(rsa->d, BN_FLG_CONSTTIME); if (BN_mod_inverse(rsa->d, e, lcm, ctx) == NULL) goto err; /* (Step 3) return an error if d is too small */ if (BN_num_bits(rsa->d) <= (nbits >> 1)) { ret = 0; goto err; } /* (Step 4) n = pq */ if (rsa->n == NULL) rsa->n = BN_new(); if (rsa->n == NULL || !BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; /* (Step 5a) dP = d mod (p-1) */ if (rsa->dmp1 == NULL) rsa->dmp1 = BN_secure_new(); if (rsa->dmp1 == NULL) goto err; BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME); if (!BN_mod(rsa->dmp1, rsa->d, p1, ctx)) goto err; /* (Step 5b) dQ = d mod (q-1) */ if (rsa->dmq1 == NULL) rsa->dmq1 = BN_secure_new(); if (rsa->dmq1 == NULL) goto err; BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME); if (!BN_mod(rsa->dmq1, rsa->d, q1, ctx)) goto err; /* (Step 5c) qInv = (inverse of q) mod p */ BN_free(rsa->iqmp); rsa->iqmp = BN_secure_new(); if (rsa->iqmp == NULL) goto err; BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME); if (BN_mod_inverse(rsa->iqmp, rsa->q, rsa->p, ctx) == NULL) goto err; rsa->dirty_cnt++; ret = 1; err: if (ret != 1) { BN_free(rsa->e); rsa->e = NULL; BN_free(rsa->d); rsa->d = NULL; BN_free(rsa->n); rsa->n = NULL; BN_free(rsa->iqmp); rsa->iqmp = NULL; BN_free(rsa->dmq1); rsa->dmq1 = NULL; BN_free(rsa->dmp1); rsa->dmp1 = NULL; } BN_clear(p1); BN_clear(q1); BN_clear(lcm); BN_clear(p1q1); BN_clear(gcd); BN_CTX_end(ctx); return ret; } /* * Generate a SP800-56B RSA key. * * See SP800-56Br1 6.3.1 "RSA Key-Pair Generation with a Fixed Public Exponent" * 6.3.1.1 rsakpg1 - basic * 6.3.1.3 rsakpg1 - crt * * See also FIPS 186-4 Section B.3.6 * "Generation of Probable Primes with Conditions Based on Auxiliary * Probable Primes." * * Params: * rsa The rsa object. * nbits The intended key size in bits. * efixed The public exponent. If NULL a default of 65537 is used. * cb An optional BIGNUM callback. * Returns: 1 if successfully generated otherwise it returns 0. */ int ossl_rsa_sp800_56b_generate_key(RSA *rsa, int nbits, const BIGNUM *efixed, BN_GENCB *cb) { int ret = 0; int ok; BN_CTX *ctx = NULL; BIGNUM *e = NULL; RSA_ACVP_TEST *info = NULL; BIGNUM *tmp; #if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) info = rsa->acvp_test; #endif /* (Steps 1a-1b) : Currently ignores the strength check */ if (!ossl_rsa_sp800_56b_validate_strength(nbits, -1)) return 0; /* Check that the RNG is capable of generating a key this large */ if (!rsa_validate_rng_strength(RAND_get0_private(rsa->libctx), nbits)) return 0; ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) return 0; /* Set default if e is not passed in */ if (efixed == NULL) { e = BN_new(); if (e == NULL || !BN_set_word(e, 65537)) goto err; } else { e = (BIGNUM *)efixed; } /* (Step 1c) fixed exponent is checked later .*/ for (;;) { /* (Step 2) Generate prime factors */ if (!ossl_rsa_fips186_4_gen_prob_primes(rsa, info, nbits, e, ctx, cb)) goto err; /* p>q check and skipping in case of acvp test */ if (info == NULL && BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* (Steps 3-5) Compute params d, n, dP, dQ, qInv */ ok = ossl_rsa_sp800_56b_derive_params_from_pq(rsa, nbits, e, ctx); if (ok < 0) goto err; if (ok > 0) break; /* Gets here if computed d is too small - so try again */ } /* (Step 6) Do pairwise test - optional validity test has been omitted */ ret = ossl_rsa_sp800_56b_pairwise_test(rsa, ctx); err: if (efixed == NULL) BN_free(e); BN_CTX_free(ctx); return ret; } /* * See SP800-56Br1 6.3.1.3 (Step 6) Perform a pair-wise consistency test by * verifying that: k = (k^e)^d mod n for some integer k where 1 < k < n-1. * * Returns 1 if the RSA key passes the pairwise test or 0 it it fails. */ int ossl_rsa_sp800_56b_pairwise_test(RSA *rsa, BN_CTX *ctx) { int ret = 0; BIGNUM *k, *tmp; BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); k = BN_CTX_get(ctx); if (k == NULL) goto err; BN_set_flags(k, BN_FLG_CONSTTIME); ret = (BN_set_word(k, 2) && BN_mod_exp(tmp, k, rsa->e, rsa->n, ctx) && BN_mod_exp(tmp, tmp, rsa->d, rsa->n, ctx) && BN_cmp(k, tmp) == 0); if (ret == 0) ERR_raise(ERR_LIB_RSA, RSA_R_PAIRWISE_TEST_FAILURE); err: BN_CTX_end(ctx); return ret; }
13,544
29.1
81
c
openssl
openssl-master/crypto/rsa/rsa_x931.c
/* * Copyright 2005-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/objects.h> int RSA_padding_add_X931(unsigned char *to, int tlen, const unsigned char *from, int flen) { int j; unsigned char *p; /* * Absolute minimum amount of padding is 1 header nibble, 1 padding * nibble and 2 trailer bytes: but 1 hash if is already in 'from'. */ j = tlen - flen - 2; if (j < 0) { ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return -1; } p = (unsigned char *)to; /* If no padding start and end nibbles are in one byte */ if (j == 0) { *p++ = 0x6A; } else { *p++ = 0x6B; if (j > 1) { memset(p, 0xBB, j - 1); p += j - 1; } *p++ = 0xBA; } memcpy(p, from, (unsigned int)flen); p += flen; *p = 0xCC; return 1; } int RSA_padding_check_X931(unsigned char *to, int tlen, const unsigned char *from, int flen, int num) { int i = 0, j; const unsigned char *p; p = from; if ((num != flen) || ((*p != 0x6A) && (*p != 0x6B))) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_HEADER); return -1; } if (*p++ == 0x6B) { j = flen - 3; for (i = 0; i < j; i++) { unsigned char c = *p++; if (c == 0xBA) break; if (c != 0xBB) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING); return -1; } } j -= i; if (i == 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING); return -1; } } else { j = flen - 2; } if (p[j] != 0xCC) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_TRAILER); return -1; } memcpy(to, p, (unsigned int)j); return j; } /* Translate between X931 hash ids and NIDs */ int RSA_X931_hash_id(int nid) { switch (nid) { case NID_sha1: return 0x33; case NID_sha256: return 0x34; case NID_sha384: return 0x36; case NID_sha512: return 0x35; } return -1; }
2,678
20.604839
74
c
openssl
openssl-master/crypto/rsa/rsa_x931g.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <string.h> #include <time.h> #include <openssl/err.h> #include <openssl/bn.h> #include "rsa_local.h" /* X9.31 RSA key derivation and generation */ int RSA_X931_derive_ex(RSA *rsa, BIGNUM *p1, BIGNUM *p2, BIGNUM *q1, BIGNUM *q2, const BIGNUM *Xp1, const BIGNUM *Xp2, const BIGNUM *Xp, const BIGNUM *Xq1, const BIGNUM *Xq2, const BIGNUM *Xq, const BIGNUM *e, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL; BN_CTX *ctx = NULL, *ctx2 = NULL; int ret = 0; if (rsa == NULL) goto err; ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); r3 = BN_CTX_get(ctx); if (r3 == NULL) goto err; if (!rsa->e) { rsa->e = BN_dup(e); if (!rsa->e) goto err; } else { e = rsa->e; } /* * If not all parameters present only calculate what we can. This allows * test programs to output selective parameters. */ if (Xp && rsa->p == NULL) { rsa->p = BN_new(); if (rsa->p == NULL) goto err; if (!BN_X931_derive_prime_ex(rsa->p, p1, p2, Xp, Xp1, Xp2, e, ctx, cb)) goto err; } if (Xq && rsa->q == NULL) { rsa->q = BN_new(); if (rsa->q == NULL) goto err; if (!BN_X931_derive_prime_ex(rsa->q, q1, q2, Xq, Xq1, Xq2, e, ctx, cb)) goto err; } if (rsa->p == NULL || rsa->q == NULL) { BN_CTX_end(ctx); BN_CTX_free(ctx); return 2; } /* * Since both primes are set we can now calculate all remaining * components. */ /* calculate n */ rsa->n = BN_new(); if (rsa->n == NULL) goto err; if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; /* calculate d */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* p-1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* q-1 */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* (p-1)(q-1) */ if (!BN_gcd(r3, r1, r2, ctx)) goto err; if (!BN_div(r0, NULL, r0, r3, ctx)) goto err; /* LCM((p-1)(q-1)) */ ctx2 = BN_CTX_new(); if (ctx2 == NULL) goto err; rsa->d = BN_mod_inverse(NULL, rsa->e, r0, ctx2); /* d */ if (rsa->d == NULL) goto err; /* calculate d mod (p-1) */ rsa->dmp1 = BN_new(); if (rsa->dmp1 == NULL) goto err; if (!BN_mod(rsa->dmp1, rsa->d, r1, ctx)) goto err; /* calculate d mod (q-1) */ rsa->dmq1 = BN_new(); if (rsa->dmq1 == NULL) goto err; if (!BN_mod(rsa->dmq1, rsa->d, r2, ctx)) goto err; /* calculate inverse of q mod p */ rsa->iqmp = BN_mod_inverse(NULL, rsa->q, rsa->p, ctx2); if (rsa->iqmp == NULL) goto err; rsa->dirty_cnt++; ret = 1; err: BN_CTX_end(ctx); BN_CTX_free(ctx); BN_CTX_free(ctx2); return ret; } int RSA_X931_generate_key_ex(RSA *rsa, int bits, const BIGNUM *e, BN_GENCB *cb) { int ok = 0; BIGNUM *Xp = NULL, *Xq = NULL; BN_CTX *ctx = NULL; ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) goto error; BN_CTX_start(ctx); Xp = BN_CTX_get(ctx); Xq = BN_CTX_get(ctx); if (Xq == NULL) goto error; if (!BN_X931_generate_Xpq(Xp, Xq, bits, ctx)) goto error; rsa->p = BN_new(); rsa->q = BN_new(); if (rsa->p == NULL || rsa->q == NULL) goto error; /* Generate two primes from Xp, Xq */ if (!BN_X931_generate_prime_ex(rsa->p, NULL, NULL, NULL, NULL, Xp, e, ctx, cb)) goto error; if (!BN_X931_generate_prime_ex(rsa->q, NULL, NULL, NULL, NULL, Xq, e, ctx, cb)) goto error; /* * Since rsa->p and rsa->q are valid this call will just derive remaining * RSA components. */ if (!RSA_X931_derive_ex(rsa, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, e, cb)) goto error; rsa->dirty_cnt++; ok = 1; error: BN_CTX_end(ctx); BN_CTX_free(ctx); if (ok) return 1; return 0; }
4,992
23.237864
78
c
openssl
openssl-master/crypto/seed/seed_cbc.c
/* * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * SEED low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/seed.h> #include <openssl/modes.h> void SEED_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const SEED_KEY_SCHEDULE *ks, unsigned char ivec[SEED_BLOCK_SIZE], int enc) { if (enc) CRYPTO_cbc128_encrypt(in, out, len, ks, ivec, (block128_f) SEED_encrypt); else CRYPTO_cbc128_decrypt(in, out, len, ks, ivec, (block128_f) SEED_decrypt); }
968
31.3
74
c
openssl
openssl-master/crypto/seed/seed_cfb.c
/* * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * SEED low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/seed.h> #include <openssl/modes.h> void SEED_cfb128_encrypt(const unsigned char *in, unsigned char *out, size_t len, const SEED_KEY_SCHEDULE *ks, unsigned char ivec[SEED_BLOCK_SIZE], int *num, int enc) { CRYPTO_cfb128_encrypt(in, out, len, ks, ivec, num, enc, (block128_f) SEED_encrypt); }
880
31.62963
74
c
openssl
openssl-master/crypto/seed/seed_ecb.c
/* * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * SEED low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/seed.h> void SEED_ecb_encrypt(const unsigned char *in, unsigned char *out, const SEED_KEY_SCHEDULE *ks, int enc) { if (enc) SEED_encrypt(in, out, ks); else SEED_decrypt(in, out, ks); }
716
26.576923
74
c
openssl
openssl-master/crypto/seed/seed_local.h
/* * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Copyright (c) 2007 KISA(Korea Information Security Agency). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Neither the name of author nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef OSSL_CRYPTO_SEED_LOCAL_H # define OSSL_CRYPTO_SEED_LOCAL_H # include <openssl/e_os2.h> # include <openssl/seed.h> # ifdef SEED_LONG /* need 32-bit type */ typedef unsigned long seed_word; # else typedef unsigned int seed_word; # endif # define char2word(c, i) \ (i) = ((((seed_word)(c)[0]) << 24) | (((seed_word)(c)[1]) << 16) | (((seed_word)(c)[2]) << 8) | ((seed_word)(c)[3])) # define word2char(l, c) \ *((c)+0) = (unsigned char)((l)>>24) & 0xff; \ *((c)+1) = (unsigned char)((l)>>16) & 0xff; \ *((c)+2) = (unsigned char)((l)>> 8) & 0xff; \ *((c)+3) = (unsigned char)((l)) & 0xff # define KEYSCHEDULE_UPDATE0(T0, T1, X1, X2, X3, X4, KC) \ (T0) = (X3); \ (X3) = (((X3)<<8) ^ ((X4)>>24)) & 0xffffffff; \ (X4) = (((X4)<<8) ^ ((T0)>>24)) & 0xffffffff; \ (T0) = ((X1) + (X3) - (KC)) & 0xffffffff; \ (T1) = ((X2) + (KC) - (X4)) & 0xffffffff # define KEYSCHEDULE_UPDATE1(T0, T1, X1, X2, X3, X4, KC) \ (T0) = (X1); \ (X1) = (((X1)>>8) ^ ((X2)<<24)) & 0xffffffff; \ (X2) = (((X2)>>8) ^ ((T0)<<24)) & 0xffffffff; \ (T0) = ((X1) + (X3) - (KC)) & 0xffffffff; \ (T1) = ((X2) + (KC) - (X4)) & 0xffffffff # define KEYUPDATE_TEMP(T0, T1, K) \ (K)[0] = G_FUNC((T0)); \ (K)[1] = G_FUNC((T1)) # define XOR_SEEDBLOCK(DST, SRC) \ ((DST))[0] ^= ((SRC))[0]; \ ((DST))[1] ^= ((SRC))[1]; \ ((DST))[2] ^= ((SRC))[2]; \ ((DST))[3] ^= ((SRC))[3] # define MOV_SEEDBLOCK(DST, SRC) \ ((DST))[0] = ((SRC))[0]; \ ((DST))[1] = ((SRC))[1]; \ ((DST))[2] = ((SRC))[2]; \ ((DST))[3] = ((SRC))[3] # define CHAR2WORD(C, I) \ char2word((C), (I)[0]); \ char2word((C+4), (I)[1]); \ char2word((C+8), (I)[2]); \ char2word((C+12), (I)[3]) # define WORD2CHAR(I, C) \ word2char((I)[0], (C)); \ word2char((I)[1], (C+4)); \ word2char((I)[2], (C+8)); \ word2char((I)[3], (C+12)) # define E_SEED(T0, T1, X1, X2, X3, X4, rbase) \ (T0) = (X3) ^ (ks->data)[(rbase)]; \ (T1) = (X4) ^ (ks->data)[(rbase)+1]; \ (T1) ^= (T0); \ (T1) = G_FUNC((T1)); \ (T0) = ((T0) + (T1)) & 0xffffffff; \ (T0) = G_FUNC((T0)); \ (T1) = ((T1) + (T0)) & 0xffffffff; \ (T1) = G_FUNC((T1)); \ (T0) = ((T0) + (T1)) & 0xffffffff; \ (X1) ^= (T0); \ (X2) ^= (T1) #endif /* OSSL_CRYPTO_SEED_LOCAL_H */
4,564
39.39823
124
h
openssl
openssl-master/crypto/seed/seed_ofb.c
/* * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * SEED low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/seed.h> #include <openssl/modes.h> void SEED_ofb128_encrypt(const unsigned char *in, unsigned char *out, size_t len, const SEED_KEY_SCHEDULE *ks, unsigned char ivec[SEED_BLOCK_SIZE], int *num) { CRYPTO_ofb128_encrypt(in, out, len, ks, ivec, num, (block128_f) SEED_encrypt); }
841
31.384615
74
c
openssl
openssl-master/crypto/sha/sha1_one.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * SHA-1 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/crypto.h> #include <openssl/sha.h> #include <openssl/evp.h> #include "crypto/sha.h" unsigned char *ossl_sha1(const unsigned char *d, size_t n, unsigned char *md) { SHA_CTX c; static unsigned char m[SHA_DIGEST_LENGTH]; if (md == NULL) md = m; if (!SHA1_Init(&c)) return NULL; SHA1_Update(&c, d, n); SHA1_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); return md; } unsigned char *SHA1(const unsigned char *d, size_t n, unsigned char *md) { static unsigned char m[SHA_DIGEST_LENGTH]; if (md == NULL) md = m; return EVP_Q_digest(NULL, "SHA1", NULL, d, n, md, NULL) ? md : NULL; } unsigned char *SHA224(const unsigned char *d, size_t n, unsigned char *md) { static unsigned char m[SHA224_DIGEST_LENGTH]; if (md == NULL) md = m; return EVP_Q_digest(NULL, "SHA224", NULL, d, n, md, NULL) ? md : NULL; } unsigned char *SHA256(const unsigned char *d, size_t n, unsigned char *md) { static unsigned char m[SHA256_DIGEST_LENGTH]; if (md == NULL) md = m; return EVP_Q_digest(NULL, "SHA256", NULL, d, n, md, NULL) ? md : NULL; } unsigned char *SHA384(const unsigned char *d, size_t n, unsigned char *md) { static unsigned char m[SHA384_DIGEST_LENGTH]; if (md == NULL) md = m; return EVP_Q_digest(NULL, "SHA384", NULL, d, n, md, NULL) ? md : NULL; } unsigned char *SHA512(const unsigned char *d, size_t n, unsigned char *md) { static unsigned char m[SHA512_DIGEST_LENGTH]; if (md == NULL) md = m; return EVP_Q_digest(NULL, "SHA512", NULL, d, n, md, NULL) ? md : NULL; }
2,140
25.109756
77
c
openssl
openssl-master/crypto/sha/sha1dgst.c
/* * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * SHA-1 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/crypto.h> #include <openssl/opensslconf.h> #include <openssl/opensslv.h> #include <openssl/evp.h> #include <openssl/sha.h> /* The implementation is in crypto/md32_common.h */ #include "sha_local.h" #include "crypto/sha.h" int ossl_sha1_ctrl(SHA_CTX *sha1, int cmd, int mslen, void *ms) { unsigned char padtmp[40]; unsigned char sha1tmp[SHA_DIGEST_LENGTH]; if (cmd != EVP_CTRL_SSL3_MASTER_SECRET) return -2; if (sha1 == NULL) return 0; /* SSLv3 client auth handling: see RFC-6101 5.6.8 */ if (mslen != 48) return 0; /* At this point hash contains all handshake messages, update * with master secret and pad_1. */ if (SHA1_Update(sha1, ms, mslen) <= 0) return 0; /* Set padtmp to pad_1 value */ memset(padtmp, 0x36, sizeof(padtmp)); if (!SHA1_Update(sha1, padtmp, sizeof(padtmp))) return 0; if (!SHA1_Final(sha1tmp, sha1)) return 0; /* Reinitialise context */ if (!SHA1_Init(sha1)) return 0; if (SHA1_Update(sha1, ms, mslen) <= 0) return 0; /* Set padtmp to pad_2 value */ memset(padtmp, 0x5c, sizeof(padtmp)); if (!SHA1_Update(sha1, padtmp, sizeof(padtmp))) return 0; if (!SHA1_Update(sha1, sha1tmp, sizeof(sha1tmp))) return 0; /* Now when ctx is finalised it will return the SSL v3 hash value */ OPENSSL_cleanse(sha1tmp, sizeof(sha1tmp)); return 1; }
1,934
22.888889
74
c
openssl
openssl-master/crypto/sha/sha256.c
/* * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * SHA256 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslconf.h> #include <stdlib.h> #include <string.h> #include <openssl/crypto.h> #include <openssl/sha.h> #include <openssl/opensslv.h> #include "internal/endian.h" #include "crypto/sha.h" int SHA224_Init(SHA256_CTX *c) { memset(c, 0, sizeof(*c)); c->h[0] = 0xc1059ed8UL; c->h[1] = 0x367cd507UL; c->h[2] = 0x3070dd17UL; c->h[3] = 0xf70e5939UL; c->h[4] = 0xffc00b31UL; c->h[5] = 0x68581511UL; c->h[6] = 0x64f98fa7UL; c->h[7] = 0xbefa4fa4UL; c->md_len = SHA224_DIGEST_LENGTH; return 1; } int SHA256_Init(SHA256_CTX *c) { memset(c, 0, sizeof(*c)); c->h[0] = 0x6a09e667UL; c->h[1] = 0xbb67ae85UL; c->h[2] = 0x3c6ef372UL; c->h[3] = 0xa54ff53aUL; c->h[4] = 0x510e527fUL; c->h[5] = 0x9b05688cUL; c->h[6] = 0x1f83d9abUL; c->h[7] = 0x5be0cd19UL; c->md_len = SHA256_DIGEST_LENGTH; return 1; } int ossl_sha256_192_init(SHA256_CTX *c) { SHA256_Init(c); c->md_len = SHA256_192_DIGEST_LENGTH; return 1; } int SHA224_Update(SHA256_CTX *c, const void *data, size_t len) { return SHA256_Update(c, data, len); } int SHA224_Final(unsigned char *md, SHA256_CTX *c) { return SHA256_Final(md, c); } #define DATA_ORDER_IS_BIG_ENDIAN #define HASH_LONG SHA_LONG #define HASH_CTX SHA256_CTX #define HASH_CBLOCK SHA_CBLOCK /* * Note that FIPS180-2 discusses "Truncation of the Hash Function Output." * default: case below covers for it. It's not clear however if it's * permitted to truncate to amount of bytes not divisible by 4. I bet not, * but if it is, then default: case shall be extended. For reference. * Idea behind separate cases for pre-defined lengths is to let the * compiler decide if it's appropriate to unroll small loops. */ #define HASH_MAKE_STRING(c,s) do { \ unsigned long ll; \ unsigned int nn; \ switch ((c)->md_len) \ { case SHA256_192_DIGEST_LENGTH: \ for (nn=0;nn<SHA256_192_DIGEST_LENGTH/4;nn++) \ { ll=(c)->h[nn]; (void)HOST_l2c(ll,(s)); } \ break; \ case SHA224_DIGEST_LENGTH: \ for (nn=0;nn<SHA224_DIGEST_LENGTH/4;nn++) \ { ll=(c)->h[nn]; (void)HOST_l2c(ll,(s)); } \ break; \ case SHA256_DIGEST_LENGTH: \ for (nn=0;nn<SHA256_DIGEST_LENGTH/4;nn++) \ { ll=(c)->h[nn]; (void)HOST_l2c(ll,(s)); } \ break; \ default: \ if ((c)->md_len > SHA256_DIGEST_LENGTH) \ return 0; \ for (nn=0;nn<(c)->md_len/4;nn++) \ { ll=(c)->h[nn]; (void)HOST_l2c(ll,(s)); } \ break; \ } \ } while (0) #define HASH_UPDATE SHA256_Update #define HASH_TRANSFORM SHA256_Transform #define HASH_FINAL SHA256_Final #define HASH_BLOCK_DATA_ORDER sha256_block_data_order #ifndef SHA256_ASM static #endif void sha256_block_data_order(SHA256_CTX *ctx, const void *in, size_t num); #include "crypto/md32_common.h" #ifndef SHA256_ASM static const SHA_LONG K256[64] = { 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL }; # ifndef PEDANTIC # if defined(__GNUC__) && __GNUC__>=2 && \ !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if defined(__riscv_zknh) # define Sigma0(x) ({ MD32_REG_T ret; \ asm ("sha256sum0 %0, %1" \ : "=r"(ret) \ : "r"(x)); ret; }) # define Sigma1(x) ({ MD32_REG_T ret; \ asm ("sha256sum1 %0, %1" \ : "=r"(ret) \ : "r"(x)); ret; }) # define sigma0(x) ({ MD32_REG_T ret; \ asm ("sha256sig0 %0, %1" \ : "=r"(ret) \ : "r"(x)); ret; }) # define sigma1(x) ({ MD32_REG_T ret; \ asm ("sha256sig1 %0, %1" \ : "=r"(ret) \ : "r"(x)); ret; }) # endif # if defined(__riscv_zbt) || defined(__riscv_zpn) # define Ch(x,y,z) ({ MD32_REG_T ret; \ asm (".insn r4 0x33, 1, 0x3, %0, %2, %1, %3"\ : "=r"(ret) \ : "r"(x), "r"(y), "r"(z)); ret; }) # define Maj(x,y,z) ({ MD32_REG_T ret; \ asm (".insn r4 0x33, 1, 0x3, %0, %2, %1, %3"\ : "=r"(ret) \ : "r"(x^z), "r"(y), "r"(x)); ret; }) # endif # endif # endif /* * FIPS specification refers to right rotations, while our ROTATE macro * is left one. This is why you might notice that rotation coefficients * differ from those observed in FIPS document by 32-N... */ # ifndef Sigma0 # define Sigma0(x) (ROTATE((x),30) ^ ROTATE((x),19) ^ ROTATE((x),10)) # endif # ifndef Sigma1 # define Sigma1(x) (ROTATE((x),26) ^ ROTATE((x),21) ^ ROTATE((x),7)) # endif # ifndef sigma0 # define sigma0(x) (ROTATE((x),25) ^ ROTATE((x),14) ^ ((x)>>3)) # endif # ifndef sigma1 # define sigma1(x) (ROTATE((x),15) ^ ROTATE((x),13) ^ ((x)>>10)) # endif # ifndef Ch # define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) # endif # ifndef Maj # define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) # endif # ifdef OPENSSL_SMALL_FOOTPRINT static void sha256_block_data_order(SHA256_CTX *ctx, const void *in, size_t num) { unsigned MD32_REG_T a, b, c, d, e, f, g, h, s0, s1, T1, T2; SHA_LONG X[16], l; int i; const unsigned char *data = in; while (num--) { a = ctx->h[0]; b = ctx->h[1]; c = ctx->h[2]; d = ctx->h[3]; e = ctx->h[4]; f = ctx->h[5]; g = ctx->h[6]; h = ctx->h[7]; for (i = 0; i < 16; i++) { (void)HOST_c2l(data, l); T1 = X[i] = l; T1 += h + Sigma1(e) + Ch(e, f, g) + K256[i]; T2 = Sigma0(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } for (; i < 64; i++) { s0 = X[(i + 1) & 0x0f]; s0 = sigma0(s0); s1 = X[(i + 14) & 0x0f]; s1 = sigma1(s1); T1 = X[i & 0xf] += s0 + s1 + X[(i + 9) & 0xf]; T1 += h + Sigma1(e) + Ch(e, f, g) + K256[i]; T2 = Sigma0(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } ctx->h[0] += a; ctx->h[1] += b; ctx->h[2] += c; ctx->h[3] += d; ctx->h[4] += e; ctx->h[5] += f; ctx->h[6] += g; ctx->h[7] += h; } } # else # define ROUND_00_15(i,a,b,c,d,e,f,g,h) do { \ T1 += h + Sigma1(e) + Ch(e,f,g) + K256[i]; \ h = Sigma0(a) + Maj(a,b,c); \ d += T1; h += T1; } while (0) # define ROUND_16_63(i,a,b,c,d,e,f,g,h,X) do { \ s0 = X[(i+1)&0x0f]; s0 = sigma0(s0); \ s1 = X[(i+14)&0x0f]; s1 = sigma1(s1); \ T1 = X[(i)&0x0f] += s0 + s1 + X[(i+9)&0x0f]; \ ROUND_00_15(i,a,b,c,d,e,f,g,h); } while (0) static void sha256_block_data_order(SHA256_CTX *ctx, const void *in, size_t num) { unsigned MD32_REG_T a, b, c, d, e, f, g, h, s0, s1, T1; SHA_LONG X[16]; int i; const unsigned char *data = in; DECLARE_IS_ENDIAN; while (num--) { a = ctx->h[0]; b = ctx->h[1]; c = ctx->h[2]; d = ctx->h[3]; e = ctx->h[4]; f = ctx->h[5]; g = ctx->h[6]; h = ctx->h[7]; if (!IS_LITTLE_ENDIAN && sizeof(SHA_LONG) == 4 && ((size_t)in % 4) == 0) { const SHA_LONG *W = (const SHA_LONG *)data; T1 = X[0] = W[0]; ROUND_00_15(0, a, b, c, d, e, f, g, h); T1 = X[1] = W[1]; ROUND_00_15(1, h, a, b, c, d, e, f, g); T1 = X[2] = W[2]; ROUND_00_15(2, g, h, a, b, c, d, e, f); T1 = X[3] = W[3]; ROUND_00_15(3, f, g, h, a, b, c, d, e); T1 = X[4] = W[4]; ROUND_00_15(4, e, f, g, h, a, b, c, d); T1 = X[5] = W[5]; ROUND_00_15(5, d, e, f, g, h, a, b, c); T1 = X[6] = W[6]; ROUND_00_15(6, c, d, e, f, g, h, a, b); T1 = X[7] = W[7]; ROUND_00_15(7, b, c, d, e, f, g, h, a); T1 = X[8] = W[8]; ROUND_00_15(8, a, b, c, d, e, f, g, h); T1 = X[9] = W[9]; ROUND_00_15(9, h, a, b, c, d, e, f, g); T1 = X[10] = W[10]; ROUND_00_15(10, g, h, a, b, c, d, e, f); T1 = X[11] = W[11]; ROUND_00_15(11, f, g, h, a, b, c, d, e); T1 = X[12] = W[12]; ROUND_00_15(12, e, f, g, h, a, b, c, d); T1 = X[13] = W[13]; ROUND_00_15(13, d, e, f, g, h, a, b, c); T1 = X[14] = W[14]; ROUND_00_15(14, c, d, e, f, g, h, a, b); T1 = X[15] = W[15]; ROUND_00_15(15, b, c, d, e, f, g, h, a); data += SHA256_CBLOCK; } else { SHA_LONG l; (void)HOST_c2l(data, l); T1 = X[0] = l; ROUND_00_15(0, a, b, c, d, e, f, g, h); (void)HOST_c2l(data, l); T1 = X[1] = l; ROUND_00_15(1, h, a, b, c, d, e, f, g); (void)HOST_c2l(data, l); T1 = X[2] = l; ROUND_00_15(2, g, h, a, b, c, d, e, f); (void)HOST_c2l(data, l); T1 = X[3] = l; ROUND_00_15(3, f, g, h, a, b, c, d, e); (void)HOST_c2l(data, l); T1 = X[4] = l; ROUND_00_15(4, e, f, g, h, a, b, c, d); (void)HOST_c2l(data, l); T1 = X[5] = l; ROUND_00_15(5, d, e, f, g, h, a, b, c); (void)HOST_c2l(data, l); T1 = X[6] = l; ROUND_00_15(6, c, d, e, f, g, h, a, b); (void)HOST_c2l(data, l); T1 = X[7] = l; ROUND_00_15(7, b, c, d, e, f, g, h, a); (void)HOST_c2l(data, l); T1 = X[8] = l; ROUND_00_15(8, a, b, c, d, e, f, g, h); (void)HOST_c2l(data, l); T1 = X[9] = l; ROUND_00_15(9, h, a, b, c, d, e, f, g); (void)HOST_c2l(data, l); T1 = X[10] = l; ROUND_00_15(10, g, h, a, b, c, d, e, f); (void)HOST_c2l(data, l); T1 = X[11] = l; ROUND_00_15(11, f, g, h, a, b, c, d, e); (void)HOST_c2l(data, l); T1 = X[12] = l; ROUND_00_15(12, e, f, g, h, a, b, c, d); (void)HOST_c2l(data, l); T1 = X[13] = l; ROUND_00_15(13, d, e, f, g, h, a, b, c); (void)HOST_c2l(data, l); T1 = X[14] = l; ROUND_00_15(14, c, d, e, f, g, h, a, b); (void)HOST_c2l(data, l); T1 = X[15] = l; ROUND_00_15(15, b, c, d, e, f, g, h, a); } for (i = 16; i < 64; i += 8) { ROUND_16_63(i + 0, a, b, c, d, e, f, g, h, X); ROUND_16_63(i + 1, h, a, b, c, d, e, f, g, X); ROUND_16_63(i + 2, g, h, a, b, c, d, e, f, X); ROUND_16_63(i + 3, f, g, h, a, b, c, d, e, X); ROUND_16_63(i + 4, e, f, g, h, a, b, c, d, X); ROUND_16_63(i + 5, d, e, f, g, h, a, b, c, X); ROUND_16_63(i + 6, c, d, e, f, g, h, a, b, X); ROUND_16_63(i + 7, b, c, d, e, f, g, h, a, X); } ctx->h[0] += a; ctx->h[1] += b; ctx->h[2] += c; ctx->h[3] += d; ctx->h[4] += e; ctx->h[5] += f; ctx->h[6] += g; ctx->h[7] += h; } } # endif #endif /* SHA256_ASM */
14,081
32.688995
76
c
openssl
openssl-master/crypto/sha/sha3.c
/* * Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include "internal/sha3.h" void SHA3_squeeze(uint64_t A[5][5], unsigned char *out, size_t len, size_t r); void ossl_sha3_reset(KECCAK1600_CTX *ctx) { memset(ctx->A, 0, sizeof(ctx->A)); ctx->bufsz = 0; } int ossl_sha3_init(KECCAK1600_CTX *ctx, unsigned char pad, size_t bitlen) { size_t bsz = SHA3_BLOCKSIZE(bitlen); if (bsz <= sizeof(ctx->buf)) { ossl_sha3_reset(ctx); ctx->block_size = bsz; ctx->md_size = bitlen / 8; ctx->pad = pad; return 1; } return 0; } int ossl_keccak_kmac_init(KECCAK1600_CTX *ctx, unsigned char pad, size_t bitlen) { int ret = ossl_sha3_init(ctx, pad, bitlen); if (ret) ctx->md_size *= 2; return ret; } int ossl_sha3_update(KECCAK1600_CTX *ctx, const void *_inp, size_t len) { const unsigned char *inp = _inp; size_t bsz = ctx->block_size; size_t num, rem; if (len == 0) return 1; if ((num = ctx->bufsz) != 0) { /* process intermediate buffer? */ rem = bsz - num; if (len < rem) { memcpy(ctx->buf + num, inp, len); ctx->bufsz += len; return 1; } /* * We have enough data to fill or overflow the intermediate * buffer. So we append |rem| bytes and process the block, * leaving the rest for later processing... */ memcpy(ctx->buf + num, inp, rem); inp += rem, len -= rem; (void)SHA3_absorb(ctx->A, ctx->buf, bsz, bsz); ctx->bufsz = 0; /* ctx->buf is processed, ctx->num is guaranteed to be zero */ } if (len >= bsz) rem = SHA3_absorb(ctx->A, inp, len, bsz); else rem = len; if (rem) { memcpy(ctx->buf, inp + len - rem, rem); ctx->bufsz = rem; } return 1; } int ossl_sha3_final(unsigned char *md, KECCAK1600_CTX *ctx) { size_t bsz = ctx->block_size; size_t num = ctx->bufsz; if (ctx->md_size == 0) return 1; /* * Pad the data with 10*1. Note that |num| can be |bsz - 1| * in which case both byte operations below are performed on * same byte... */ memset(ctx->buf + num, 0, bsz - num); ctx->buf[num] = ctx->pad; ctx->buf[bsz - 1] |= 0x80; (void)SHA3_absorb(ctx->A, ctx->buf, bsz, bsz); SHA3_squeeze(ctx->A, md, ctx->md_size, bsz); return 1; }
2,727
23.8
80
c
openssl
openssl-master/crypto/sha/sha_local.h
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/sha.h> #include "internal/endian.h" #define DATA_ORDER_IS_BIG_ENDIAN #define HASH_LONG SHA_LONG #define HASH_CTX SHA_CTX #define HASH_CBLOCK SHA_CBLOCK #define HASH_MAKE_STRING(c,s) do { \ unsigned long ll; \ ll=(c)->h0; (void)HOST_l2c(ll,(s)); \ ll=(c)->h1; (void)HOST_l2c(ll,(s)); \ ll=(c)->h2; (void)HOST_l2c(ll,(s)); \ ll=(c)->h3; (void)HOST_l2c(ll,(s)); \ ll=(c)->h4; (void)HOST_l2c(ll,(s)); \ } while (0) #define HASH_UPDATE SHA1_Update #define HASH_TRANSFORM SHA1_Transform #define HASH_FINAL SHA1_Final #define HASH_INIT SHA1_Init #define HASH_BLOCK_DATA_ORDER sha1_block_data_order #define Xupdate(a,ix,ia,ib,ic,id) ( (a)=(ia^ib^ic^id), \ ix=(a)=ROTATE((a),1) \ ) #ifndef SHA1_ASM static void sha1_block_data_order(SHA_CTX *c, const void *p, size_t num); #else void sha1_block_data_order(SHA_CTX *c, const void *p, size_t num); #endif #include "crypto/md32_common.h" #define INIT_DATA_h0 0x67452301UL #define INIT_DATA_h1 0xefcdab89UL #define INIT_DATA_h2 0x98badcfeUL #define INIT_DATA_h3 0x10325476UL #define INIT_DATA_h4 0xc3d2e1f0UL int HASH_INIT(SHA_CTX *c) { memset(c, 0, sizeof(*c)); c->h0 = INIT_DATA_h0; c->h1 = INIT_DATA_h1; c->h2 = INIT_DATA_h2; c->h3 = INIT_DATA_h3; c->h4 = INIT_DATA_h4; return 1; } #define K_00_19 0x5a827999UL #define K_20_39 0x6ed9eba1UL #define K_40_59 0x8f1bbcdcUL #define K_60_79 0xca62c1d6UL /* * As pointed out by Wei Dai, F() below can be simplified to the code in * F_00_19. Wei attributes these optimizations to Peter Gutmann's SHS code, * and he attributes it to Rich Schroeppel. * #define F(x,y,z) (((x) & (y)) | ((~(x)) & (z))) * I've just become aware of another tweak to be made, again from Wei Dai, * in F_40_59, (x&a)|(y&a) -> (x|y)&a */ #define F_00_19(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) #define F_20_39(b,c,d) ((b) ^ (c) ^ (d)) #define F_40_59(b,c,d) (((b) & (c)) | (((b)|(c)) & (d))) #define F_60_79(b,c,d) F_20_39(b,c,d) #ifndef OPENSSL_SMALL_FOOTPRINT # define BODY_00_15(i,a,b,c,d,e,f,xi) \ (f)=xi+(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ (b)=ROTATE((b),30); # define BODY_16_19(i,a,b,c,d,e,f,xi,xa,xb,xc,xd) \ Xupdate(f,xi,xa,xb,xc,xd); \ (f)+=(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ (b)=ROTATE((b),30); # define BODY_20_31(i,a,b,c,d,e,f,xi,xa,xb,xc,xd) \ Xupdate(f,xi,xa,xb,xc,xd); \ (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ (b)=ROTATE((b),30); # define BODY_32_39(i,a,b,c,d,e,f,xa,xb,xc,xd) \ Xupdate(f,xa,xa,xb,xc,xd); \ (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ (b)=ROTATE((b),30); # define BODY_40_59(i,a,b,c,d,e,f,xa,xb,xc,xd) \ Xupdate(f,xa,xa,xb,xc,xd); \ (f)+=(e)+K_40_59+ROTATE((a),5)+F_40_59((b),(c),(d)); \ (b)=ROTATE((b),30); # define BODY_60_79(i,a,b,c,d,e,f,xa,xb,xc,xd) \ Xupdate(f,xa,xa,xb,xc,xd); \ (f)=xa+(e)+K_60_79+ROTATE((a),5)+F_60_79((b),(c),(d)); \ (b)=ROTATE((b),30); # ifdef X # undef X # endif # ifndef MD32_XARRAY /* * Originally X was an array. As it's automatic it's natural * to expect RISC compiler to accommodate at least part of it in * the register bank, isn't it? Unfortunately not all compilers * "find" this expectation reasonable:-( On order to make such * compilers generate better code I replace X[] with a bunch of * X0, X1, etc. See the function body below... */ # define X(i) XX##i # else /* * However! Some compilers (most notably HP C) get overwhelmed by * that many local variables so that we have to have the way to * fall down to the original behavior. */ # define X(i) XX[i] # endif # if !defined(SHA1_ASM) static void HASH_BLOCK_DATA_ORDER(SHA_CTX *c, const void *p, size_t num) { const unsigned char *data = p; register unsigned MD32_REG_T A, B, C, D, E, T, l; # ifndef MD32_XARRAY unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, XX8, XX9, XX10, XX11, XX12, XX13, XX14, XX15; # else SHA_LONG XX[16]; # endif A = c->h0; B = c->h1; C = c->h2; D = c->h3; E = c->h4; for (;;) { DECLARE_IS_ENDIAN; if (!IS_LITTLE_ENDIAN && sizeof(SHA_LONG) == 4 && ((size_t)p % 4) == 0) { const SHA_LONG *W = (const SHA_LONG *)data; X(0) = W[0]; X(1) = W[1]; BODY_00_15(0, A, B, C, D, E, T, X(0)); X(2) = W[2]; BODY_00_15(1, T, A, B, C, D, E, X(1)); X(3) = W[3]; BODY_00_15(2, E, T, A, B, C, D, X(2)); X(4) = W[4]; BODY_00_15(3, D, E, T, A, B, C, X(3)); X(5) = W[5]; BODY_00_15(4, C, D, E, T, A, B, X(4)); X(6) = W[6]; BODY_00_15(5, B, C, D, E, T, A, X(5)); X(7) = W[7]; BODY_00_15(6, A, B, C, D, E, T, X(6)); X(8) = W[8]; BODY_00_15(7, T, A, B, C, D, E, X(7)); X(9) = W[9]; BODY_00_15(8, E, T, A, B, C, D, X(8)); X(10) = W[10]; BODY_00_15(9, D, E, T, A, B, C, X(9)); X(11) = W[11]; BODY_00_15(10, C, D, E, T, A, B, X(10)); X(12) = W[12]; BODY_00_15(11, B, C, D, E, T, A, X(11)); X(13) = W[13]; BODY_00_15(12, A, B, C, D, E, T, X(12)); X(14) = W[14]; BODY_00_15(13, T, A, B, C, D, E, X(13)); X(15) = W[15]; BODY_00_15(14, E, T, A, B, C, D, X(14)); BODY_00_15(15, D, E, T, A, B, C, X(15)); data += SHA_CBLOCK; } else { (void)HOST_c2l(data, l); X(0) = l; (void)HOST_c2l(data, l); X(1) = l; BODY_00_15(0, A, B, C, D, E, T, X(0)); (void)HOST_c2l(data, l); X(2) = l; BODY_00_15(1, T, A, B, C, D, E, X(1)); (void)HOST_c2l(data, l); X(3) = l; BODY_00_15(2, E, T, A, B, C, D, X(2)); (void)HOST_c2l(data, l); X(4) = l; BODY_00_15(3, D, E, T, A, B, C, X(3)); (void)HOST_c2l(data, l); X(5) = l; BODY_00_15(4, C, D, E, T, A, B, X(4)); (void)HOST_c2l(data, l); X(6) = l; BODY_00_15(5, B, C, D, E, T, A, X(5)); (void)HOST_c2l(data, l); X(7) = l; BODY_00_15(6, A, B, C, D, E, T, X(6)); (void)HOST_c2l(data, l); X(8) = l; BODY_00_15(7, T, A, B, C, D, E, X(7)); (void)HOST_c2l(data, l); X(9) = l; BODY_00_15(8, E, T, A, B, C, D, X(8)); (void)HOST_c2l(data, l); X(10) = l; BODY_00_15(9, D, E, T, A, B, C, X(9)); (void)HOST_c2l(data, l); X(11) = l; BODY_00_15(10, C, D, E, T, A, B, X(10)); (void)HOST_c2l(data, l); X(12) = l; BODY_00_15(11, B, C, D, E, T, A, X(11)); (void)HOST_c2l(data, l); X(13) = l; BODY_00_15(12, A, B, C, D, E, T, X(12)); (void)HOST_c2l(data, l); X(14) = l; BODY_00_15(13, T, A, B, C, D, E, X(13)); (void)HOST_c2l(data, l); X(15) = l; BODY_00_15(14, E, T, A, B, C, D, X(14)); BODY_00_15(15, D, E, T, A, B, C, X(15)); } BODY_16_19(16, C, D, E, T, A, B, X(0), X(0), X(2), X(8), X(13)); BODY_16_19(17, B, C, D, E, T, A, X(1), X(1), X(3), X(9), X(14)); BODY_16_19(18, A, B, C, D, E, T, X(2), X(2), X(4), X(10), X(15)); BODY_16_19(19, T, A, B, C, D, E, X(3), X(3), X(5), X(11), X(0)); BODY_20_31(20, E, T, A, B, C, D, X(4), X(4), X(6), X(12), X(1)); BODY_20_31(21, D, E, T, A, B, C, X(5), X(5), X(7), X(13), X(2)); BODY_20_31(22, C, D, E, T, A, B, X(6), X(6), X(8), X(14), X(3)); BODY_20_31(23, B, C, D, E, T, A, X(7), X(7), X(9), X(15), X(4)); BODY_20_31(24, A, B, C, D, E, T, X(8), X(8), X(10), X(0), X(5)); BODY_20_31(25, T, A, B, C, D, E, X(9), X(9), X(11), X(1), X(6)); BODY_20_31(26, E, T, A, B, C, D, X(10), X(10), X(12), X(2), X(7)); BODY_20_31(27, D, E, T, A, B, C, X(11), X(11), X(13), X(3), X(8)); BODY_20_31(28, C, D, E, T, A, B, X(12), X(12), X(14), X(4), X(9)); BODY_20_31(29, B, C, D, E, T, A, X(13), X(13), X(15), X(5), X(10)); BODY_20_31(30, A, B, C, D, E, T, X(14), X(14), X(0), X(6), X(11)); BODY_20_31(31, T, A, B, C, D, E, X(15), X(15), X(1), X(7), X(12)); BODY_32_39(32, E, T, A, B, C, D, X(0), X(2), X(8), X(13)); BODY_32_39(33, D, E, T, A, B, C, X(1), X(3), X(9), X(14)); BODY_32_39(34, C, D, E, T, A, B, X(2), X(4), X(10), X(15)); BODY_32_39(35, B, C, D, E, T, A, X(3), X(5), X(11), X(0)); BODY_32_39(36, A, B, C, D, E, T, X(4), X(6), X(12), X(1)); BODY_32_39(37, T, A, B, C, D, E, X(5), X(7), X(13), X(2)); BODY_32_39(38, E, T, A, B, C, D, X(6), X(8), X(14), X(3)); BODY_32_39(39, D, E, T, A, B, C, X(7), X(9), X(15), X(4)); BODY_40_59(40, C, D, E, T, A, B, X(8), X(10), X(0), X(5)); BODY_40_59(41, B, C, D, E, T, A, X(9), X(11), X(1), X(6)); BODY_40_59(42, A, B, C, D, E, T, X(10), X(12), X(2), X(7)); BODY_40_59(43, T, A, B, C, D, E, X(11), X(13), X(3), X(8)); BODY_40_59(44, E, T, A, B, C, D, X(12), X(14), X(4), X(9)); BODY_40_59(45, D, E, T, A, B, C, X(13), X(15), X(5), X(10)); BODY_40_59(46, C, D, E, T, A, B, X(14), X(0), X(6), X(11)); BODY_40_59(47, B, C, D, E, T, A, X(15), X(1), X(7), X(12)); BODY_40_59(48, A, B, C, D, E, T, X(0), X(2), X(8), X(13)); BODY_40_59(49, T, A, B, C, D, E, X(1), X(3), X(9), X(14)); BODY_40_59(50, E, T, A, B, C, D, X(2), X(4), X(10), X(15)); BODY_40_59(51, D, E, T, A, B, C, X(3), X(5), X(11), X(0)); BODY_40_59(52, C, D, E, T, A, B, X(4), X(6), X(12), X(1)); BODY_40_59(53, B, C, D, E, T, A, X(5), X(7), X(13), X(2)); BODY_40_59(54, A, B, C, D, E, T, X(6), X(8), X(14), X(3)); BODY_40_59(55, T, A, B, C, D, E, X(7), X(9), X(15), X(4)); BODY_40_59(56, E, T, A, B, C, D, X(8), X(10), X(0), X(5)); BODY_40_59(57, D, E, T, A, B, C, X(9), X(11), X(1), X(6)); BODY_40_59(58, C, D, E, T, A, B, X(10), X(12), X(2), X(7)); BODY_40_59(59, B, C, D, E, T, A, X(11), X(13), X(3), X(8)); BODY_60_79(60, A, B, C, D, E, T, X(12), X(14), X(4), X(9)); BODY_60_79(61, T, A, B, C, D, E, X(13), X(15), X(5), X(10)); BODY_60_79(62, E, T, A, B, C, D, X(14), X(0), X(6), X(11)); BODY_60_79(63, D, E, T, A, B, C, X(15), X(1), X(7), X(12)); BODY_60_79(64, C, D, E, T, A, B, X(0), X(2), X(8), X(13)); BODY_60_79(65, B, C, D, E, T, A, X(1), X(3), X(9), X(14)); BODY_60_79(66, A, B, C, D, E, T, X(2), X(4), X(10), X(15)); BODY_60_79(67, T, A, B, C, D, E, X(3), X(5), X(11), X(0)); BODY_60_79(68, E, T, A, B, C, D, X(4), X(6), X(12), X(1)); BODY_60_79(69, D, E, T, A, B, C, X(5), X(7), X(13), X(2)); BODY_60_79(70, C, D, E, T, A, B, X(6), X(8), X(14), X(3)); BODY_60_79(71, B, C, D, E, T, A, X(7), X(9), X(15), X(4)); BODY_60_79(72, A, B, C, D, E, T, X(8), X(10), X(0), X(5)); BODY_60_79(73, T, A, B, C, D, E, X(9), X(11), X(1), X(6)); BODY_60_79(74, E, T, A, B, C, D, X(10), X(12), X(2), X(7)); BODY_60_79(75, D, E, T, A, B, C, X(11), X(13), X(3), X(8)); BODY_60_79(76, C, D, E, T, A, B, X(12), X(14), X(4), X(9)); BODY_60_79(77, B, C, D, E, T, A, X(13), X(15), X(5), X(10)); BODY_60_79(78, A, B, C, D, E, T, X(14), X(0), X(6), X(11)); BODY_60_79(79, T, A, B, C, D, E, X(15), X(1), X(7), X(12)); c->h0 = (c->h0 + E) & 0xffffffffL; c->h1 = (c->h1 + T) & 0xffffffffL; c->h2 = (c->h2 + A) & 0xffffffffL; c->h3 = (c->h3 + B) & 0xffffffffL; c->h4 = (c->h4 + C) & 0xffffffffL; if (--num == 0) break; A = c->h0; B = c->h1; C = c->h2; D = c->h3; E = c->h4; } } # endif #else /* OPENSSL_SMALL_FOOTPRINT */ # define BODY_00_15(xi) do { \ T=E+K_00_19+F_00_19(B,C,D); \ E=D, D=C, C=ROTATE(B,30), B=A; \ A=ROTATE(A,5)+T+xi; } while(0) # define BODY_16_19(xa,xb,xc,xd) do { \ Xupdate(T,xa,xa,xb,xc,xd); \ T+=E+K_00_19+F_00_19(B,C,D); \ E=D, D=C, C=ROTATE(B,30), B=A; \ A=ROTATE(A,5)+T; } while(0) # define BODY_20_39(xa,xb,xc,xd) do { \ Xupdate(T,xa,xa,xb,xc,xd); \ T+=E+K_20_39+F_20_39(B,C,D); \ E=D, D=C, C=ROTATE(B,30), B=A; \ A=ROTATE(A,5)+T; } while(0) # define BODY_40_59(xa,xb,xc,xd) do { \ Xupdate(T,xa,xa,xb,xc,xd); \ T+=E+K_40_59+F_40_59(B,C,D); \ E=D, D=C, C=ROTATE(B,30), B=A; \ A=ROTATE(A,5)+T; } while(0) # define BODY_60_79(xa,xb,xc,xd) do { \ Xupdate(T,xa,xa,xb,xc,xd); \ T=E+K_60_79+F_60_79(B,C,D); \ E=D, D=C, C=ROTATE(B,30), B=A; \ A=ROTATE(A,5)+T+xa; } while(0) # if !defined(SHA1_ASM) static void HASH_BLOCK_DATA_ORDER(SHA_CTX *c, const void *p, size_t num) { const unsigned char *data = p; register unsigned MD32_REG_T A, B, C, D, E, T, l; int i; SHA_LONG X[16]; A = c->h0; B = c->h1; C = c->h2; D = c->h3; E = c->h4; for (;;) { for (i = 0; i < 16; i++) { (void)HOST_c2l(data, l); X[i] = l; BODY_00_15(X[i]); } for (i = 0; i < 4; i++) { BODY_16_19(X[i], X[i + 2], X[i + 8], X[(i + 13) & 15]); } for (; i < 24; i++) { BODY_20_39(X[i & 15], X[(i + 2) & 15], X[(i + 8) & 15], X[(i + 13) & 15]); } for (i = 0; i < 20; i++) { BODY_40_59(X[(i + 8) & 15], X[(i + 10) & 15], X[i & 15], X[(i + 5) & 15]); } for (i = 4; i < 24; i++) { BODY_60_79(X[(i + 8) & 15], X[(i + 10) & 15], X[i & 15], X[(i + 5) & 15]); } c->h0 = (c->h0 + A) & 0xffffffffL; c->h1 = (c->h1 + B) & 0xffffffffL; c->h2 = (c->h2 + C) & 0xffffffffL; c->h3 = (c->h3 + D) & 0xffffffffL; c->h4 = (c->h4 + E) & 0xffffffffL; if (--num == 0) break; A = c->h0; B = c->h1; C = c->h2; D = c->h3; E = c->h4; } } # endif #endif
15,454
35.710214
76
h
openssl
openssl-master/crypto/sha/sha_ppc.c
/* * Copyright 2009-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/sha.h> #include "crypto/ppc_arch.h" void sha256_block_p8(void *ctx, const void *inp, size_t len); void sha256_block_ppc(void *ctx, const void *inp, size_t len); void sha256_block_data_order(void *ctx, const void *inp, size_t len); void sha256_block_data_order(void *ctx, const void *inp, size_t len) { OPENSSL_ppccap_P & PPC_CRYPTO207 ? sha256_block_p8(ctx, inp, len) : sha256_block_ppc(ctx, inp, len); } void sha512_block_p8(void *ctx, const void *inp, size_t len); void sha512_block_ppc(void *ctx, const void *inp, size_t len); void sha512_block_data_order(void *ctx, const void *inp, size_t len); void sha512_block_data_order(void *ctx, const void *inp, size_t len) { OPENSSL_ppccap_P & PPC_CRYPTO207 ? sha512_block_p8(ctx, inp, len) : sha512_block_ppc(ctx, inp, len); }
1,229
35.176471
74
c
openssl
openssl-master/crypto/siphash/siphash.c
/* * Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* Based on https://131002.net/siphash C reference implementation */ /* SipHash reference C implementation Copyright (c) 2012-2016 Jean-Philippe Aumasson Copyright (c) 2012-2014 Daniel J. Bernstein To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include <stdlib.h> #include <string.h> #include <openssl/crypto.h> #include "crypto/siphash.h" #define ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b)))) #define U32TO8_LE(p, v) \ (p)[0] = (uint8_t)((v)); \ (p)[1] = (uint8_t)((v) >> 8); \ (p)[2] = (uint8_t)((v) >> 16); \ (p)[3] = (uint8_t)((v) >> 24); #define U64TO8_LE(p, v) \ U32TO8_LE((p), (uint32_t)((v))); \ U32TO8_LE((p) + 4, (uint32_t)((v) >> 32)); #define U8TO64_LE(p) \ (((uint64_t)((p)[0])) | ((uint64_t)((p)[1]) << 8) | \ ((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) | \ ((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) | \ ((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56)) #define SIPROUND \ do { \ v0 += v1; \ v1 = ROTL(v1, 13); \ v1 ^= v0; \ v0 = ROTL(v0, 32); \ v2 += v3; \ v3 = ROTL(v3, 16); \ v3 ^= v2; \ v0 += v3; \ v3 = ROTL(v3, 21); \ v3 ^= v0; \ v2 += v1; \ v1 = ROTL(v1, 17); \ v1 ^= v2; \ v2 = ROTL(v2, 32); \ } while (0) size_t SipHash_ctx_size(void) { return sizeof(SIPHASH); } size_t SipHash_hash_size(SIPHASH *ctx) { return ctx->hash_size; } static size_t siphash_adjust_hash_size(size_t hash_size) { if (hash_size == 0) hash_size = SIPHASH_MAX_DIGEST_SIZE; return hash_size; } int SipHash_set_hash_size(SIPHASH *ctx, size_t hash_size) { hash_size = siphash_adjust_hash_size(hash_size); if (hash_size != SIPHASH_MIN_DIGEST_SIZE && hash_size != SIPHASH_MAX_DIGEST_SIZE) return 0; /* * It's possible that the key was set first. If the hash size changes, * we need to adjust v1 (see SipHash_Init(). */ /* Start by adjusting the stored size, to make things easier */ ctx->hash_size = siphash_adjust_hash_size(ctx->hash_size); /* Now, adjust ctx->v1 if the old and the new size differ */ if ((size_t)ctx->hash_size != hash_size) { ctx->v1 ^= 0xee; ctx->hash_size = hash_size; } return 1; } /* hash_size = crounds = drounds = 0 means SipHash24 with 16-byte output */ int SipHash_Init(SIPHASH *ctx, const unsigned char *k, int crounds, int drounds) { uint64_t k0 = U8TO64_LE(k); uint64_t k1 = U8TO64_LE(k + 8); /* If the hash size wasn't set, i.e. is zero */ ctx->hash_size = siphash_adjust_hash_size(ctx->hash_size); if (drounds == 0) drounds = SIPHASH_D_ROUNDS; if (crounds == 0) crounds = SIPHASH_C_ROUNDS; ctx->crounds = crounds; ctx->drounds = drounds; ctx->len = 0; ctx->total_inlen = 0; ctx->v0 = 0x736f6d6570736575ULL ^ k0; ctx->v1 = 0x646f72616e646f6dULL ^ k1; ctx->v2 = 0x6c7967656e657261ULL ^ k0; ctx->v3 = 0x7465646279746573ULL ^ k1; if (ctx->hash_size == SIPHASH_MAX_DIGEST_SIZE) ctx->v1 ^= 0xee; return 1; } void SipHash_Update(SIPHASH *ctx, const unsigned char *in, size_t inlen) { uint64_t m; const uint8_t *end; int left; unsigned int i; uint64_t v0 = ctx->v0; uint64_t v1 = ctx->v1; uint64_t v2 = ctx->v2; uint64_t v3 = ctx->v3; ctx->total_inlen += inlen; if (ctx->len) { /* deal with leavings */ size_t available = SIPHASH_BLOCK_SIZE - ctx->len; /* not enough to fill leavings */ if (inlen < available) { memcpy(&ctx->leavings[ctx->len], in, inlen); ctx->len += inlen; return; } /* copy data into leavings and reduce input */ memcpy(&ctx->leavings[ctx->len], in, available); inlen -= available; in += available; /* process leavings */ m = U8TO64_LE(ctx->leavings); v3 ^= m; for (i = 0; i < ctx->crounds; ++i) SIPROUND; v0 ^= m; } left = inlen & (SIPHASH_BLOCK_SIZE-1); /* gets put into leavings */ end = in + inlen - left; for (; in != end; in += 8) { m = U8TO64_LE(in); v3 ^= m; for (i = 0; i < ctx->crounds; ++i) SIPROUND; v0 ^= m; } /* save leavings and other ctx */ if (left) memcpy(ctx->leavings, end, left); ctx->len = left; ctx->v0 = v0; ctx->v1 = v1; ctx->v2 = v2; ctx->v3 = v3; } int SipHash_Final(SIPHASH *ctx, unsigned char *out, size_t outlen) { /* finalize hash */ unsigned int i; uint64_t b = ctx->total_inlen << 56; uint64_t v0 = ctx->v0; uint64_t v1 = ctx->v1; uint64_t v2 = ctx->v2; uint64_t v3 = ctx->v3; if (ctx->crounds == 0 || outlen == 0 || outlen != (size_t)ctx->hash_size) return 0; switch (ctx->len) { case 7: b |= ((uint64_t)ctx->leavings[6]) << 48; /* fall through */ case 6: b |= ((uint64_t)ctx->leavings[5]) << 40; /* fall through */ case 5: b |= ((uint64_t)ctx->leavings[4]) << 32; /* fall through */ case 4: b |= ((uint64_t)ctx->leavings[3]) << 24; /* fall through */ case 3: b |= ((uint64_t)ctx->leavings[2]) << 16; /* fall through */ case 2: b |= ((uint64_t)ctx->leavings[1]) << 8; /* fall through */ case 1: b |= ((uint64_t)ctx->leavings[0]); case 0: break; } v3 ^= b; for (i = 0; i < ctx->crounds; ++i) SIPROUND; v0 ^= b; if (ctx->hash_size == SIPHASH_MAX_DIGEST_SIZE) v2 ^= 0xee; else v2 ^= 0xff; for (i = 0; i < ctx->drounds; ++i) SIPROUND; b = v0 ^ v1 ^ v2 ^ v3; U64TO8_LE(out, b); if (ctx->hash_size == SIPHASH_MIN_DIGEST_SIZE) return 1; v1 ^= 0xdd; for (i = 0; i < ctx->drounds; ++i) SIPROUND; b = v0 ^ v1 ^ v2 ^ v3; U64TO8_LE(out + 8, b); return 1; }
8,084
30.582031
80
c
openssl
openssl-master/crypto/sm2/sm2_crypt.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * ECDSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "crypto/sm2.h" #include "crypto/sm2err.h" #include "crypto/ec.h" /* ossl_ecdh_kdf_X9_63() */ #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/bn.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <string.h> typedef struct SM2_Ciphertext_st SM2_Ciphertext; DECLARE_ASN1_FUNCTIONS(SM2_Ciphertext) struct SM2_Ciphertext_st { BIGNUM *C1x; BIGNUM *C1y; ASN1_OCTET_STRING *C3; ASN1_OCTET_STRING *C2; }; ASN1_SEQUENCE(SM2_Ciphertext) = { ASN1_SIMPLE(SM2_Ciphertext, C1x, BIGNUM), ASN1_SIMPLE(SM2_Ciphertext, C1y, BIGNUM), ASN1_SIMPLE(SM2_Ciphertext, C3, ASN1_OCTET_STRING), ASN1_SIMPLE(SM2_Ciphertext, C2, ASN1_OCTET_STRING), } ASN1_SEQUENCE_END(SM2_Ciphertext) IMPLEMENT_ASN1_FUNCTIONS(SM2_Ciphertext) static size_t ec_field_size(const EC_GROUP *group) { /* Is there some simpler way to do this? */ BIGNUM *p = BN_new(); BIGNUM *a = BN_new(); BIGNUM *b = BN_new(); size_t field_size = 0; if (p == NULL || a == NULL || b == NULL) goto done; if (!EC_GROUP_get_curve(group, p, a, b, NULL)) goto done; field_size = (BN_num_bits(p) + 7) / 8; done: BN_free(p); BN_free(a); BN_free(b); return field_size; } int ossl_sm2_plaintext_size(const unsigned char *ct, size_t ct_size, size_t *pt_size) { struct SM2_Ciphertext_st *sm2_ctext = NULL; sm2_ctext = d2i_SM2_Ciphertext(NULL, &ct, ct_size); if (sm2_ctext == NULL) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING); return 0; } *pt_size = sm2_ctext->C2->length; SM2_Ciphertext_free(sm2_ctext); return 1; } int ossl_sm2_ciphertext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len, size_t *ct_size) { const size_t field_size = ec_field_size(EC_KEY_get0_group(key)); const int md_size = EVP_MD_get_size(digest); size_t sz; if (field_size == 0 || md_size < 0) return 0; /* Integer and string are simple type; set constructed = 0, means primitive and definite length encoding. */ sz = 2 * ASN1_object_size(0, field_size + 1, V_ASN1_INTEGER) + ASN1_object_size(0, md_size, V_ASN1_OCTET_STRING) + ASN1_object_size(0, msg_len, V_ASN1_OCTET_STRING); /* Sequence is structured type; set constructed = 1, means constructed and definite length encoding. */ *ct_size = ASN1_object_size(1, sz, V_ASN1_SEQUENCE); return 1; } int ossl_sm2_encrypt(const EC_KEY *key, const EVP_MD *digest, const uint8_t *msg, size_t msg_len, uint8_t *ciphertext_buf, size_t *ciphertext_len) { int rc = 0, ciphertext_leni; size_t i; BN_CTX *ctx = NULL; BIGNUM *k = NULL; BIGNUM *x1 = NULL; BIGNUM *y1 = NULL; BIGNUM *x2 = NULL; BIGNUM *y2 = NULL; EVP_MD_CTX *hash = EVP_MD_CTX_new(); struct SM2_Ciphertext_st ctext_struct; const EC_GROUP *group = EC_KEY_get0_group(key); const BIGNUM *order = EC_GROUP_get0_order(group); const EC_POINT *P = EC_KEY_get0_public_key(key); EC_POINT *kG = NULL; EC_POINT *kP = NULL; uint8_t *msg_mask = NULL; uint8_t *x2y2 = NULL; uint8_t *C3 = NULL; size_t field_size; const int C3_size = EVP_MD_get_size(digest); EVP_MD *fetched_digest = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); const char *propq = ossl_ec_key_get0_propq(key); /* NULL these before any "goto done" */ ctext_struct.C2 = NULL; ctext_struct.C3 = NULL; if (hash == NULL || C3_size <= 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } field_size = ec_field_size(group); if (field_size == 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } kG = EC_POINT_new(group); kP = EC_POINT_new(group); if (kG == NULL || kP == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } ctx = BN_CTX_new_ex(libctx); if (ctx == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } BN_CTX_start(ctx); k = BN_CTX_get(ctx); x1 = BN_CTX_get(ctx); x2 = BN_CTX_get(ctx); y1 = BN_CTX_get(ctx); y2 = BN_CTX_get(ctx); if (y2 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } x2y2 = OPENSSL_zalloc(2 * field_size); C3 = OPENSSL_zalloc(C3_size); if (x2y2 == NULL || C3 == NULL) goto done; memset(ciphertext_buf, 0, *ciphertext_len); if (!BN_priv_rand_range_ex(k, order, 0, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (!EC_POINT_mul(group, kG, k, NULL, NULL, ctx) || !EC_POINT_get_affine_coordinates(group, kG, x1, y1, ctx) || !EC_POINT_mul(group, kP, NULL, P, k, ctx) || !EC_POINT_get_affine_coordinates(group, kP, x2, y2, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } if (BN_bn2binpad(x2, x2y2, field_size) < 0 || BN_bn2binpad(y2, x2y2 + field_size, field_size) < 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } msg_mask = OPENSSL_zalloc(msg_len); if (msg_mask == NULL) goto done; /* X9.63 with no salt happens to match the KDF used in SM2 */ if (!ossl_ecdh_kdf_X9_63(msg_mask, msg_len, x2y2, 2 * field_size, NULL, 0, digest, libctx, propq)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } for (i = 0; i != msg_len; ++i) msg_mask[i] ^= msg[i]; fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(digest), propq); if (fetched_digest == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (EVP_DigestInit(hash, fetched_digest) == 0 || EVP_DigestUpdate(hash, x2y2, field_size) == 0 || EVP_DigestUpdate(hash, msg, msg_len) == 0 || EVP_DigestUpdate(hash, x2y2 + field_size, field_size) == 0 || EVP_DigestFinal(hash, C3, NULL) == 0) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } ctext_struct.C1x = x1; ctext_struct.C1y = y1; ctext_struct.C3 = ASN1_OCTET_STRING_new(); ctext_struct.C2 = ASN1_OCTET_STRING_new(); if (ctext_struct.C3 == NULL || ctext_struct.C2 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_ASN1_LIB); goto done; } if (!ASN1_OCTET_STRING_set(ctext_struct.C3, C3, C3_size) || !ASN1_OCTET_STRING_set(ctext_struct.C2, msg_mask, msg_len)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } ciphertext_leni = i2d_SM2_Ciphertext(&ctext_struct, &ciphertext_buf); /* Ensure cast to size_t is safe */ if (ciphertext_leni < 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } *ciphertext_len = (size_t)ciphertext_leni; rc = 1; done: EVP_MD_free(fetched_digest); ASN1_OCTET_STRING_free(ctext_struct.C2); ASN1_OCTET_STRING_free(ctext_struct.C3); OPENSSL_free(msg_mask); OPENSSL_free(x2y2); OPENSSL_free(C3); EVP_MD_CTX_free(hash); BN_CTX_free(ctx); EC_POINT_free(kG); EC_POINT_free(kP); return rc; } int ossl_sm2_decrypt(const EC_KEY *key, const EVP_MD *digest, const uint8_t *ciphertext, size_t ciphertext_len, uint8_t *ptext_buf, size_t *ptext_len) { int rc = 0; int i; BN_CTX *ctx = NULL; const EC_GROUP *group = EC_KEY_get0_group(key); EC_POINT *C1 = NULL; struct SM2_Ciphertext_st *sm2_ctext = NULL; BIGNUM *x2 = NULL; BIGNUM *y2 = NULL; uint8_t *x2y2 = NULL; uint8_t *computed_C3 = NULL; const size_t field_size = ec_field_size(group); const int hash_size = EVP_MD_get_size(digest); uint8_t *msg_mask = NULL; const uint8_t *C2 = NULL; const uint8_t *C3 = NULL; int msg_len = 0; EVP_MD_CTX *hash = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); const char *propq = ossl_ec_key_get0_propq(key); if (field_size == 0 || hash_size <= 0) goto done; memset(ptext_buf, 0xFF, *ptext_len); sm2_ctext = d2i_SM2_Ciphertext(NULL, &ciphertext, ciphertext_len); if (sm2_ctext == NULL) { ERR_raise(ERR_LIB_SM2, SM2_R_ASN1_ERROR); goto done; } if (sm2_ctext->C3->length != hash_size) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING); goto done; } C2 = sm2_ctext->C2->data; C3 = sm2_ctext->C3->data; msg_len = sm2_ctext->C2->length; if (*ptext_len < (size_t)msg_len) { ERR_raise(ERR_LIB_SM2, SM2_R_BUFFER_TOO_SMALL); goto done; } ctx = BN_CTX_new_ex(libctx); if (ctx == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } BN_CTX_start(ctx); x2 = BN_CTX_get(ctx); y2 = BN_CTX_get(ctx); if (y2 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } msg_mask = OPENSSL_zalloc(msg_len); x2y2 = OPENSSL_zalloc(2 * field_size); computed_C3 = OPENSSL_zalloc(hash_size); if (msg_mask == NULL || x2y2 == NULL || computed_C3 == NULL) goto done; C1 = EC_POINT_new(group); if (C1 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } if (!EC_POINT_set_affine_coordinates(group, C1, sm2_ctext->C1x, sm2_ctext->C1y, ctx) || !EC_POINT_mul(group, C1, NULL, C1, EC_KEY_get0_private_key(key), ctx) || !EC_POINT_get_affine_coordinates(group, C1, x2, y2, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } if (BN_bn2binpad(x2, x2y2, field_size) < 0 || BN_bn2binpad(y2, x2y2 + field_size, field_size) < 0 || !ossl_ecdh_kdf_X9_63(msg_mask, msg_len, x2y2, 2 * field_size, NULL, 0, digest, libctx, propq)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } for (i = 0; i != msg_len; ++i) ptext_buf[i] = C2[i] ^ msg_mask[i]; hash = EVP_MD_CTX_new(); if (hash == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } if (!EVP_DigestInit(hash, digest) || !EVP_DigestUpdate(hash, x2y2, field_size) || !EVP_DigestUpdate(hash, ptext_buf, msg_len) || !EVP_DigestUpdate(hash, x2y2 + field_size, field_size) || !EVP_DigestFinal(hash, computed_C3, NULL)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } if (CRYPTO_memcmp(computed_C3, C3, hash_size) != 0) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_DIGEST); goto done; } rc = 1; *ptext_len = msg_len; done: if (rc == 0) memset(ptext_buf, 0, *ptext_len); OPENSSL_free(msg_mask); OPENSSL_free(x2y2); OPENSSL_free(computed_C3); EC_POINT_free(C1); BN_CTX_free(ctx); SM2_Ciphertext_free(sm2_ctext); EVP_MD_CTX_free(hash); return rc; }
11,729
27.962963
112
c
openssl
openssl-master/crypto/sm2/sm2_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include "crypto/sm2err.h" #ifndef OPENSSL_NO_SM2 # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA SM2_str_reasons[] = { {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_ASN1_ERROR), "asn1 error"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_BAD_SIGNATURE), "bad signature"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_BUFFER_TOO_SMALL), "buffer too small"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_DIST_ID_TOO_LARGE), "dist id too large"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_ID_NOT_SET), "id not set"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_ID_TOO_LARGE), "id too large"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_CURVE), "invalid curve"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_DIGEST), "invalid digest"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_DIGEST_TYPE), "invalid digest type"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_ENCODING), "invalid encoding"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_FIELD), "invalid field"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_INVALID_PRIVATE_KEY), "invalid private key"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_NO_PARAMETERS_SET), "no parameters set"}, {ERR_PACK(ERR_LIB_SM2, 0, SM2_R_USER_ID_TOO_LARGE), "user id too large"}, {0, NULL} }; # endif int ossl_err_load_SM2_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(SM2_str_reasons[0].error) == NULL) ERR_load_strings_const(SM2_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
1,837
35.039216
77
c
openssl
openssl-master/crypto/sm2/sm2_key.c
/* * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/deprecated.h" /* to be able to use EC_KEY and EC_GROUP */ #include <openssl/err.h> #include "crypto/sm2err.h" #include "crypto/sm2.h" #include <openssl/ec.h> /* EC_KEY and EC_GROUP functions */ /* * SM2 key generation is implemented within ec_generate_key() in * crypto/ec/ec_key.c */ int ossl_sm2_key_private_check(const EC_KEY *eckey) { int ret = 0; BIGNUM *max = NULL; const EC_GROUP *group = NULL; const BIGNUM *priv_key = NULL, *order = NULL; if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL || (priv_key = EC_KEY_get0_private_key(eckey)) == NULL || (order = EC_GROUP_get0_order(group)) == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* range of SM2 private key is [1, n-1) */ max = BN_dup(order); if (max == NULL || !BN_sub_word(max, 1)) goto end; if (BN_cmp(priv_key, BN_value_one()) < 0 || BN_cmp(priv_key, max) >= 0) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_PRIVATE_KEY); goto end; } ret = 1; end: BN_free(max); return ret; }
1,483
27.538462
76
c
openssl
openssl-master/crypto/sm2/sm2_sign.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/deprecated.h" #include "crypto/sm2.h" #include "crypto/sm2err.h" #include "crypto/ec.h" /* ossl_ec_group_do_inverse_ord() */ #include "internal/numbers.h" #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/bn.h> #include <string.h> int ossl_sm2_compute_z_digest(uint8_t *out, const EVP_MD *digest, const uint8_t *id, const size_t id_len, const EC_KEY *key) { int rc = 0; const EC_GROUP *group = EC_KEY_get0_group(key); BN_CTX *ctx = NULL; EVP_MD_CTX *hash = NULL; BIGNUM *p = NULL; BIGNUM *a = NULL; BIGNUM *b = NULL; BIGNUM *xG = NULL; BIGNUM *yG = NULL; BIGNUM *xA = NULL; BIGNUM *yA = NULL; int p_bytes = 0; uint8_t *buf = NULL; uint16_t entl = 0; uint8_t e_byte = 0; hash = EVP_MD_CTX_new(); if (hash == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } ctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(key)); if (ctx == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } p = BN_CTX_get(ctx); a = BN_CTX_get(ctx); b = BN_CTX_get(ctx); xG = BN_CTX_get(ctx); yG = BN_CTX_get(ctx); xA = BN_CTX_get(ctx); yA = BN_CTX_get(ctx); if (yA == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } if (!EVP_DigestInit(hash, digest)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } /* Z = h(ENTL || ID || a || b || xG || yG || xA || yA) */ if (id_len >= (UINT16_MAX / 8)) { /* too large */ ERR_raise(ERR_LIB_SM2, SM2_R_ID_TOO_LARGE); goto done; } entl = (uint16_t)(8 * id_len); e_byte = entl >> 8; if (!EVP_DigestUpdate(hash, &e_byte, 1)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } e_byte = entl & 0xFF; if (!EVP_DigestUpdate(hash, &e_byte, 1)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } if (id_len > 0 && !EVP_DigestUpdate(hash, id, id_len)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } if (!EC_GROUP_get_curve(group, p, a, b, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } p_bytes = BN_num_bytes(p); buf = OPENSSL_zalloc(p_bytes); if (buf == NULL) goto done; if (BN_bn2binpad(a, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || BN_bn2binpad(b, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || !EC_POINT_get_affine_coordinates(group, EC_GROUP_get0_generator(group), xG, yG, ctx) || BN_bn2binpad(xG, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || BN_bn2binpad(yG, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || !EC_POINT_get_affine_coordinates(group, EC_KEY_get0_public_key(key), xA, yA, ctx) || BN_bn2binpad(xA, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || BN_bn2binpad(yA, buf, p_bytes) < 0 || !EVP_DigestUpdate(hash, buf, p_bytes) || !EVP_DigestFinal(hash, out, NULL)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } rc = 1; done: OPENSSL_free(buf); BN_CTX_free(ctx); EVP_MD_CTX_free(hash); return rc; } static BIGNUM *sm2_compute_msg_hash(const EVP_MD *digest, const EC_KEY *key, const uint8_t *id, const size_t id_len, const uint8_t *msg, size_t msg_len) { EVP_MD_CTX *hash = EVP_MD_CTX_new(); const int md_size = EVP_MD_get_size(digest); uint8_t *z = NULL; BIGNUM *e = NULL; EVP_MD *fetched_digest = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); const char *propq = ossl_ec_key_get0_propq(key); if (md_size < 0) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_DIGEST); goto done; } if (hash == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } z = OPENSSL_zalloc(md_size); if (z == NULL) goto done; fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(digest), propq); if (fetched_digest == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (!ossl_sm2_compute_z_digest(z, fetched_digest, id, id_len, key)) { /* SM2err already called */ goto done; } if (!EVP_DigestInit(hash, fetched_digest) || !EVP_DigestUpdate(hash, z, md_size) || !EVP_DigestUpdate(hash, msg, msg_len) /* reuse z buffer to hold H(Z || M) */ || !EVP_DigestFinal(hash, z, NULL)) { ERR_raise(ERR_LIB_SM2, ERR_R_EVP_LIB); goto done; } e = BN_bin2bn(z, md_size, NULL); if (e == NULL) ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); done: EVP_MD_free(fetched_digest); OPENSSL_free(z); EVP_MD_CTX_free(hash); return e; } static ECDSA_SIG *sm2_sig_gen(const EC_KEY *key, const BIGNUM *e) { const BIGNUM *dA = EC_KEY_get0_private_key(key); const EC_GROUP *group = EC_KEY_get0_group(key); const BIGNUM *order = EC_GROUP_get0_order(group); ECDSA_SIG *sig = NULL; EC_POINT *kG = NULL; BN_CTX *ctx = NULL; BIGNUM *k = NULL; BIGNUM *rk = NULL; BIGNUM *r = NULL; BIGNUM *s = NULL; BIGNUM *x1 = NULL; BIGNUM *tmp = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); kG = EC_POINT_new(group); if (kG == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } ctx = BN_CTX_new_ex(libctx); if (ctx == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } BN_CTX_start(ctx); k = BN_CTX_get(ctx); rk = BN_CTX_get(ctx); x1 = BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } /* * These values are returned and so should not be allocated out of the * context */ r = BN_new(); s = BN_new(); if (r == NULL || s == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } /* * A3: Generate a random number k in [1,n-1] using random number generators; * A4: Compute (x1,y1)=[k]G, and convert the type of data x1 to be integer * as specified in clause 4.2.8 of GM/T 0003.1-2012; * A5: Compute r=(e+x1) mod n. If r=0 or r+k=n, then go to A3; * A6: Compute s=(1/(1+dA)*(k-r*dA)) mod n. If s=0, then go to A3; * A7: Convert the type of data (r,s) to be bit strings according to the details * in clause 4.2.2 of GM/T 0003.1-2012. Then the signature of message M is (r,s). */ for (;;) { if (!BN_priv_rand_range_ex(k, order, 0, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (!EC_POINT_mul(group, kG, k, NULL, NULL, ctx) || !EC_POINT_get_affine_coordinates(group, kG, x1, NULL, ctx) || !BN_mod_add(r, e, x1, order, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } /* try again if r == 0 or r+k == n */ if (BN_is_zero(r)) continue; if (!BN_add(rk, r, k)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } if (BN_cmp(rk, order) == 0) continue; if (!BN_add(s, dA, BN_value_one()) || !ossl_ec_group_do_inverse_ord(group, s, s, ctx) || !BN_mod_mul(tmp, dA, r, order, ctx) || !BN_sub(tmp, k, tmp) || !BN_mod_mul(s, s, tmp, order, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } /* try again if s == 0 */ if (BN_is_zero(s)) continue; sig = ECDSA_SIG_new(); if (sig == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_ECDSA_LIB); goto done; } /* takes ownership of r and s */ ECDSA_SIG_set0(sig, r, s); break; } done: if (sig == NULL) { BN_free(r); BN_free(s); } BN_CTX_free(ctx); EC_POINT_free(kG); return sig; } static int sm2_sig_verify(const EC_KEY *key, const ECDSA_SIG *sig, const BIGNUM *e) { int ret = 0; const EC_GROUP *group = EC_KEY_get0_group(key); const BIGNUM *order = EC_GROUP_get0_order(group); BN_CTX *ctx = NULL; EC_POINT *pt = NULL; BIGNUM *t = NULL; BIGNUM *x1 = NULL; const BIGNUM *r = NULL; const BIGNUM *s = NULL; OSSL_LIB_CTX *libctx = ossl_ec_key_get_libctx(key); ctx = BN_CTX_new_ex(libctx); pt = EC_POINT_new(group); if (ctx == NULL || pt == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } BN_CTX_start(ctx); t = BN_CTX_get(ctx); x1 = BN_CTX_get(ctx); if (x1 == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } /* * B1: verify whether r' in [1,n-1], verification failed if not * B2: verify whether s' in [1,n-1], verification failed if not * B3: set M'~=ZA || M' * B4: calculate e'=Hv(M'~) * B5: calculate t = (r' + s') modn, verification failed if t=0 * B6: calculate the point (x1', y1')=[s']G + [t]PA * B7: calculate R=(e'+x1') modn, verification pass if yes, otherwise failed */ ECDSA_SIG_get0(sig, &r, &s); if (BN_cmp(r, BN_value_one()) < 0 || BN_cmp(s, BN_value_one()) < 0 || BN_cmp(order, r) <= 0 || BN_cmp(order, s) <= 0) { ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE); goto done; } if (!BN_mod_add(t, r, s, order, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } if (BN_is_zero(t)) { ERR_raise(ERR_LIB_SM2, SM2_R_BAD_SIGNATURE); goto done; } if (!EC_POINT_mul(group, pt, s, EC_KEY_get0_public_key(key), t, ctx) || !EC_POINT_get_affine_coordinates(group, pt, x1, NULL, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_EC_LIB); goto done; } if (!BN_mod_add(t, e, x1, order, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } if (BN_cmp(r, t) == 0) ret = 1; done: BN_CTX_end(ctx); EC_POINT_free(pt); BN_CTX_free(ctx); return ret; } ECDSA_SIG *ossl_sm2_do_sign(const EC_KEY *key, const EVP_MD *digest, const uint8_t *id, const size_t id_len, const uint8_t *msg, size_t msg_len) { BIGNUM *e = NULL; ECDSA_SIG *sig = NULL; e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len); if (e == NULL) { /* SM2err already called */ goto done; } sig = sm2_sig_gen(key, e); done: BN_free(e); return sig; } int ossl_sm2_do_verify(const EC_KEY *key, const EVP_MD *digest, const ECDSA_SIG *sig, const uint8_t *id, const size_t id_len, const uint8_t *msg, size_t msg_len) { BIGNUM *e = NULL; int ret = 0; e = sm2_compute_msg_hash(digest, key, id, id_len, msg, msg_len); if (e == NULL) { /* SM2err already called */ goto done; } ret = sm2_sig_verify(key, sig, e); done: BN_free(e); return ret; } int ossl_sm2_internal_sign(const unsigned char *dgst, int dgstlen, unsigned char *sig, unsigned int *siglen, EC_KEY *eckey) { BIGNUM *e = NULL; ECDSA_SIG *s = NULL; int sigleni; int ret = -1; e = BN_bin2bn(dgst, dgstlen, NULL); if (e == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } s = sm2_sig_gen(eckey, e); if (s == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } sigleni = i2d_ECDSA_SIG(s, sig != NULL ? &sig : NULL); if (sigleni < 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } *siglen = (unsigned int)sigleni; ret = 1; done: ECDSA_SIG_free(s); BN_free(e); return ret; } int ossl_sm2_internal_verify(const unsigned char *dgst, int dgstlen, const unsigned char *sig, int sig_len, EC_KEY *eckey) { ECDSA_SIG *s = NULL; BIGNUM *e = NULL; const unsigned char *p = sig; unsigned char *der = NULL; int derlen = -1; int ret = -1; s = ECDSA_SIG_new(); if (s == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_ECDSA_LIB); goto done; } if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING); goto done; } /* Ensure signature uses DER and doesn't have trailing garbage */ derlen = i2d_ECDSA_SIG(s, &der); if (derlen != sig_len || memcmp(sig, der, derlen) != 0) { ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING); goto done; } e = BN_bin2bn(dgst, dgstlen, NULL); if (e == NULL) { ERR_raise(ERR_LIB_SM2, ERR_R_BN_LIB); goto done; } ret = sm2_sig_verify(eckey, s, e); done: OPENSSL_free(der); BN_free(e); ECDSA_SIG_free(s); return ret; }
14,354
26.552783
89
c
openssl
openssl-master/crypto/sm3/legacy_sm3.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "crypto/evp.h" #include "../evp/legacy_meth.h" #include "internal/sm3.h" IMPLEMENT_LEGACY_EVP_MD_METH_LC(sm3_int, ossl_sm3) static const EVP_MD sm3_md = { NID_sm3, NID_sm3WithRSAEncryption, SM3_DIGEST_LENGTH, 0, EVP_ORIG_GLOBAL, LEGACY_EVP_MD_METH_TABLE(sm3_int_init, sm3_int_update, sm3_int_final, NULL, SM3_CBLOCK), }; const EVP_MD *EVP_sm3(void) { return &sm3_md; }
827
24.875
79
c
openssl
openssl-master/crypto/sm3/sm3.c
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/e_os2.h> #include "sm3_local.h" int ossl_sm3_init(SM3_CTX *c) { memset(c, 0, sizeof(*c)); c->A = SM3_A; c->B = SM3_B; c->C = SM3_C; c->D = SM3_D; c->E = SM3_E; c->F = SM3_F; c->G = SM3_G; c->H = SM3_H; return 1; } void ossl_sm3_block_data_order(SM3_CTX *ctx, const void *p, size_t num) { const unsigned char *data = p; register unsigned MD32_REG_T A, B, C, D, E, F, G, H; unsigned MD32_REG_T W00, W01, W02, W03, W04, W05, W06, W07, W08, W09, W10, W11, W12, W13, W14, W15; for (; num--;) { A = ctx->A; B = ctx->B; C = ctx->C; D = ctx->D; E = ctx->E; F = ctx->F; G = ctx->G; H = ctx->H; /* * We have to load all message bytes immediately since SM3 reads * them slightly out of order. */ (void)HOST_c2l(data, W00); (void)HOST_c2l(data, W01); (void)HOST_c2l(data, W02); (void)HOST_c2l(data, W03); (void)HOST_c2l(data, W04); (void)HOST_c2l(data, W05); (void)HOST_c2l(data, W06); (void)HOST_c2l(data, W07); (void)HOST_c2l(data, W08); (void)HOST_c2l(data, W09); (void)HOST_c2l(data, W10); (void)HOST_c2l(data, W11); (void)HOST_c2l(data, W12); (void)HOST_c2l(data, W13); (void)HOST_c2l(data, W14); (void)HOST_c2l(data, W15); R1(A, B, C, D, E, F, G, H, 0x79CC4519, W00, W00 ^ W04); W00 = EXPAND(W00, W07, W13, W03, W10); R1(D, A, B, C, H, E, F, G, 0xF3988A32, W01, W01 ^ W05); W01 = EXPAND(W01, W08, W14, W04, W11); R1(C, D, A, B, G, H, E, F, 0xE7311465, W02, W02 ^ W06); W02 = EXPAND(W02, W09, W15, W05, W12); R1(B, C, D, A, F, G, H, E, 0xCE6228CB, W03, W03 ^ W07); W03 = EXPAND(W03, W10, W00, W06, W13); R1(A, B, C, D, E, F, G, H, 0x9CC45197, W04, W04 ^ W08); W04 = EXPAND(W04, W11, W01, W07, W14); R1(D, A, B, C, H, E, F, G, 0x3988A32F, W05, W05 ^ W09); W05 = EXPAND(W05, W12, W02, W08, W15); R1(C, D, A, B, G, H, E, F, 0x7311465E, W06, W06 ^ W10); W06 = EXPAND(W06, W13, W03, W09, W00); R1(B, C, D, A, F, G, H, E, 0xE6228CBC, W07, W07 ^ W11); W07 = EXPAND(W07, W14, W04, W10, W01); R1(A, B, C, D, E, F, G, H, 0xCC451979, W08, W08 ^ W12); W08 = EXPAND(W08, W15, W05, W11, W02); R1(D, A, B, C, H, E, F, G, 0x988A32F3, W09, W09 ^ W13); W09 = EXPAND(W09, W00, W06, W12, W03); R1(C, D, A, B, G, H, E, F, 0x311465E7, W10, W10 ^ W14); W10 = EXPAND(W10, W01, W07, W13, W04); R1(B, C, D, A, F, G, H, E, 0x6228CBCE, W11, W11 ^ W15); W11 = EXPAND(W11, W02, W08, W14, W05); R1(A, B, C, D, E, F, G, H, 0xC451979C, W12, W12 ^ W00); W12 = EXPAND(W12, W03, W09, W15, W06); R1(D, A, B, C, H, E, F, G, 0x88A32F39, W13, W13 ^ W01); W13 = EXPAND(W13, W04, W10, W00, W07); R1(C, D, A, B, G, H, E, F, 0x11465E73, W14, W14 ^ W02); W14 = EXPAND(W14, W05, W11, W01, W08); R1(B, C, D, A, F, G, H, E, 0x228CBCE6, W15, W15 ^ W03); W15 = EXPAND(W15, W06, W12, W02, W09); R2(A, B, C, D, E, F, G, H, 0x9D8A7A87, W00, W00 ^ W04); W00 = EXPAND(W00, W07, W13, W03, W10); R2(D, A, B, C, H, E, F, G, 0x3B14F50F, W01, W01 ^ W05); W01 = EXPAND(W01, W08, W14, W04, W11); R2(C, D, A, B, G, H, E, F, 0x7629EA1E, W02, W02 ^ W06); W02 = EXPAND(W02, W09, W15, W05, W12); R2(B, C, D, A, F, G, H, E, 0xEC53D43C, W03, W03 ^ W07); W03 = EXPAND(W03, W10, W00, W06, W13); R2(A, B, C, D, E, F, G, H, 0xD8A7A879, W04, W04 ^ W08); W04 = EXPAND(W04, W11, W01, W07, W14); R2(D, A, B, C, H, E, F, G, 0xB14F50F3, W05, W05 ^ W09); W05 = EXPAND(W05, W12, W02, W08, W15); R2(C, D, A, B, G, H, E, F, 0x629EA1E7, W06, W06 ^ W10); W06 = EXPAND(W06, W13, W03, W09, W00); R2(B, C, D, A, F, G, H, E, 0xC53D43CE, W07, W07 ^ W11); W07 = EXPAND(W07, W14, W04, W10, W01); R2(A, B, C, D, E, F, G, H, 0x8A7A879D, W08, W08 ^ W12); W08 = EXPAND(W08, W15, W05, W11, W02); R2(D, A, B, C, H, E, F, G, 0x14F50F3B, W09, W09 ^ W13); W09 = EXPAND(W09, W00, W06, W12, W03); R2(C, D, A, B, G, H, E, F, 0x29EA1E76, W10, W10 ^ W14); W10 = EXPAND(W10, W01, W07, W13, W04); R2(B, C, D, A, F, G, H, E, 0x53D43CEC, W11, W11 ^ W15); W11 = EXPAND(W11, W02, W08, W14, W05); R2(A, B, C, D, E, F, G, H, 0xA7A879D8, W12, W12 ^ W00); W12 = EXPAND(W12, W03, W09, W15, W06); R2(D, A, B, C, H, E, F, G, 0x4F50F3B1, W13, W13 ^ W01); W13 = EXPAND(W13, W04, W10, W00, W07); R2(C, D, A, B, G, H, E, F, 0x9EA1E762, W14, W14 ^ W02); W14 = EXPAND(W14, W05, W11, W01, W08); R2(B, C, D, A, F, G, H, E, 0x3D43CEC5, W15, W15 ^ W03); W15 = EXPAND(W15, W06, W12, W02, W09); R2(A, B, C, D, E, F, G, H, 0x7A879D8A, W00, W00 ^ W04); W00 = EXPAND(W00, W07, W13, W03, W10); R2(D, A, B, C, H, E, F, G, 0xF50F3B14, W01, W01 ^ W05); W01 = EXPAND(W01, W08, W14, W04, W11); R2(C, D, A, B, G, H, E, F, 0xEA1E7629, W02, W02 ^ W06); W02 = EXPAND(W02, W09, W15, W05, W12); R2(B, C, D, A, F, G, H, E, 0xD43CEC53, W03, W03 ^ W07); W03 = EXPAND(W03, W10, W00, W06, W13); R2(A, B, C, D, E, F, G, H, 0xA879D8A7, W04, W04 ^ W08); W04 = EXPAND(W04, W11, W01, W07, W14); R2(D, A, B, C, H, E, F, G, 0x50F3B14F, W05, W05 ^ W09); W05 = EXPAND(W05, W12, W02, W08, W15); R2(C, D, A, B, G, H, E, F, 0xA1E7629E, W06, W06 ^ W10); W06 = EXPAND(W06, W13, W03, W09, W00); R2(B, C, D, A, F, G, H, E, 0x43CEC53D, W07, W07 ^ W11); W07 = EXPAND(W07, W14, W04, W10, W01); R2(A, B, C, D, E, F, G, H, 0x879D8A7A, W08, W08 ^ W12); W08 = EXPAND(W08, W15, W05, W11, W02); R2(D, A, B, C, H, E, F, G, 0x0F3B14F5, W09, W09 ^ W13); W09 = EXPAND(W09, W00, W06, W12, W03); R2(C, D, A, B, G, H, E, F, 0x1E7629EA, W10, W10 ^ W14); W10 = EXPAND(W10, W01, W07, W13, W04); R2(B, C, D, A, F, G, H, E, 0x3CEC53D4, W11, W11 ^ W15); W11 = EXPAND(W11, W02, W08, W14, W05); R2(A, B, C, D, E, F, G, H, 0x79D8A7A8, W12, W12 ^ W00); W12 = EXPAND(W12, W03, W09, W15, W06); R2(D, A, B, C, H, E, F, G, 0xF3B14F50, W13, W13 ^ W01); W13 = EXPAND(W13, W04, W10, W00, W07); R2(C, D, A, B, G, H, E, F, 0xE7629EA1, W14, W14 ^ W02); W14 = EXPAND(W14, W05, W11, W01, W08); R2(B, C, D, A, F, G, H, E, 0xCEC53D43, W15, W15 ^ W03); W15 = EXPAND(W15, W06, W12, W02, W09); R2(A, B, C, D, E, F, G, H, 0x9D8A7A87, W00, W00 ^ W04); W00 = EXPAND(W00, W07, W13, W03, W10); R2(D, A, B, C, H, E, F, G, 0x3B14F50F, W01, W01 ^ W05); W01 = EXPAND(W01, W08, W14, W04, W11); R2(C, D, A, B, G, H, E, F, 0x7629EA1E, W02, W02 ^ W06); W02 = EXPAND(W02, W09, W15, W05, W12); R2(B, C, D, A, F, G, H, E, 0xEC53D43C, W03, W03 ^ W07); W03 = EXPAND(W03, W10, W00, W06, W13); R2(A, B, C, D, E, F, G, H, 0xD8A7A879, W04, W04 ^ W08); R2(D, A, B, C, H, E, F, G, 0xB14F50F3, W05, W05 ^ W09); R2(C, D, A, B, G, H, E, F, 0x629EA1E7, W06, W06 ^ W10); R2(B, C, D, A, F, G, H, E, 0xC53D43CE, W07, W07 ^ W11); R2(A, B, C, D, E, F, G, H, 0x8A7A879D, W08, W08 ^ W12); R2(D, A, B, C, H, E, F, G, 0x14F50F3B, W09, W09 ^ W13); R2(C, D, A, B, G, H, E, F, 0x29EA1E76, W10, W10 ^ W14); R2(B, C, D, A, F, G, H, E, 0x53D43CEC, W11, W11 ^ W15); R2(A, B, C, D, E, F, G, H, 0xA7A879D8, W12, W12 ^ W00); R2(D, A, B, C, H, E, F, G, 0x4F50F3B1, W13, W13 ^ W01); R2(C, D, A, B, G, H, E, F, 0x9EA1E762, W14, W14 ^ W02); R2(B, C, D, A, F, G, H, E, 0x3D43CEC5, W15, W15 ^ W03); ctx->A ^= A; ctx->B ^= B; ctx->C ^= C; ctx->D ^= D; ctx->E ^= E; ctx->F ^= F; ctx->G ^= G; ctx->H ^= H; } }
8,583
42.795918
74
c
openssl
openssl-master/crypto/sm3/sm3_local.h
/* * Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include "internal/sm3.h" #define DATA_ORDER_IS_BIG_ENDIAN #define HASH_LONG SM3_WORD #define HASH_CTX SM3_CTX #define HASH_CBLOCK SM3_CBLOCK #define HASH_UPDATE ossl_sm3_update #define HASH_TRANSFORM ossl_sm3_transform #define HASH_FINAL ossl_sm3_final #define HASH_MAKE_STRING(c, s) \ do { \ unsigned long ll; \ ll=(c)->A; (void)HOST_l2c(ll, (s)); \ ll=(c)->B; (void)HOST_l2c(ll, (s)); \ ll=(c)->C; (void)HOST_l2c(ll, (s)); \ ll=(c)->D; (void)HOST_l2c(ll, (s)); \ ll=(c)->E; (void)HOST_l2c(ll, (s)); \ ll=(c)->F; (void)HOST_l2c(ll, (s)); \ ll=(c)->G; (void)HOST_l2c(ll, (s)); \ ll=(c)->H; (void)HOST_l2c(ll, (s)); \ } while (0) #if defined(OPENSSL_SM3_ASM) # if defined(__aarch64__) # include "crypto/arm_arch.h" # define HWSM3_CAPABLE (OPENSSL_armcap_P & ARMV8_SM3) void ossl_hwsm3_block_data_order(SM3_CTX *c, const void *p, size_t num); # endif #endif #if defined(HWSM3_CAPABLE) # define HASH_BLOCK_DATA_ORDER (HWSM3_CAPABLE ? ossl_hwsm3_block_data_order \ : ossl_sm3_block_data_order) #else # define HASH_BLOCK_DATA_ORDER ossl_sm3_block_data_order #endif void ossl_sm3_block_data_order(SM3_CTX *c, const void *p, size_t num); void ossl_sm3_transform(SM3_CTX *c, const unsigned char *data); #include "crypto/md32_common.h" #ifndef PEDANTIC # if defined(__GNUC__) && __GNUC__>=2 && \ !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if defined(__riscv_zksh) # define P0(x) ({ MD32_REG_T ret; \ asm ("sm3p0 %0, %1" \ : "=r"(ret) \ : "r"(x)); ret; }) # define P1(x) ({ MD32_REG_T ret; \ asm ("sm3p1 %0, %1" \ : "=r"(ret) \ : "r"(x)); ret; }) # endif # endif #endif #ifndef P0 # define P0(X) (X ^ ROTATE(X, 9) ^ ROTATE(X, 17)) #endif #ifndef P1 # define P1(X) (X ^ ROTATE(X, 15) ^ ROTATE(X, 23)) #endif #define FF0(X,Y,Z) (X ^ Y ^ Z) #define GG0(X,Y,Z) (X ^ Y ^ Z) #define FF1(X,Y,Z) ((X & Y) | ((X | Y) & Z)) #define GG1(X,Y,Z) ((Z ^ (X & (Y ^ Z)))) #define EXPAND(W0,W7,W13,W3,W10) \ (P1(W0 ^ W7 ^ ROTATE(W13, 15)) ^ ROTATE(W3, 7) ^ W10) #define RND(A, B, C, D, E, F, G, H, TJ, Wi, Wj, FF, GG) \ do { \ const SM3_WORD A12 = ROTATE(A, 12); \ const SM3_WORD A12_SM = A12 + E + TJ; \ const SM3_WORD SS1 = ROTATE(A12_SM, 7); \ const SM3_WORD TT1 = FF(A, B, C) + D + (SS1 ^ A12) + (Wj); \ const SM3_WORD TT2 = GG(E, F, G) + H + SS1 + Wi; \ B = ROTATE(B, 9); \ D = TT1; \ F = ROTATE(F, 19); \ H = P0(TT2); \ } while(0) #define R1(A,B,C,D,E,F,G,H,TJ,Wi,Wj) \ RND(A,B,C,D,E,F,G,H,TJ,Wi,Wj,FF0,GG0) #define R2(A,B,C,D,E,F,G,H,TJ,Wi,Wj) \ RND(A,B,C,D,E,F,G,H,TJ,Wi,Wj,FF1,GG1) #define SM3_A 0x7380166fUL #define SM3_B 0x4914b2b9UL #define SM3_C 0x172442d7UL #define SM3_D 0xda8a0600UL #define SM3_E 0xa96f30bcUL #define SM3_F 0x163138aaUL #define SM3_G 0xe38dee4dUL #define SM3_H 0xb0fb0e4eUL
4,028
34.034783
77
h
openssl
openssl-master/crypto/sm4/sm4.c
/* * Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. All Rights Reserved. * Ported from Ribose contributions from Botan. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/e_os2.h> #include "crypto/sm4.h" static const uint8_t SM4_S[256] = { 0xD6, 0x90, 0xE9, 0xFE, 0xCC, 0xE1, 0x3D, 0xB7, 0x16, 0xB6, 0x14, 0xC2, 0x28, 0xFB, 0x2C, 0x05, 0x2B, 0x67, 0x9A, 0x76, 0x2A, 0xBE, 0x04, 0xC3, 0xAA, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9C, 0x42, 0x50, 0xF4, 0x91, 0xEF, 0x98, 0x7A, 0x33, 0x54, 0x0B, 0x43, 0xED, 0xCF, 0xAC, 0x62, 0xE4, 0xB3, 0x1C, 0xA9, 0xC9, 0x08, 0xE8, 0x95, 0x80, 0xDF, 0x94, 0xFA, 0x75, 0x8F, 0x3F, 0xA6, 0x47, 0x07, 0xA7, 0xFC, 0xF3, 0x73, 0x17, 0xBA, 0x83, 0x59, 0x3C, 0x19, 0xE6, 0x85, 0x4F, 0xA8, 0x68, 0x6B, 0x81, 0xB2, 0x71, 0x64, 0xDA, 0x8B, 0xF8, 0xEB, 0x0F, 0x4B, 0x70, 0x56, 0x9D, 0x35, 0x1E, 0x24, 0x0E, 0x5E, 0x63, 0x58, 0xD1, 0xA2, 0x25, 0x22, 0x7C, 0x3B, 0x01, 0x21, 0x78, 0x87, 0xD4, 0x00, 0x46, 0x57, 0x9F, 0xD3, 0x27, 0x52, 0x4C, 0x36, 0x02, 0xE7, 0xA0, 0xC4, 0xC8, 0x9E, 0xEA, 0xBF, 0x8A, 0xD2, 0x40, 0xC7, 0x38, 0xB5, 0xA3, 0xF7, 0xF2, 0xCE, 0xF9, 0x61, 0x15, 0xA1, 0xE0, 0xAE, 0x5D, 0xA4, 0x9B, 0x34, 0x1A, 0x55, 0xAD, 0x93, 0x32, 0x30, 0xF5, 0x8C, 0xB1, 0xE3, 0x1D, 0xF6, 0xE2, 0x2E, 0x82, 0x66, 0xCA, 0x60, 0xC0, 0x29, 0x23, 0xAB, 0x0D, 0x53, 0x4E, 0x6F, 0xD5, 0xDB, 0x37, 0x45, 0xDE, 0xFD, 0x8E, 0x2F, 0x03, 0xFF, 0x6A, 0x72, 0x6D, 0x6C, 0x5B, 0x51, 0x8D, 0x1B, 0xAF, 0x92, 0xBB, 0xDD, 0xBC, 0x7F, 0x11, 0xD9, 0x5C, 0x41, 0x1F, 0x10, 0x5A, 0xD8, 0x0A, 0xC1, 0x31, 0x88, 0xA5, 0xCD, 0x7B, 0xBD, 0x2D, 0x74, 0xD0, 0x12, 0xB8, 0xE5, 0xB4, 0xB0, 0x89, 0x69, 0x97, 0x4A, 0x0C, 0x96, 0x77, 0x7E, 0x65, 0xB9, 0xF1, 0x09, 0xC5, 0x6E, 0xC6, 0x84, 0x18, 0xF0, 0x7D, 0xEC, 0x3A, 0xDC, 0x4D, 0x20, 0x79, 0xEE, 0x5F, 0x3E, 0xD7, 0xCB, 0x39, 0x48 }; /* * SM4_SBOX_T[j] == L(SM4_SBOX[j]). */ static const uint32_t SM4_SBOX_T0[256] = { 0x8ED55B5B, 0xD0924242, 0x4DEAA7A7, 0x06FDFBFB, 0xFCCF3333, 0x65E28787, 0xC93DF4F4, 0x6BB5DEDE, 0x4E165858, 0x6EB4DADA, 0x44145050, 0xCAC10B0B, 0x8828A0A0, 0x17F8EFEF, 0x9C2CB0B0, 0x11051414, 0x872BACAC, 0xFB669D9D, 0xF2986A6A, 0xAE77D9D9, 0x822AA8A8, 0x46BCFAFA, 0x14041010, 0xCFC00F0F, 0x02A8AAAA, 0x54451111, 0x5F134C4C, 0xBE269898, 0x6D482525, 0x9E841A1A, 0x1E061818, 0xFD9B6666, 0xEC9E7272, 0x4A430909, 0x10514141, 0x24F7D3D3, 0xD5934646, 0x53ECBFBF, 0xF89A6262, 0x927BE9E9, 0xFF33CCCC, 0x04555151, 0x270B2C2C, 0x4F420D0D, 0x59EEB7B7, 0xF3CC3F3F, 0x1CAEB2B2, 0xEA638989, 0x74E79393, 0x7FB1CECE, 0x6C1C7070, 0x0DABA6A6, 0xEDCA2727, 0x28082020, 0x48EBA3A3, 0xC1975656, 0x80820202, 0xA3DC7F7F, 0xC4965252, 0x12F9EBEB, 0xA174D5D5, 0xB38D3E3E, 0xC33FFCFC, 0x3EA49A9A, 0x5B461D1D, 0x1B071C1C, 0x3BA59E9E, 0x0CFFF3F3, 0x3FF0CFCF, 0xBF72CDCD, 0x4B175C5C, 0x52B8EAEA, 0x8F810E0E, 0x3D586565, 0xCC3CF0F0, 0x7D196464, 0x7EE59B9B, 0x91871616, 0x734E3D3D, 0x08AAA2A2, 0xC869A1A1, 0xC76AADAD, 0x85830606, 0x7AB0CACA, 0xB570C5C5, 0xF4659191, 0xB2D96B6B, 0xA7892E2E, 0x18FBE3E3, 0x47E8AFAF, 0x330F3C3C, 0x674A2D2D, 0xB071C1C1, 0x0E575959, 0xE99F7676, 0xE135D4D4, 0x661E7878, 0xB4249090, 0x360E3838, 0x265F7979, 0xEF628D8D, 0x38596161, 0x95D24747, 0x2AA08A8A, 0xB1259494, 0xAA228888, 0x8C7DF1F1, 0xD73BECEC, 0x05010404, 0xA5218484, 0x9879E1E1, 0x9B851E1E, 0x84D75353, 0x00000000, 0x5E471919, 0x0B565D5D, 0xE39D7E7E, 0x9FD04F4F, 0xBB279C9C, 0x1A534949, 0x7C4D3131, 0xEE36D8D8, 0x0A020808, 0x7BE49F9F, 0x20A28282, 0xD4C71313, 0xE8CB2323, 0xE69C7A7A, 0x42E9ABAB, 0x43BDFEFE, 0xA2882A2A, 0x9AD14B4B, 0x40410101, 0xDBC41F1F, 0xD838E0E0, 0x61B7D6D6, 0x2FA18E8E, 0x2BF4DFDF, 0x3AF1CBCB, 0xF6CD3B3B, 0x1DFAE7E7, 0xE5608585, 0x41155454, 0x25A38686, 0x60E38383, 0x16ACBABA, 0x295C7575, 0x34A69292, 0xF7996E6E, 0xE434D0D0, 0x721A6868, 0x01545555, 0x19AFB6B6, 0xDF914E4E, 0xFA32C8C8, 0xF030C0C0, 0x21F6D7D7, 0xBC8E3232, 0x75B3C6C6, 0x6FE08F8F, 0x691D7474, 0x2EF5DBDB, 0x6AE18B8B, 0x962EB8B8, 0x8A800A0A, 0xFE679999, 0xE2C92B2B, 0xE0618181, 0xC0C30303, 0x8D29A4A4, 0xAF238C8C, 0x07A9AEAE, 0x390D3434, 0x1F524D4D, 0x764F3939, 0xD36EBDBD, 0x81D65757, 0xB7D86F6F, 0xEB37DCDC, 0x51441515, 0xA6DD7B7B, 0x09FEF7F7, 0xB68C3A3A, 0x932FBCBC, 0x0F030C0C, 0x03FCFFFF, 0xC26BA9A9, 0xBA73C9C9, 0xD96CB5B5, 0xDC6DB1B1, 0x375A6D6D, 0x15504545, 0xB98F3636, 0x771B6C6C, 0x13ADBEBE, 0xDA904A4A, 0x57B9EEEE, 0xA9DE7777, 0x4CBEF2F2, 0x837EFDFD, 0x55114444, 0xBDDA6767, 0x2C5D7171, 0x45400505, 0x631F7C7C, 0x50104040, 0x325B6969, 0xB8DB6363, 0x220A2828, 0xC5C20707, 0xF531C4C4, 0xA88A2222, 0x31A79696, 0xF9CE3737, 0x977AEDED, 0x49BFF6F6, 0x992DB4B4, 0xA475D1D1, 0x90D34343, 0x5A124848, 0x58BAE2E2, 0x71E69797, 0x64B6D2D2, 0x70B2C2C2, 0xAD8B2626, 0xCD68A5A5, 0xCB955E5E, 0x624B2929, 0x3C0C3030, 0xCE945A5A, 0xAB76DDDD, 0x867FF9F9, 0xF1649595, 0x5DBBE6E6, 0x35F2C7C7, 0x2D092424, 0xD1C61717, 0xD66FB9B9, 0xDEC51B1B, 0x94861212, 0x78186060, 0x30F3C3C3, 0x897CF5F5, 0x5CEFB3B3, 0xD23AE8E8, 0xACDF7373, 0x794C3535, 0xA0208080, 0x9D78E5E5, 0x56EDBBBB, 0x235E7D7D, 0xC63EF8F8, 0x8BD45F5F, 0xE7C82F2F, 0xDD39E4E4, 0x68492121 }; static uint32_t SM4_SBOX_T1[256] = { 0x5B8ED55B, 0x42D09242, 0xA74DEAA7, 0xFB06FDFB, 0x33FCCF33, 0x8765E287, 0xF4C93DF4, 0xDE6BB5DE, 0x584E1658, 0xDA6EB4DA, 0x50441450, 0x0BCAC10B, 0xA08828A0, 0xEF17F8EF, 0xB09C2CB0, 0x14110514, 0xAC872BAC, 0x9DFB669D, 0x6AF2986A, 0xD9AE77D9, 0xA8822AA8, 0xFA46BCFA, 0x10140410, 0x0FCFC00F, 0xAA02A8AA, 0x11544511, 0x4C5F134C, 0x98BE2698, 0x256D4825, 0x1A9E841A, 0x181E0618, 0x66FD9B66, 0x72EC9E72, 0x094A4309, 0x41105141, 0xD324F7D3, 0x46D59346, 0xBF53ECBF, 0x62F89A62, 0xE9927BE9, 0xCCFF33CC, 0x51045551, 0x2C270B2C, 0x0D4F420D, 0xB759EEB7, 0x3FF3CC3F, 0xB21CAEB2, 0x89EA6389, 0x9374E793, 0xCE7FB1CE, 0x706C1C70, 0xA60DABA6, 0x27EDCA27, 0x20280820, 0xA348EBA3, 0x56C19756, 0x02808202, 0x7FA3DC7F, 0x52C49652, 0xEB12F9EB, 0xD5A174D5, 0x3EB38D3E, 0xFCC33FFC, 0x9A3EA49A, 0x1D5B461D, 0x1C1B071C, 0x9E3BA59E, 0xF30CFFF3, 0xCF3FF0CF, 0xCDBF72CD, 0x5C4B175C, 0xEA52B8EA, 0x0E8F810E, 0x653D5865, 0xF0CC3CF0, 0x647D1964, 0x9B7EE59B, 0x16918716, 0x3D734E3D, 0xA208AAA2, 0xA1C869A1, 0xADC76AAD, 0x06858306, 0xCA7AB0CA, 0xC5B570C5, 0x91F46591, 0x6BB2D96B, 0x2EA7892E, 0xE318FBE3, 0xAF47E8AF, 0x3C330F3C, 0x2D674A2D, 0xC1B071C1, 0x590E5759, 0x76E99F76, 0xD4E135D4, 0x78661E78, 0x90B42490, 0x38360E38, 0x79265F79, 0x8DEF628D, 0x61385961, 0x4795D247, 0x8A2AA08A, 0x94B12594, 0x88AA2288, 0xF18C7DF1, 0xECD73BEC, 0x04050104, 0x84A52184, 0xE19879E1, 0x1E9B851E, 0x5384D753, 0x00000000, 0x195E4719, 0x5D0B565D, 0x7EE39D7E, 0x4F9FD04F, 0x9CBB279C, 0x491A5349, 0x317C4D31, 0xD8EE36D8, 0x080A0208, 0x9F7BE49F, 0x8220A282, 0x13D4C713, 0x23E8CB23, 0x7AE69C7A, 0xAB42E9AB, 0xFE43BDFE, 0x2AA2882A, 0x4B9AD14B, 0x01404101, 0x1FDBC41F, 0xE0D838E0, 0xD661B7D6, 0x8E2FA18E, 0xDF2BF4DF, 0xCB3AF1CB, 0x3BF6CD3B, 0xE71DFAE7, 0x85E56085, 0x54411554, 0x8625A386, 0x8360E383, 0xBA16ACBA, 0x75295C75, 0x9234A692, 0x6EF7996E, 0xD0E434D0, 0x68721A68, 0x55015455, 0xB619AFB6, 0x4EDF914E, 0xC8FA32C8, 0xC0F030C0, 0xD721F6D7, 0x32BC8E32, 0xC675B3C6, 0x8F6FE08F, 0x74691D74, 0xDB2EF5DB, 0x8B6AE18B, 0xB8962EB8, 0x0A8A800A, 0x99FE6799, 0x2BE2C92B, 0x81E06181, 0x03C0C303, 0xA48D29A4, 0x8CAF238C, 0xAE07A9AE, 0x34390D34, 0x4D1F524D, 0x39764F39, 0xBDD36EBD, 0x5781D657, 0x6FB7D86F, 0xDCEB37DC, 0x15514415, 0x7BA6DD7B, 0xF709FEF7, 0x3AB68C3A, 0xBC932FBC, 0x0C0F030C, 0xFF03FCFF, 0xA9C26BA9, 0xC9BA73C9, 0xB5D96CB5, 0xB1DC6DB1, 0x6D375A6D, 0x45155045, 0x36B98F36, 0x6C771B6C, 0xBE13ADBE, 0x4ADA904A, 0xEE57B9EE, 0x77A9DE77, 0xF24CBEF2, 0xFD837EFD, 0x44551144, 0x67BDDA67, 0x712C5D71, 0x05454005, 0x7C631F7C, 0x40501040, 0x69325B69, 0x63B8DB63, 0x28220A28, 0x07C5C207, 0xC4F531C4, 0x22A88A22, 0x9631A796, 0x37F9CE37, 0xED977AED, 0xF649BFF6, 0xB4992DB4, 0xD1A475D1, 0x4390D343, 0x485A1248, 0xE258BAE2, 0x9771E697, 0xD264B6D2, 0xC270B2C2, 0x26AD8B26, 0xA5CD68A5, 0x5ECB955E, 0x29624B29, 0x303C0C30, 0x5ACE945A, 0xDDAB76DD, 0xF9867FF9, 0x95F16495, 0xE65DBBE6, 0xC735F2C7, 0x242D0924, 0x17D1C617, 0xB9D66FB9, 0x1BDEC51B, 0x12948612, 0x60781860, 0xC330F3C3, 0xF5897CF5, 0xB35CEFB3, 0xE8D23AE8, 0x73ACDF73, 0x35794C35, 0x80A02080, 0xE59D78E5, 0xBB56EDBB, 0x7D235E7D, 0xF8C63EF8, 0x5F8BD45F, 0x2FE7C82F, 0xE4DD39E4, 0x21684921}; static uint32_t SM4_SBOX_T2[256] = { 0x5B5B8ED5, 0x4242D092, 0xA7A74DEA, 0xFBFB06FD, 0x3333FCCF, 0x878765E2, 0xF4F4C93D, 0xDEDE6BB5, 0x58584E16, 0xDADA6EB4, 0x50504414, 0x0B0BCAC1, 0xA0A08828, 0xEFEF17F8, 0xB0B09C2C, 0x14141105, 0xACAC872B, 0x9D9DFB66, 0x6A6AF298, 0xD9D9AE77, 0xA8A8822A, 0xFAFA46BC, 0x10101404, 0x0F0FCFC0, 0xAAAA02A8, 0x11115445, 0x4C4C5F13, 0x9898BE26, 0x25256D48, 0x1A1A9E84, 0x18181E06, 0x6666FD9B, 0x7272EC9E, 0x09094A43, 0x41411051, 0xD3D324F7, 0x4646D593, 0xBFBF53EC, 0x6262F89A, 0xE9E9927B, 0xCCCCFF33, 0x51510455, 0x2C2C270B, 0x0D0D4F42, 0xB7B759EE, 0x3F3FF3CC, 0xB2B21CAE, 0x8989EA63, 0x939374E7, 0xCECE7FB1, 0x70706C1C, 0xA6A60DAB, 0x2727EDCA, 0x20202808, 0xA3A348EB, 0x5656C197, 0x02028082, 0x7F7FA3DC, 0x5252C496, 0xEBEB12F9, 0xD5D5A174, 0x3E3EB38D, 0xFCFCC33F, 0x9A9A3EA4, 0x1D1D5B46, 0x1C1C1B07, 0x9E9E3BA5, 0xF3F30CFF, 0xCFCF3FF0, 0xCDCDBF72, 0x5C5C4B17, 0xEAEA52B8, 0x0E0E8F81, 0x65653D58, 0xF0F0CC3C, 0x64647D19, 0x9B9B7EE5, 0x16169187, 0x3D3D734E, 0xA2A208AA, 0xA1A1C869, 0xADADC76A, 0x06068583, 0xCACA7AB0, 0xC5C5B570, 0x9191F465, 0x6B6BB2D9, 0x2E2EA789, 0xE3E318FB, 0xAFAF47E8, 0x3C3C330F, 0x2D2D674A, 0xC1C1B071, 0x59590E57, 0x7676E99F, 0xD4D4E135, 0x7878661E, 0x9090B424, 0x3838360E, 0x7979265F, 0x8D8DEF62, 0x61613859, 0x474795D2, 0x8A8A2AA0, 0x9494B125, 0x8888AA22, 0xF1F18C7D, 0xECECD73B, 0x04040501, 0x8484A521, 0xE1E19879, 0x1E1E9B85, 0x535384D7, 0x00000000, 0x19195E47, 0x5D5D0B56, 0x7E7EE39D, 0x4F4F9FD0, 0x9C9CBB27, 0x49491A53, 0x31317C4D, 0xD8D8EE36, 0x08080A02, 0x9F9F7BE4, 0x828220A2, 0x1313D4C7, 0x2323E8CB, 0x7A7AE69C, 0xABAB42E9, 0xFEFE43BD, 0x2A2AA288, 0x4B4B9AD1, 0x01014041, 0x1F1FDBC4, 0xE0E0D838, 0xD6D661B7, 0x8E8E2FA1, 0xDFDF2BF4, 0xCBCB3AF1, 0x3B3BF6CD, 0xE7E71DFA, 0x8585E560, 0x54544115, 0x868625A3, 0x838360E3, 0xBABA16AC, 0x7575295C, 0x929234A6, 0x6E6EF799, 0xD0D0E434, 0x6868721A, 0x55550154, 0xB6B619AF, 0x4E4EDF91, 0xC8C8FA32, 0xC0C0F030, 0xD7D721F6, 0x3232BC8E, 0xC6C675B3, 0x8F8F6FE0, 0x7474691D, 0xDBDB2EF5, 0x8B8B6AE1, 0xB8B8962E, 0x0A0A8A80, 0x9999FE67, 0x2B2BE2C9, 0x8181E061, 0x0303C0C3, 0xA4A48D29, 0x8C8CAF23, 0xAEAE07A9, 0x3434390D, 0x4D4D1F52, 0x3939764F, 0xBDBDD36E, 0x575781D6, 0x6F6FB7D8, 0xDCDCEB37, 0x15155144, 0x7B7BA6DD, 0xF7F709FE, 0x3A3AB68C, 0xBCBC932F, 0x0C0C0F03, 0xFFFF03FC, 0xA9A9C26B, 0xC9C9BA73, 0xB5B5D96C, 0xB1B1DC6D, 0x6D6D375A, 0x45451550, 0x3636B98F, 0x6C6C771B, 0xBEBE13AD, 0x4A4ADA90, 0xEEEE57B9, 0x7777A9DE, 0xF2F24CBE, 0xFDFD837E, 0x44445511, 0x6767BDDA, 0x71712C5D, 0x05054540, 0x7C7C631F, 0x40405010, 0x6969325B, 0x6363B8DB, 0x2828220A, 0x0707C5C2, 0xC4C4F531, 0x2222A88A, 0x969631A7, 0x3737F9CE, 0xEDED977A, 0xF6F649BF, 0xB4B4992D, 0xD1D1A475, 0x434390D3, 0x48485A12, 0xE2E258BA, 0x979771E6, 0xD2D264B6, 0xC2C270B2, 0x2626AD8B, 0xA5A5CD68, 0x5E5ECB95, 0x2929624B, 0x30303C0C, 0x5A5ACE94, 0xDDDDAB76, 0xF9F9867F, 0x9595F164, 0xE6E65DBB, 0xC7C735F2, 0x24242D09, 0x1717D1C6, 0xB9B9D66F, 0x1B1BDEC5, 0x12129486, 0x60607818, 0xC3C330F3, 0xF5F5897C, 0xB3B35CEF, 0xE8E8D23A, 0x7373ACDF, 0x3535794C, 0x8080A020, 0xE5E59D78, 0xBBBB56ED, 0x7D7D235E, 0xF8F8C63E, 0x5F5F8BD4, 0x2F2FE7C8, 0xE4E4DD39, 0x21216849}; static uint32_t SM4_SBOX_T3[256] = { 0xD55B5B8E, 0x924242D0, 0xEAA7A74D, 0xFDFBFB06, 0xCF3333FC, 0xE2878765, 0x3DF4F4C9, 0xB5DEDE6B, 0x1658584E, 0xB4DADA6E, 0x14505044, 0xC10B0BCA, 0x28A0A088, 0xF8EFEF17, 0x2CB0B09C, 0x05141411, 0x2BACAC87, 0x669D9DFB, 0x986A6AF2, 0x77D9D9AE, 0x2AA8A882, 0xBCFAFA46, 0x04101014, 0xC00F0FCF, 0xA8AAAA02, 0x45111154, 0x134C4C5F, 0x269898BE, 0x4825256D, 0x841A1A9E, 0x0618181E, 0x9B6666FD, 0x9E7272EC, 0x4309094A, 0x51414110, 0xF7D3D324, 0x934646D5, 0xECBFBF53, 0x9A6262F8, 0x7BE9E992, 0x33CCCCFF, 0x55515104, 0x0B2C2C27, 0x420D0D4F, 0xEEB7B759, 0xCC3F3FF3, 0xAEB2B21C, 0x638989EA, 0xE7939374, 0xB1CECE7F, 0x1C70706C, 0xABA6A60D, 0xCA2727ED, 0x08202028, 0xEBA3A348, 0x975656C1, 0x82020280, 0xDC7F7FA3, 0x965252C4, 0xF9EBEB12, 0x74D5D5A1, 0x8D3E3EB3, 0x3FFCFCC3, 0xA49A9A3E, 0x461D1D5B, 0x071C1C1B, 0xA59E9E3B, 0xFFF3F30C, 0xF0CFCF3F, 0x72CDCDBF, 0x175C5C4B, 0xB8EAEA52, 0x810E0E8F, 0x5865653D, 0x3CF0F0CC, 0x1964647D, 0xE59B9B7E, 0x87161691, 0x4E3D3D73, 0xAAA2A208, 0x69A1A1C8, 0x6AADADC7, 0x83060685, 0xB0CACA7A, 0x70C5C5B5, 0x659191F4, 0xD96B6BB2, 0x892E2EA7, 0xFBE3E318, 0xE8AFAF47, 0x0F3C3C33, 0x4A2D2D67, 0x71C1C1B0, 0x5759590E, 0x9F7676E9, 0x35D4D4E1, 0x1E787866, 0x249090B4, 0x0E383836, 0x5F797926, 0x628D8DEF, 0x59616138, 0xD2474795, 0xA08A8A2A, 0x259494B1, 0x228888AA, 0x7DF1F18C, 0x3BECECD7, 0x01040405, 0x218484A5, 0x79E1E198, 0x851E1E9B, 0xD7535384, 0x00000000, 0x4719195E, 0x565D5D0B, 0x9D7E7EE3, 0xD04F4F9F, 0x279C9CBB, 0x5349491A, 0x4D31317C, 0x36D8D8EE, 0x0208080A, 0xE49F9F7B, 0xA2828220, 0xC71313D4, 0xCB2323E8, 0x9C7A7AE6, 0xE9ABAB42, 0xBDFEFE43, 0x882A2AA2, 0xD14B4B9A, 0x41010140, 0xC41F1FDB, 0x38E0E0D8, 0xB7D6D661, 0xA18E8E2F, 0xF4DFDF2B, 0xF1CBCB3A, 0xCD3B3BF6, 0xFAE7E71D, 0x608585E5, 0x15545441, 0xA3868625, 0xE3838360, 0xACBABA16, 0x5C757529, 0xA6929234, 0x996E6EF7, 0x34D0D0E4, 0x1A686872, 0x54555501, 0xAFB6B619, 0x914E4EDF, 0x32C8C8FA, 0x30C0C0F0, 0xF6D7D721, 0x8E3232BC, 0xB3C6C675, 0xE08F8F6F, 0x1D747469, 0xF5DBDB2E, 0xE18B8B6A, 0x2EB8B896, 0x800A0A8A, 0x679999FE, 0xC92B2BE2, 0x618181E0, 0xC30303C0, 0x29A4A48D, 0x238C8CAF, 0xA9AEAE07, 0x0D343439, 0x524D4D1F, 0x4F393976, 0x6EBDBDD3, 0xD6575781, 0xD86F6FB7, 0x37DCDCEB, 0x44151551, 0xDD7B7BA6, 0xFEF7F709, 0x8C3A3AB6, 0x2FBCBC93, 0x030C0C0F, 0xFCFFFF03, 0x6BA9A9C2, 0x73C9C9BA, 0x6CB5B5D9, 0x6DB1B1DC, 0x5A6D6D37, 0x50454515, 0x8F3636B9, 0x1B6C6C77, 0xADBEBE13, 0x904A4ADA, 0xB9EEEE57, 0xDE7777A9, 0xBEF2F24C, 0x7EFDFD83, 0x11444455, 0xDA6767BD, 0x5D71712C, 0x40050545, 0x1F7C7C63, 0x10404050, 0x5B696932, 0xDB6363B8, 0x0A282822, 0xC20707C5, 0x31C4C4F5, 0x8A2222A8, 0xA7969631, 0xCE3737F9, 0x7AEDED97, 0xBFF6F649, 0x2DB4B499, 0x75D1D1A4, 0xD3434390, 0x1248485A, 0xBAE2E258, 0xE6979771, 0xB6D2D264, 0xB2C2C270, 0x8B2626AD, 0x68A5A5CD, 0x955E5ECB, 0x4B292962, 0x0C30303C, 0x945A5ACE, 0x76DDDDAB, 0x7FF9F986, 0x649595F1, 0xBBE6E65D, 0xF2C7C735, 0x0924242D, 0xC61717D1, 0x6FB9B9D6, 0xC51B1BDE, 0x86121294, 0x18606078, 0xF3C3C330, 0x7CF5F589, 0xEFB3B35C, 0x3AE8E8D2, 0xDF7373AC, 0x4C353579, 0x208080A0, 0x78E5E59D, 0xEDBBBB56, 0x5E7D7D23, 0x3EF8F8C6, 0xD45F5F8B, 0xC82F2FE7, 0x39E4E4DD, 0x49212168}; static ossl_inline uint32_t rotl(uint32_t a, uint8_t n) { return (a << n) | (a >> (32 - n)); } static ossl_inline uint32_t load_u32_be(const uint8_t *b, uint32_t n) { return ((uint32_t)b[4 * n] << 24) | ((uint32_t)b[4 * n + 1] << 16) | ((uint32_t)b[4 * n + 2] << 8) | ((uint32_t)b[4 * n + 3]); } static ossl_inline void store_u32_be(uint32_t v, uint8_t *b) { b[0] = (uint8_t)(v >> 24); b[1] = (uint8_t)(v >> 16); b[2] = (uint8_t)(v >> 8); b[3] = (uint8_t)(v); } static ossl_inline uint32_t SM4_T_non_lin_sub(uint32_t X) { uint32_t t = 0; t |= ((uint32_t)SM4_S[(uint8_t)(X >> 24)]) << 24; t |= ((uint32_t)SM4_S[(uint8_t)(X >> 16)]) << 16; t |= ((uint32_t)SM4_S[(uint8_t)(X >> 8)]) << 8; t |= SM4_S[(uint8_t)X]; return t; } static ossl_inline uint32_t SM4_T_slow(uint32_t X) { uint32_t t = SM4_T_non_lin_sub(X); /* * L linear transform */ return t ^ rotl(t, 2) ^ rotl(t, 10) ^ rotl(t, 18) ^ rotl(t, 24); } static ossl_inline uint32_t SM4_T(uint32_t X) { return SM4_SBOX_T0[(uint8_t)(X >> 24)] ^ SM4_SBOX_T1[(uint8_t)(X >> 16)] ^ SM4_SBOX_T2[(uint8_t)(X >> 8)] ^ SM4_SBOX_T3[(uint8_t)X]; } static ossl_inline uint32_t SM4_key_sub(uint32_t X) { uint32_t t = SM4_T_non_lin_sub(X); return t ^ rotl(t, 13) ^ rotl(t, 23); } int ossl_sm4_set_key(const uint8_t *key, SM4_KEY *ks) { /* * Family Key */ static const uint32_t FK[4] = { 0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc }; /* * Constant Key */ static const uint32_t CK[32] = { 0x00070E15, 0x1C232A31, 0x383F464D, 0x545B6269, 0x70777E85, 0x8C939AA1, 0xA8AFB6BD, 0xC4CBD2D9, 0xE0E7EEF5, 0xFC030A11, 0x181F262D, 0x343B4249, 0x50575E65, 0x6C737A81, 0x888F969D, 0xA4ABB2B9, 0xC0C7CED5, 0xDCE3EAF1, 0xF8FF060D, 0x141B2229, 0x30373E45, 0x4C535A61, 0x686F767D, 0x848B9299, 0xA0A7AEB5, 0xBCC3CAD1, 0xD8DFE6ED, 0xF4FB0209, 0x10171E25, 0x2C333A41, 0x484F565D, 0x646B7279 }; uint32_t K[4]; int i; K[0] = load_u32_be(key, 0) ^ FK[0]; K[1] = load_u32_be(key, 1) ^ FK[1]; K[2] = load_u32_be(key, 2) ^ FK[2]; K[3] = load_u32_be(key, 3) ^ FK[3]; for (i = 0; i < SM4_KEY_SCHEDULE; i = i + 4) { K[0] ^= SM4_key_sub(K[1] ^ K[2] ^ K[3] ^ CK[i]); K[1] ^= SM4_key_sub(K[2] ^ K[3] ^ K[0] ^ CK[i + 1]); K[2] ^= SM4_key_sub(K[3] ^ K[0] ^ K[1] ^ CK[i + 2]); K[3] ^= SM4_key_sub(K[0] ^ K[1] ^ K[2] ^ CK[i + 3]); ks->rk[i ] = K[0]; ks->rk[i + 1] = K[1]; ks->rk[i + 2] = K[2]; ks->rk[i + 3] = K[3]; } return 1; } #define SM4_RNDS(k0, k1, k2, k3, F) \ do { \ B0 ^= F(B1 ^ B2 ^ B3 ^ ks->rk[k0]); \ B1 ^= F(B0 ^ B2 ^ B3 ^ ks->rk[k1]); \ B2 ^= F(B0 ^ B1 ^ B3 ^ ks->rk[k2]); \ B3 ^= F(B0 ^ B1 ^ B2 ^ ks->rk[k3]); \ } while(0) void ossl_sm4_encrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks) { uint32_t B0 = load_u32_be(in, 0); uint32_t B1 = load_u32_be(in, 1); uint32_t B2 = load_u32_be(in, 2); uint32_t B3 = load_u32_be(in, 3); /* * Uses byte-wise sbox in the first and last rounds to provide some * protection from cache based side channels. */ SM4_RNDS( 0, 1, 2, 3, SM4_T_slow); SM4_RNDS( 4, 5, 6, 7, SM4_T); SM4_RNDS( 8, 9, 10, 11, SM4_T); SM4_RNDS(12, 13, 14, 15, SM4_T); SM4_RNDS(16, 17, 18, 19, SM4_T); SM4_RNDS(20, 21, 22, 23, SM4_T); SM4_RNDS(24, 25, 26, 27, SM4_T); SM4_RNDS(28, 29, 30, 31, SM4_T_slow); store_u32_be(B3, out); store_u32_be(B2, out + 4); store_u32_be(B1, out + 8); store_u32_be(B0, out + 12); } void ossl_sm4_decrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks) { uint32_t B0 = load_u32_be(in, 0); uint32_t B1 = load_u32_be(in, 1); uint32_t B2 = load_u32_be(in, 2); uint32_t B3 = load_u32_be(in, 3); SM4_RNDS(31, 30, 29, 28, SM4_T_slow); SM4_RNDS(27, 26, 25, 24, SM4_T); SM4_RNDS(23, 22, 21, 20, SM4_T); SM4_RNDS(19, 18, 17, 16, SM4_T); SM4_RNDS(15, 14, 13, 12, SM4_T); SM4_RNDS(11, 10, 9, 8, SM4_T); SM4_RNDS( 7, 6, 5, 4, SM4_T); SM4_RNDS( 3, 2, 1, 0, SM4_T_slow); store_u32_be(B3, out); store_u32_be(B2, out + 4); store_u32_be(B1, out + 8); store_u32_be(B0, out + 12); }
19,802
51.113158
75
c
openssl
openssl-master/crypto/srp/srp_lib.c
/* * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2004, EdelKey Project. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * Originally written by Christophe Renou and Peter Sylvester, * for the EdelKey project. */ /* All the SRP APIs in this file are deprecated */ #define OPENSSL_SUPPRESS_DEPRECATED #ifndef OPENSSL_NO_SRP # include "internal/cryptlib.h" # include <openssl/sha.h> # include <openssl/srp.h> # include <openssl/evp.h> # include "crypto/bn_srp.h" /* calculate = SHA1(PAD(x) || PAD(y)) */ static BIGNUM *srp_Calc_xy(const BIGNUM *x, const BIGNUM *y, const BIGNUM *N, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char digest[SHA_DIGEST_LENGTH]; unsigned char *tmp = NULL; int numN = BN_num_bytes(N); BIGNUM *res = NULL; EVP_MD *sha1 = EVP_MD_fetch(libctx, "SHA1", propq); if (sha1 == NULL) return NULL; if (x != N && BN_ucmp(x, N) >= 0) goto err; if (y != N && BN_ucmp(y, N) >= 0) goto err; if ((tmp = OPENSSL_malloc(numN * 2)) == NULL) goto err; if (BN_bn2binpad(x, tmp, numN) < 0 || BN_bn2binpad(y, tmp + numN, numN) < 0 || !EVP_Digest(tmp, numN * 2, digest, NULL, sha1, NULL)) goto err; res = BN_bin2bn(digest, sizeof(digest), NULL); err: EVP_MD_free(sha1); OPENSSL_free(tmp); return res; } static BIGNUM *srp_Calc_k(const BIGNUM *N, const BIGNUM *g, OSSL_LIB_CTX *libctx, const char *propq) { /* k = SHA1(N | PAD(g)) -- tls-srp RFC 5054 */ return srp_Calc_xy(N, g, N, libctx, propq); } BIGNUM *SRP_Calc_u_ex(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N, OSSL_LIB_CTX *libctx, const char *propq) { /* u = SHA1(PAD(A) || PAD(B) ) -- tls-srp RFC 5054 */ return srp_Calc_xy(A, B, N, libctx, propq); } BIGNUM *SRP_Calc_u(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N) { /* u = SHA1(PAD(A) || PAD(B) ) -- tls-srp RFC 5054 */ return srp_Calc_xy(A, B, N, NULL, NULL); } BIGNUM *SRP_Calc_server_key(const BIGNUM *A, const BIGNUM *v, const BIGNUM *u, const BIGNUM *b, const BIGNUM *N) { BIGNUM *tmp = NULL, *S = NULL; BN_CTX *bn_ctx; if (u == NULL || A == NULL || v == NULL || b == NULL || N == NULL) return NULL; if ((bn_ctx = BN_CTX_new()) == NULL || (tmp = BN_new()) == NULL) goto err; /* S = (A*v**u) ** b */ if (!BN_mod_exp(tmp, v, u, N, bn_ctx)) goto err; if (!BN_mod_mul(tmp, A, tmp, N, bn_ctx)) goto err; S = BN_new(); if (S != NULL && !BN_mod_exp(S, tmp, b, N, bn_ctx)) { BN_free(S); S = NULL; } err: BN_CTX_free(bn_ctx); BN_clear_free(tmp); return S; } BIGNUM *SRP_Calc_B_ex(const BIGNUM *b, const BIGNUM *N, const BIGNUM *g, const BIGNUM *v, OSSL_LIB_CTX *libctx, const char *propq) { BIGNUM *kv = NULL, *gb = NULL; BIGNUM *B = NULL, *k = NULL; BN_CTX *bn_ctx; if (b == NULL || N == NULL || g == NULL || v == NULL || (bn_ctx = BN_CTX_new_ex(libctx)) == NULL) return NULL; if ((kv = BN_new()) == NULL || (gb = BN_new()) == NULL || (B = BN_new()) == NULL) goto err; /* B = g**b + k*v */ if (!BN_mod_exp(gb, g, b, N, bn_ctx) || (k = srp_Calc_k(N, g, libctx, propq)) == NULL || !BN_mod_mul(kv, v, k, N, bn_ctx) || !BN_mod_add(B, gb, kv, N, bn_ctx)) { BN_free(B); B = NULL; } err: BN_CTX_free(bn_ctx); BN_clear_free(kv); BN_clear_free(gb); BN_free(k); return B; } BIGNUM *SRP_Calc_B(const BIGNUM *b, const BIGNUM *N, const BIGNUM *g, const BIGNUM *v) { return SRP_Calc_B_ex(b, N, g, v, NULL, NULL); } BIGNUM *SRP_Calc_x_ex(const BIGNUM *s, const char *user, const char *pass, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char dig[SHA_DIGEST_LENGTH]; EVP_MD_CTX *ctxt; unsigned char *cs = NULL; BIGNUM *res = NULL; EVP_MD *sha1 = NULL; if ((s == NULL) || (user == NULL) || (pass == NULL)) return NULL; ctxt = EVP_MD_CTX_new(); if (ctxt == NULL) return NULL; if ((cs = OPENSSL_malloc(BN_num_bytes(s))) == NULL) goto err; sha1 = EVP_MD_fetch(libctx, "SHA1", propq); if (sha1 == NULL) goto err; if (!EVP_DigestInit_ex(ctxt, sha1, NULL) || !EVP_DigestUpdate(ctxt, user, strlen(user)) || !EVP_DigestUpdate(ctxt, ":", 1) || !EVP_DigestUpdate(ctxt, pass, strlen(pass)) || !EVP_DigestFinal_ex(ctxt, dig, NULL) || !EVP_DigestInit_ex(ctxt, sha1, NULL)) goto err; if (BN_bn2bin(s, cs) < 0) goto err; if (!EVP_DigestUpdate(ctxt, cs, BN_num_bytes(s))) goto err; if (!EVP_DigestUpdate(ctxt, dig, sizeof(dig)) || !EVP_DigestFinal_ex(ctxt, dig, NULL)) goto err; res = BN_bin2bn(dig, sizeof(dig), NULL); err: EVP_MD_free(sha1); OPENSSL_free(cs); EVP_MD_CTX_free(ctxt); return res; } BIGNUM *SRP_Calc_x(const BIGNUM *s, const char *user, const char *pass) { return SRP_Calc_x_ex(s, user, pass, NULL, NULL); } BIGNUM *SRP_Calc_A(const BIGNUM *a, const BIGNUM *N, const BIGNUM *g) { BN_CTX *bn_ctx; BIGNUM *A = NULL; if (a == NULL || N == NULL || g == NULL || (bn_ctx = BN_CTX_new()) == NULL) return NULL; if ((A = BN_new()) != NULL && !BN_mod_exp(A, g, a, N, bn_ctx)) { BN_free(A); A = NULL; } BN_CTX_free(bn_ctx); return A; } BIGNUM *SRP_Calc_client_key_ex(const BIGNUM *N, const BIGNUM *B, const BIGNUM *g, const BIGNUM *x, const BIGNUM *a, const BIGNUM *u, OSSL_LIB_CTX *libctx, const char *propq) { BIGNUM *tmp = NULL, *tmp2 = NULL, *tmp3 = NULL, *k = NULL, *K = NULL; BIGNUM *xtmp = NULL; BN_CTX *bn_ctx; if (u == NULL || B == NULL || N == NULL || g == NULL || x == NULL || a == NULL || (bn_ctx = BN_CTX_new_ex(libctx)) == NULL) return NULL; if ((tmp = BN_new()) == NULL || (tmp2 = BN_new()) == NULL || (tmp3 = BN_new()) == NULL || (xtmp = BN_new()) == NULL) goto err; BN_with_flags(xtmp, x, BN_FLG_CONSTTIME); BN_set_flags(tmp, BN_FLG_CONSTTIME); if (!BN_mod_exp(tmp, g, xtmp, N, bn_ctx)) goto err; if ((k = srp_Calc_k(N, g, libctx, propq)) == NULL) goto err; if (!BN_mod_mul(tmp2, tmp, k, N, bn_ctx)) goto err; if (!BN_mod_sub(tmp, B, tmp2, N, bn_ctx)) goto err; if (!BN_mul(tmp3, u, xtmp, bn_ctx)) goto err; if (!BN_add(tmp2, a, tmp3)) goto err; K = BN_new(); if (K != NULL && !BN_mod_exp(K, tmp, tmp2, N, bn_ctx)) { BN_free(K); K = NULL; } err: BN_CTX_free(bn_ctx); BN_free(xtmp); BN_clear_free(tmp); BN_clear_free(tmp2); BN_clear_free(tmp3); BN_free(k); return K; } BIGNUM *SRP_Calc_client_key(const BIGNUM *N, const BIGNUM *B, const BIGNUM *g, const BIGNUM *x, const BIGNUM *a, const BIGNUM *u) { return SRP_Calc_client_key_ex(N, B, g, x, a, u, NULL, NULL); } int SRP_Verify_B_mod_N(const BIGNUM *B, const BIGNUM *N) { BIGNUM *r; BN_CTX *bn_ctx; int ret = 0; if (B == NULL || N == NULL || (bn_ctx = BN_CTX_new()) == NULL) return 0; if ((r = BN_new()) == NULL) goto err; /* Checks if B % N == 0 */ if (!BN_nnmod(r, B, N, bn_ctx)) goto err; ret = !BN_is_zero(r); err: BN_CTX_free(bn_ctx); BN_free(r); return ret; } int SRP_Verify_A_mod_N(const BIGNUM *A, const BIGNUM *N) { /* Checks if A % N == 0 */ return SRP_Verify_B_mod_N(A, N); } static SRP_gN knowngN[] = { {"8192", &ossl_bn_generator_19, &ossl_bn_group_8192}, {"6144", &ossl_bn_generator_5, &ossl_bn_group_6144}, {"4096", &ossl_bn_generator_5, &ossl_bn_group_4096}, {"3072", &ossl_bn_generator_5, &ossl_bn_group_3072}, {"2048", &ossl_bn_generator_2, &ossl_bn_group_2048}, {"1536", &ossl_bn_generator_2, &ossl_bn_group_1536}, {"1024", &ossl_bn_generator_2, &ossl_bn_group_1024}, }; # define KNOWN_GN_NUMBER sizeof(knowngN) / sizeof(SRP_gN) /* * Check if G and N are known parameters. The values have been generated * from the IETF RFC 5054 */ char *SRP_check_known_gN_param(const BIGNUM *g, const BIGNUM *N) { size_t i; if ((g == NULL) || (N == NULL)) return NULL; for (i = 0; i < KNOWN_GN_NUMBER; i++) { if (BN_cmp(knowngN[i].g, g) == 0 && BN_cmp(knowngN[i].N, N) == 0) return knowngN[i].id; } return NULL; } SRP_gN *SRP_get_default_gN(const char *id) { size_t i; if (id == NULL) return knowngN; for (i = 0; i < KNOWN_GN_NUMBER; i++) { if (strcmp(knowngN[i].id, id) == 0) return knowngN + i; } return NULL; } #endif
9,230
26.555224
81
c
openssl
openssl-master/crypto/srp/srp_vfy.c
/* * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2004, EdelKey Project. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * Originally written by Christophe Renou and Peter Sylvester, * for the EdelKey project. */ /* All the SRP APIs in this file are deprecated */ #define OPENSSL_SUPPRESS_DEPRECATED #ifndef OPENSSL_NO_SRP # include "internal/cryptlib.h" # include "crypto/evp.h" # include <openssl/sha.h> # include <openssl/srp.h> # include <openssl/evp.h> # include <openssl/buffer.h> # include <openssl/rand.h> # include <openssl/txt_db.h> # include <openssl/err.h> # define SRP_RANDOM_SALT_LEN 20 # define MAX_LEN 2500 /* * Note that SRP uses its own variant of base 64 encoding. A different base64 * alphabet is used and no padding '=' characters are added. Instead we pad to * the front with 0 bytes and subsequently strip off leading encoded padding. * This variant is used for compatibility with other SRP implementations - * notably libsrp, but also others. It is also required for backwards * compatibility in order to load verifier files from other OpenSSL versions. */ /* * Convert a base64 string into raw byte array representation. * Returns the length of the decoded data, or -1 on error. */ static int t_fromb64(unsigned char *a, size_t alen, const char *src) { EVP_ENCODE_CTX *ctx; int outl = 0, outl2 = 0; size_t size, padsize; const unsigned char *pad = (const unsigned char *)"00"; while (*src == ' ' || *src == '\t' || *src == '\n') ++src; size = strlen(src); padsize = 4 - (size & 3); padsize &= 3; /* Four bytes in src become three bytes output. */ if (size > INT_MAX || ((size + padsize) / 4) * 3 > alen) return -1; ctx = EVP_ENCODE_CTX_new(); if (ctx == NULL) return -1; /* * This should never occur because 1 byte of data always requires 2 bytes of * encoding, i.e. * 0 bytes unencoded = 0 bytes encoded * 1 byte unencoded = 2 bytes encoded * 2 bytes unencoded = 3 bytes encoded * 3 bytes unencoded = 4 bytes encoded * 4 bytes unencoded = 6 bytes encoded * etc */ if (padsize == 3) { outl = -1; goto err; } /* Valid padsize values are now 0, 1 or 2 */ EVP_DecodeInit(ctx); evp_encode_ctx_set_flags(ctx, EVP_ENCODE_CTX_USE_SRP_ALPHABET); /* Add any encoded padding that is required */ if (padsize != 0 && EVP_DecodeUpdate(ctx, a, &outl, pad, padsize) < 0) { outl = -1; goto err; } if (EVP_DecodeUpdate(ctx, a, &outl2, (const unsigned char *)src, size) < 0) { outl = -1; goto err; } outl += outl2; EVP_DecodeFinal(ctx, a + outl, &outl2); outl += outl2; /* Strip off the leading padding */ if (padsize != 0) { if ((int)padsize >= outl) { outl = -1; goto err; } /* * If we added 1 byte of padding prior to encoding then we have 2 bytes * of "real" data which gets spread across 4 encoded bytes like this: * (6 bits pad)(2 bits pad | 4 bits data)(6 bits data)(6 bits data) * So 1 byte of pre-encoding padding results in 1 full byte of encoded * padding. * If we added 2 bytes of padding prior to encoding this gets encoded * as: * (6 bits pad)(6 bits pad)(4 bits pad | 2 bits data)(6 bits data) * So 2 bytes of pre-encoding padding results in 2 full bytes of encoded * padding, i.e. we have to strip the same number of bytes of padding * from the encoded data as we added to the pre-encoded data. */ memmove(a, a + padsize, outl - padsize); outl -= padsize; } err: EVP_ENCODE_CTX_free(ctx); return outl; } /* * Convert a raw byte string into a null-terminated base64 ASCII string. * Returns 1 on success or 0 on error. */ static int t_tob64(char *dst, const unsigned char *src, int size) { EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new(); int outl = 0, outl2 = 0; unsigned char pad[2] = {0, 0}; size_t leadz = 0; if (ctx == NULL) return 0; EVP_EncodeInit(ctx); evp_encode_ctx_set_flags(ctx, EVP_ENCODE_CTX_NO_NEWLINES | EVP_ENCODE_CTX_USE_SRP_ALPHABET); /* * We pad at the front with zero bytes until the length is a multiple of 3 * so that EVP_EncodeUpdate/EVP_EncodeFinal does not add any of its own "=" * padding */ leadz = 3 - (size % 3); if (leadz != 3 && !EVP_EncodeUpdate(ctx, (unsigned char *)dst, &outl, pad, leadz)) { EVP_ENCODE_CTX_free(ctx); return 0; } if (!EVP_EncodeUpdate(ctx, (unsigned char *)dst + outl, &outl2, src, size)) { EVP_ENCODE_CTX_free(ctx); return 0; } outl += outl2; EVP_EncodeFinal(ctx, (unsigned char *)dst + outl, &outl2); outl += outl2; /* Strip the encoded padding at the front */ if (leadz != 3) { memmove(dst, dst + leadz, outl - leadz); dst[outl - leadz] = '\0'; } EVP_ENCODE_CTX_free(ctx); return 1; } void SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); } SRP_user_pwd *SRP_user_pwd_new(void) { SRP_user_pwd *ret; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) return NULL; ret->N = NULL; ret->g = NULL; ret->s = NULL; ret->v = NULL; ret->id = NULL; ret->info = NULL; return ret; } void SRP_user_pwd_set_gN(SRP_user_pwd *vinfo, const BIGNUM *g, const BIGNUM *N) { vinfo->N = N; vinfo->g = g; } int SRP_user_pwd_set1_ids(SRP_user_pwd *vinfo, const char *id, const char *info) { OPENSSL_free(vinfo->id); OPENSSL_free(vinfo->info); if (id != NULL && NULL == (vinfo->id = OPENSSL_strdup(id))) return 0; return (info == NULL || NULL != (vinfo->info = OPENSSL_strdup(info))); } static int SRP_user_pwd_set_sv(SRP_user_pwd *vinfo, const char *s, const char *v) { unsigned char tmp[MAX_LEN]; int len; vinfo->v = NULL; vinfo->s = NULL; len = t_fromb64(tmp, sizeof(tmp), v); if (len < 0) return 0; if (NULL == (vinfo->v = BN_bin2bn(tmp, len, NULL))) return 0; len = t_fromb64(tmp, sizeof(tmp), s); if (len < 0) goto err; vinfo->s = BN_bin2bn(tmp, len, NULL); if (vinfo->s == NULL) goto err; return 1; err: BN_free(vinfo->v); vinfo->v = NULL; return 0; } int SRP_user_pwd_set0_sv(SRP_user_pwd *vinfo, BIGNUM *s, BIGNUM *v) { BN_free(vinfo->s); BN_clear_free(vinfo->v); vinfo->v = v; vinfo->s = s; return (vinfo->s != NULL && vinfo->v != NULL); } static SRP_user_pwd *srp_user_pwd_dup(SRP_user_pwd *src) { SRP_user_pwd *ret; if (src == NULL) return NULL; if ((ret = SRP_user_pwd_new()) == NULL) return NULL; SRP_user_pwd_set_gN(ret, src->g, src->N); if (!SRP_user_pwd_set1_ids(ret, src->id, src->info) || !SRP_user_pwd_set0_sv(ret, BN_dup(src->s), BN_dup(src->v))) { SRP_user_pwd_free(ret); return NULL; } return ret; } SRP_VBASE *SRP_VBASE_new(char *seed_key) { SRP_VBASE *vb = OPENSSL_malloc(sizeof(*vb)); if (vb == NULL) return NULL; if ((vb->users_pwd = sk_SRP_user_pwd_new_null()) == NULL || (vb->gN_cache = sk_SRP_gN_cache_new_null()) == NULL) { OPENSSL_free(vb); return NULL; } vb->default_g = NULL; vb->default_N = NULL; vb->seed_key = NULL; if ((seed_key != NULL) && (vb->seed_key = OPENSSL_strdup(seed_key)) == NULL) { sk_SRP_user_pwd_free(vb->users_pwd); sk_SRP_gN_cache_free(vb->gN_cache); OPENSSL_free(vb); return NULL; } return vb; } void SRP_VBASE_free(SRP_VBASE *vb) { if (!vb) return; sk_SRP_user_pwd_pop_free(vb->users_pwd, SRP_user_pwd_free); sk_SRP_gN_cache_free(vb->gN_cache); OPENSSL_free(vb->seed_key); OPENSSL_free(vb); } static SRP_gN_cache *SRP_gN_new_init(const char *ch) { unsigned char tmp[MAX_LEN]; int len; SRP_gN_cache *newgN = OPENSSL_malloc(sizeof(*newgN)); if (newgN == NULL) return NULL; len = t_fromb64(tmp, sizeof(tmp), ch); if (len < 0) goto err; if ((newgN->b64_bn = OPENSSL_strdup(ch)) == NULL) goto err; if ((newgN->bn = BN_bin2bn(tmp, len, NULL))) return newgN; OPENSSL_free(newgN->b64_bn); err: OPENSSL_free(newgN); return NULL; } static void SRP_gN_free(SRP_gN_cache *gN_cache) { if (gN_cache == NULL) return; OPENSSL_free(gN_cache->b64_bn); BN_free(gN_cache->bn); OPENSSL_free(gN_cache); } static SRP_gN *SRP_get_gN_by_id(const char *id, STACK_OF(SRP_gN) *gN_tab) { int i; SRP_gN *gN; if (gN_tab != NULL) { for (i = 0; i < sk_SRP_gN_num(gN_tab); i++) { gN = sk_SRP_gN_value(gN_tab, i); if (gN && (id == NULL || strcmp(gN->id, id) == 0)) return gN; } } return SRP_get_default_gN(id); } static BIGNUM *SRP_gN_place_bn(STACK_OF(SRP_gN_cache) *gN_cache, char *ch) { int i; if (gN_cache == NULL) return NULL; /* search if we have already one... */ for (i = 0; i < sk_SRP_gN_cache_num(gN_cache); i++) { SRP_gN_cache *cache = sk_SRP_gN_cache_value(gN_cache, i); if (strcmp(cache->b64_bn, ch) == 0) return cache->bn; } { /* it is the first time that we find it */ SRP_gN_cache *newgN = SRP_gN_new_init(ch); if (newgN) { if (sk_SRP_gN_cache_insert(gN_cache, newgN, 0) > 0) return newgN->bn; SRP_gN_free(newgN); } } return NULL; } /* * This function parses the verifier file generated by the srp app. * The format for each entry is: * V base64(verifier) base64(salt) username gNid userinfo(optional) * or * I base64(N) base64(g) * Note that base64 is the SRP variant of base64 encoding described * in t_fromb64(). */ int SRP_VBASE_init(SRP_VBASE *vb, char *verifier_file) { int error_code = SRP_ERR_MEMORY; STACK_OF(SRP_gN) *SRP_gN_tab = sk_SRP_gN_new_null(); char *last_index = NULL; int i; char **pp; SRP_gN *gN = NULL; SRP_user_pwd *user_pwd = NULL; TXT_DB *tmpdb = NULL; BIO *in = BIO_new(BIO_s_file()); if (SRP_gN_tab == NULL) goto err; error_code = SRP_ERR_OPEN_FILE; if (in == NULL || BIO_read_filename(in, verifier_file) <= 0) goto err; error_code = SRP_ERR_VBASE_INCOMPLETE_FILE; if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL) goto err; error_code = SRP_ERR_MEMORY; if (vb->seed_key) { last_index = SRP_get_default_gN(NULL)->id; } for (i = 0; i < sk_OPENSSL_PSTRING_num(tmpdb->data); i++) { pp = sk_OPENSSL_PSTRING_value(tmpdb->data, i); if (pp[DB_srptype][0] == DB_SRP_INDEX) { /* * we add this couple in the internal Stack */ if ((gN = OPENSSL_malloc(sizeof(*gN))) == NULL) goto err; if ((gN->id = OPENSSL_strdup(pp[DB_srpid])) == NULL || (gN->N = SRP_gN_place_bn(vb->gN_cache, pp[DB_srpverifier])) == NULL || (gN->g = SRP_gN_place_bn(vb->gN_cache, pp[DB_srpsalt])) == NULL || sk_SRP_gN_insert(SRP_gN_tab, gN, 0) == 0) goto err; gN = NULL; if (vb->seed_key != NULL) { last_index = pp[DB_srpid]; } } else if (pp[DB_srptype][0] == DB_SRP_VALID) { /* it is a user .... */ const SRP_gN *lgN; if ((lgN = SRP_get_gN_by_id(pp[DB_srpgN], SRP_gN_tab)) != NULL) { error_code = SRP_ERR_MEMORY; if ((user_pwd = SRP_user_pwd_new()) == NULL) goto err; SRP_user_pwd_set_gN(user_pwd, lgN->g, lgN->N); if (!SRP_user_pwd_set1_ids (user_pwd, pp[DB_srpid], pp[DB_srpinfo])) goto err; error_code = SRP_ERR_VBASE_BN_LIB; if (!SRP_user_pwd_set_sv (user_pwd, pp[DB_srpsalt], pp[DB_srpverifier])) goto err; if (sk_SRP_user_pwd_insert(vb->users_pwd, user_pwd, 0) == 0) goto err; user_pwd = NULL; /* abandon responsibility */ } } } if (last_index != NULL) { /* this means that we want to simulate a default user */ if (((gN = SRP_get_gN_by_id(last_index, SRP_gN_tab)) == NULL)) { error_code = SRP_ERR_VBASE_BN_LIB; goto err; } vb->default_g = gN->g; vb->default_N = gN->N; gN = NULL; } error_code = SRP_NO_ERROR; err: /* * there may be still some leaks to fix, if this fails, the application * terminates most likely */ if (gN != NULL) { OPENSSL_free(gN->id); OPENSSL_free(gN); } SRP_user_pwd_free(user_pwd); TXT_DB_free(tmpdb); BIO_free_all(in); sk_SRP_gN_free(SRP_gN_tab); return error_code; } static SRP_user_pwd *find_user(SRP_VBASE *vb, char *username) { int i; SRP_user_pwd *user; if (vb == NULL) return NULL; for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) { user = sk_SRP_user_pwd_value(vb->users_pwd, i); if (strcmp(user->id, username) == 0) return user; } return NULL; } int SRP_VBASE_add0_user(SRP_VBASE *vb, SRP_user_pwd *user_pwd) { if (sk_SRP_user_pwd_push(vb->users_pwd, user_pwd) <= 0) return 0; return 1; } # ifndef OPENSSL_NO_DEPRECATED_1_1_0 /* * DEPRECATED: use SRP_VBASE_get1_by_user instead. * This method ignores the configured seed and fails for an unknown user. * Ownership of the returned pointer is not released to the caller. * In other words, caller must not free the result. */ SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username) { return find_user(vb, username); } # endif /* * Ownership of the returned pointer is released to the caller. * In other words, caller must free the result once done. */ SRP_user_pwd *SRP_VBASE_get1_by_user(SRP_VBASE *vb, char *username) { SRP_user_pwd *user; unsigned char digv[SHA_DIGEST_LENGTH]; unsigned char digs[SHA_DIGEST_LENGTH]; EVP_MD_CTX *ctxt = NULL; EVP_MD *md = NULL; if (vb == NULL) return NULL; if ((user = find_user(vb, username)) != NULL) return srp_user_pwd_dup(user); if ((vb->seed_key == NULL) || (vb->default_g == NULL) || (vb->default_N == NULL)) return NULL; /* if the user is unknown we set parameters as well if we have a seed_key */ if ((user = SRP_user_pwd_new()) == NULL) return NULL; SRP_user_pwd_set_gN(user, vb->default_g, vb->default_N); if (!SRP_user_pwd_set1_ids(user, username, NULL)) goto err; if (RAND_priv_bytes(digv, SHA_DIGEST_LENGTH) <= 0) goto err; md = EVP_MD_fetch(NULL, SN_sha1, NULL); if (md == NULL) goto err; ctxt = EVP_MD_CTX_new(); if (ctxt == NULL || !EVP_DigestInit_ex(ctxt, md, NULL) || !EVP_DigestUpdate(ctxt, vb->seed_key, strlen(vb->seed_key)) || !EVP_DigestUpdate(ctxt, username, strlen(username)) || !EVP_DigestFinal_ex(ctxt, digs, NULL)) goto err; EVP_MD_CTX_free(ctxt); ctxt = NULL; EVP_MD_free(md); md = NULL; if (SRP_user_pwd_set0_sv(user, BN_bin2bn(digs, SHA_DIGEST_LENGTH, NULL), BN_bin2bn(digv, SHA_DIGEST_LENGTH, NULL))) return user; err: EVP_MD_free(md); EVP_MD_CTX_free(ctxt); SRP_user_pwd_free(user); return NULL; } /* * create a verifier (*salt,*verifier,g and N are in base64) */ char *SRP_create_verifier_ex(const char *user, const char *pass, char **salt, char **verifier, const char *N, const char *g, OSSL_LIB_CTX *libctx, const char *propq) { int len; char *result = NULL, *vf = NULL; const BIGNUM *N_bn = NULL, *g_bn = NULL; BIGNUM *N_bn_alloc = NULL, *g_bn_alloc = NULL, *s = NULL, *v = NULL; unsigned char tmp[MAX_LEN]; unsigned char tmp2[MAX_LEN]; char *defgNid = NULL; int vfsize = 0; if ((user == NULL) || (pass == NULL) || (salt == NULL) || (verifier == NULL)) goto err; if (N) { if ((len = t_fromb64(tmp, sizeof(tmp), N)) <= 0) goto err; N_bn_alloc = BN_bin2bn(tmp, len, NULL); if (N_bn_alloc == NULL) goto err; N_bn = N_bn_alloc; if ((len = t_fromb64(tmp, sizeof(tmp), g)) <= 0) goto err; g_bn_alloc = BN_bin2bn(tmp, len, NULL); if (g_bn_alloc == NULL) goto err; g_bn = g_bn_alloc; defgNid = "*"; } else { SRP_gN *gN = SRP_get_default_gN(g); if (gN == NULL) goto err; N_bn = gN->N; g_bn = gN->g; defgNid = gN->id; } if (*salt == NULL) { if (RAND_bytes_ex(libctx, tmp2, SRP_RANDOM_SALT_LEN, 0) <= 0) goto err; s = BN_bin2bn(tmp2, SRP_RANDOM_SALT_LEN, NULL); } else { if ((len = t_fromb64(tmp2, sizeof(tmp2), *salt)) <= 0) goto err; s = BN_bin2bn(tmp2, len, NULL); } if (s == NULL) goto err; if (!SRP_create_verifier_BN_ex(user, pass, &s, &v, N_bn, g_bn, libctx, propq)) goto err; if (BN_bn2bin(v, tmp) < 0) goto err; vfsize = BN_num_bytes(v) * 2; if (((vf = OPENSSL_malloc(vfsize)) == NULL)) goto err; if (!t_tob64(vf, tmp, BN_num_bytes(v))) goto err; if (*salt == NULL) { char *tmp_salt; if ((tmp_salt = OPENSSL_malloc(SRP_RANDOM_SALT_LEN * 2)) == NULL) { goto err; } if (!t_tob64(tmp_salt, tmp2, SRP_RANDOM_SALT_LEN)) { OPENSSL_free(tmp_salt); goto err; } *salt = tmp_salt; } *verifier = vf; vf = NULL; result = defgNid; err: BN_free(N_bn_alloc); BN_free(g_bn_alloc); OPENSSL_clear_free(vf, vfsize); BN_clear_free(s); BN_clear_free(v); return result; } char *SRP_create_verifier(const char *user, const char *pass, char **salt, char **verifier, const char *N, const char *g) { return SRP_create_verifier_ex(user, pass, salt, verifier, N, g, NULL, NULL); } /* * create a verifier (*salt,*verifier,g and N are BIGNUMs). If *salt != NULL * then the provided salt will be used. On successful exit *verifier will point * to a newly allocated BIGNUM containing the verifier and (if a salt was not * provided) *salt will be populated with a newly allocated BIGNUM containing a * random salt. * The caller is responsible for freeing the allocated *salt and *verifier * BIGNUMS. */ int SRP_create_verifier_BN_ex(const char *user, const char *pass, BIGNUM **salt, BIGNUM **verifier, const BIGNUM *N, const BIGNUM *g, OSSL_LIB_CTX *libctx, const char *propq) { int result = 0; BIGNUM *x = NULL; BN_CTX *bn_ctx = BN_CTX_new_ex(libctx); unsigned char tmp2[MAX_LEN]; BIGNUM *salttmp = NULL, *verif; if ((user == NULL) || (pass == NULL) || (salt == NULL) || (verifier == NULL) || (N == NULL) || (g == NULL) || (bn_ctx == NULL)) goto err; if (*salt == NULL) { if (RAND_bytes_ex(libctx, tmp2, SRP_RANDOM_SALT_LEN, 0) <= 0) goto err; salttmp = BN_bin2bn(tmp2, SRP_RANDOM_SALT_LEN, NULL); if (salttmp == NULL) goto err; } else { salttmp = *salt; } x = SRP_Calc_x_ex(salttmp, user, pass, libctx, propq); if (x == NULL) goto err; verif = BN_new(); if (verif == NULL) goto err; if (!BN_mod_exp(verif, g, x, N, bn_ctx)) { BN_clear_free(verif); goto err; } result = 1; *salt = salttmp; *verifier = verif; err: if (salt != NULL && *salt != salttmp) BN_clear_free(salttmp); BN_clear_free(x); BN_CTX_free(bn_ctx); return result; } int SRP_create_verifier_BN(const char *user, const char *pass, BIGNUM **salt, BIGNUM **verifier, const BIGNUM *N, const BIGNUM *g) { return SRP_create_verifier_BN_ex(user, pass, salt, verifier, N, g, NULL, NULL); } #endif
21,405
26.620645
82
c
openssl
openssl-master/crypto/stack/stack.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include "internal/numbers.h" #include "internal/safe_math.h" #include <openssl/stack.h> #include <errno.h> #include <openssl/e_os2.h> /* For ossl_inline */ OSSL_SAFE_MATH_SIGNED(int, int) /* * The initial number of nodes in the array. */ static const int min_nodes = 4; static const int max_nodes = SIZE_MAX / sizeof(void *) < INT_MAX ? (int)(SIZE_MAX / sizeof(void *)) : INT_MAX; struct stack_st { int num; const void **data; int sorted; int num_alloc; OPENSSL_sk_compfunc comp; }; OPENSSL_sk_compfunc OPENSSL_sk_set_cmp_func(OPENSSL_STACK *sk, OPENSSL_sk_compfunc c) { OPENSSL_sk_compfunc old = sk->comp; if (sk->comp != c) sk->sorted = 0; sk->comp = c; return old; } OPENSSL_STACK *OPENSSL_sk_dup(const OPENSSL_STACK *sk) { OPENSSL_STACK *ret; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) goto err; if (sk == NULL) { ret->num = 0; ret->sorted = 0; ret->comp = NULL; } else { /* direct structure assignment */ *ret = *sk; } if (sk == NULL || sk->num == 0) { /* postpone |ret->data| allocation */ ret->data = NULL; ret->num_alloc = 0; return ret; } /* duplicate |sk->data| content */ ret->data = OPENSSL_malloc(sizeof(*ret->data) * sk->num_alloc); if (ret->data == NULL) goto err; memcpy(ret->data, sk->data, sizeof(void *) * sk->num); return ret; err: OPENSSL_sk_free(ret); return NULL; } OPENSSL_STACK *OPENSSL_sk_deep_copy(const OPENSSL_STACK *sk, OPENSSL_sk_copyfunc copy_func, OPENSSL_sk_freefunc free_func) { OPENSSL_STACK *ret; int i; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) goto err; if (sk == NULL) { ret->num = 0; ret->sorted = 0; ret->comp = NULL; } else { /* direct structure assignment */ *ret = *sk; } if (sk == NULL || sk->num == 0) { /* postpone |ret| data allocation */ ret->data = NULL; ret->num_alloc = 0; return ret; } ret->num_alloc = sk->num > min_nodes ? sk->num : min_nodes; ret->data = OPENSSL_zalloc(sizeof(*ret->data) * ret->num_alloc); if (ret->data == NULL) goto err; for (i = 0; i < ret->num; ++i) { if (sk->data[i] == NULL) continue; if ((ret->data[i] = copy_func(sk->data[i])) == NULL) { while (--i >= 0) if (ret->data[i] != NULL) free_func((void *)ret->data[i]); goto err; } } return ret; err: OPENSSL_sk_free(ret); return NULL; } OPENSSL_STACK *OPENSSL_sk_new_null(void) { return OPENSSL_sk_new_reserve(NULL, 0); } OPENSSL_STACK *OPENSSL_sk_new(OPENSSL_sk_compfunc c) { return OPENSSL_sk_new_reserve(c, 0); } /* * Calculate the array growth based on the target size. * * The growth factor is a rational number and is defined by a numerator * and a denominator. According to Andrew Koenig in his paper "Why Are * Vectors Efficient?" from JOOP 11(5) 1998, this factor should be less * than the golden ratio (1.618...). * * Considering only the Fibonacci ratios less than the golden ratio, the * number of steps from the minimum allocation to integer overflow is: * factor decimal growths * 3/2 1.5 51 * 8/5 1.6 45 * 21/13 1.615... 44 * * All larger factors have the same number of growths. * * 3/2 and 8/5 have nice power of two shifts, so seem like a good choice. */ static ossl_inline int compute_growth(int target, int current) { int err = 0; while (current < target) { if (current >= max_nodes) return 0; current = safe_muldiv_int(current, 8, 5, &err); if (err != 0) return 0; if (current >= max_nodes) current = max_nodes; } return current; } /* internal STACK storage allocation */ static int sk_reserve(OPENSSL_STACK *st, int n, int exact) { const void **tmpdata; int num_alloc; /* Check to see the reservation isn't exceeding the hard limit */ if (n > max_nodes - st->num) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_MANY_RECORDS); return 0; } /* Figure out the new size */ num_alloc = st->num + n; if (num_alloc < min_nodes) num_alloc = min_nodes; /* If |st->data| allocation was postponed */ if (st->data == NULL) { /* * At this point, |st->num_alloc| and |st->num| are 0; * so |num_alloc| value is |n| or |min_nodes| if greater than |n|. */ if ((st->data = OPENSSL_zalloc(sizeof(void *) * num_alloc)) == NULL) return 0; st->num_alloc = num_alloc; return 1; } if (!exact) { if (num_alloc <= st->num_alloc) return 1; num_alloc = compute_growth(num_alloc, st->num_alloc); if (num_alloc == 0) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_MANY_RECORDS); return 0; } } else if (num_alloc == st->num_alloc) { return 1; } tmpdata = OPENSSL_realloc((void *)st->data, sizeof(void *) * num_alloc); if (tmpdata == NULL) return 0; st->data = tmpdata; st->num_alloc = num_alloc; return 1; } OPENSSL_STACK *OPENSSL_sk_new_reserve(OPENSSL_sk_compfunc c, int n) { OPENSSL_STACK *st = OPENSSL_zalloc(sizeof(OPENSSL_STACK)); if (st == NULL) return NULL; st->comp = c; if (n <= 0) return st; if (!sk_reserve(st, n, 1)) { OPENSSL_sk_free(st); return NULL; } return st; } int OPENSSL_sk_reserve(OPENSSL_STACK *st, int n) { if (st == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (n < 0) return 1; return sk_reserve(st, n, 1); } int OPENSSL_sk_insert(OPENSSL_STACK *st, const void *data, int loc) { if (st == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (st->num == max_nodes) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_MANY_RECORDS); return 0; } if (!sk_reserve(st, 1, 0)) return 0; if ((loc >= st->num) || (loc < 0)) { st->data[st->num] = data; } else { memmove(&st->data[loc + 1], &st->data[loc], sizeof(st->data[0]) * (st->num - loc)); st->data[loc] = data; } st->num++; st->sorted = 0; return st->num; } static ossl_inline void *internal_delete(OPENSSL_STACK *st, int loc) { const void *ret = st->data[loc]; if (loc != st->num - 1) memmove(&st->data[loc], &st->data[loc + 1], sizeof(st->data[0]) * (st->num - loc - 1)); st->num--; return (void *)ret; } void *OPENSSL_sk_delete_ptr(OPENSSL_STACK *st, const void *p) { int i; if (st == NULL) return NULL; for (i = 0; i < st->num; i++) if (st->data[i] == p) return internal_delete(st, i); return NULL; } void *OPENSSL_sk_delete(OPENSSL_STACK *st, int loc) { if (st == NULL || loc < 0 || loc >= st->num) return NULL; return internal_delete(st, loc); } static int internal_find(OPENSSL_STACK *st, const void *data, int ret_val_options, int *pnum_matched) { const void *r; int i, count = 0; int *pnum = pnum_matched; if (st == NULL || st->num == 0) return -1; if (pnum == NULL) pnum = &count; if (st->comp == NULL) { for (i = 0; i < st->num; i++) if (st->data[i] == data) { *pnum = 1; return i; } *pnum = 0; return -1; } if (data == NULL) return -1; if (!st->sorted) { int res = -1; for (i = 0; i < st->num; i++) if (st->comp(&data, st->data + i) == 0) { if (res == -1) res = i; ++*pnum; /* Check if only one result is wanted and exit if so */ if (pnum_matched == NULL) return i; } if (res == -1) *pnum = 0; return res; } if (pnum_matched != NULL) ret_val_options |= OSSL_BSEARCH_FIRST_VALUE_ON_MATCH; r = ossl_bsearch(&data, st->data, st->num, sizeof(void *), st->comp, ret_val_options); if (pnum_matched != NULL) { *pnum = 0; if (r != NULL) { const void **p = (const void **)r; while (p < st->data + st->num) { if (st->comp(&data, p) != 0) break; ++*pnum; ++p; } } } return r == NULL ? -1 : (int)((const void **)r - st->data); } int OPENSSL_sk_find(OPENSSL_STACK *st, const void *data) { return internal_find(st, data, OSSL_BSEARCH_FIRST_VALUE_ON_MATCH, NULL); } int OPENSSL_sk_find_ex(OPENSSL_STACK *st, const void *data) { return internal_find(st, data, OSSL_BSEARCH_VALUE_ON_NOMATCH, NULL); } int OPENSSL_sk_find_all(OPENSSL_STACK *st, const void *data, int *pnum) { return internal_find(st, data, OSSL_BSEARCH_FIRST_VALUE_ON_MATCH, pnum); } int OPENSSL_sk_push(OPENSSL_STACK *st, const void *data) { if (st == NULL) return -1; return OPENSSL_sk_insert(st, data, st->num); } int OPENSSL_sk_unshift(OPENSSL_STACK *st, const void *data) { return OPENSSL_sk_insert(st, data, 0); } void *OPENSSL_sk_shift(OPENSSL_STACK *st) { if (st == NULL || st->num == 0) return NULL; return internal_delete(st, 0); } void *OPENSSL_sk_pop(OPENSSL_STACK *st) { if (st == NULL || st->num == 0) return NULL; return internal_delete(st, st->num - 1); } void OPENSSL_sk_zero(OPENSSL_STACK *st) { if (st == NULL || st->num == 0) return; memset(st->data, 0, sizeof(*st->data) * st->num); st->num = 0; } void OPENSSL_sk_pop_free(OPENSSL_STACK *st, OPENSSL_sk_freefunc func) { int i; if (st == NULL) return; for (i = 0; i < st->num; i++) if (st->data[i] != NULL) func((char *)st->data[i]); OPENSSL_sk_free(st); } void OPENSSL_sk_free(OPENSSL_STACK *st) { if (st == NULL) return; OPENSSL_free(st->data); OPENSSL_free(st); } int OPENSSL_sk_num(const OPENSSL_STACK *st) { return st == NULL ? -1 : st->num; } void *OPENSSL_sk_value(const OPENSSL_STACK *st, int i) { if (st == NULL || i < 0 || i >= st->num) return NULL; return (void *)st->data[i]; } void *OPENSSL_sk_set(OPENSSL_STACK *st, int i, const void *data) { if (st == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (i < 0 || i >= st->num) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT, "i=%d", i); return NULL; } st->data[i] = data; st->sorted = 0; return (void *)st->data[i]; } void OPENSSL_sk_sort(OPENSSL_STACK *st) { if (st != NULL && !st->sorted && st->comp != NULL) { if (st->num > 1) qsort(st->data, st->num, sizeof(void *), st->comp); st->sorted = 1; /* empty or single-element stack is considered sorted */ } } int OPENSSL_sk_is_sorted(const OPENSSL_STACK *st) { return st == NULL ? 1 : st->sorted; }
11,925
23.239837
80
c
openssl
openssl-master/crypto/store/store_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/storeerr.h> #include "crypto/storeerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA OSSL_STORE_str_reasons[] = { {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE), "ambiguous content type"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_BAD_PASSWORD_READ), "bad password read"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC), "error verifying pkcs12 mac"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST), "fingerprint size does not match digest"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_INVALID_SCHEME), "invalid scheme"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_IS_NOT_A), "is not a"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_LOADER_INCOMPLETE), "loader incomplete"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_LOADING_STARTED), "loading started"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_CERTIFICATE), "not a certificate"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_CRL), "not a crl"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_NAME), "not a name"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_PRIVATE_KEY), "not a private key"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_PUBLIC_KEY), "not a public key"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_PARAMETERS), "not parameters"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NO_LOADERS_FOUND), "no loaders found"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR), "passphrase callback error"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE), "path must be absolute"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES), "search only supported for directories"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED), "ui process interrupted or cancelled"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNREGISTERED_SCHEME), "unregistered scheme"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE), "unsupported content type"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNSUPPORTED_OPERATION), "unsupported operation"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE), "unsupported search type"}, {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED), "uri authority unsupported"}, {0, NULL} }; #endif int ossl_err_load_OSSL_STORE_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(OSSL_STORE_str_reasons[0].error) == NULL) ERR_load_strings_const(OSSL_STORE_str_reasons); #endif return 1; }
3,241
41.657895
90
c
openssl
openssl-master/crypto/store/store_local.h
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core_dispatch.h> #include "internal/thread_once.h" #include "internal/refcount.h" #include <openssl/dsa.h> #include <openssl/engine.h> #include <openssl/evp.h> #include <openssl/lhash.h> #include <openssl/x509.h> #include <openssl/store.h> #include "internal/passphrase.h" /*- * OSSL_STORE_INFO stuff * --------------------- */ struct ossl_store_info_st { int type; union { void *data; /* used internally as generic pointer */ struct { char *name; char *desc; } name; /* when type == OSSL_STORE_INFO_NAME */ EVP_PKEY *params; /* when type == OSSL_STORE_INFO_PARAMS */ EVP_PKEY *pubkey; /* when type == OSSL_STORE_INFO_PUBKEY */ EVP_PKEY *pkey; /* when type == OSSL_STORE_INFO_PKEY */ X509 *x509; /* when type == OSSL_STORE_INFO_CERT */ X509_CRL *crl; /* when type == OSSL_STORE_INFO_CRL */ } _; }; DEFINE_STACK_OF(OSSL_STORE_INFO) /*- * OSSL_STORE_SEARCH stuff * ----------------------- */ struct ossl_store_search_st { int search_type; /* * Used by OSSL_STORE_SEARCH_BY_NAME and * OSSL_STORE_SEARCH_BY_ISSUER_SERIAL */ X509_NAME *name; /* Used by OSSL_STORE_SEARCH_BY_ISSUER_SERIAL */ const ASN1_INTEGER *serial; /* Used by OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT */ const EVP_MD *digest; /* * Used by OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT and * OSSL_STORE_SEARCH_BY_ALIAS */ const unsigned char *string; size_t stringlength; }; /*- * OSSL_STORE_LOADER stuff * ----------------------- */ int ossl_store_register_loader_int(OSSL_STORE_LOADER *loader); OSSL_STORE_LOADER *ossl_store_unregister_loader_int(const char *scheme); /* loader stuff */ struct ossl_store_loader_st { #ifndef OPENSSL_NO_DEPRECATED_3_0 /* Legacy stuff */ const char *scheme; ENGINE *engine; OSSL_STORE_open_fn open; OSSL_STORE_attach_fn attach; OSSL_STORE_ctrl_fn ctrl; OSSL_STORE_expect_fn expect; OSSL_STORE_find_fn find; OSSL_STORE_load_fn load; OSSL_STORE_eof_fn eof; OSSL_STORE_error_fn error; OSSL_STORE_close_fn closefn; OSSL_STORE_open_ex_fn open_ex; #endif /* Provider stuff */ OSSL_PROVIDER *prov; int scheme_id; const char *propdef; const char *description; CRYPTO_REF_COUNT refcnt; OSSL_FUNC_store_open_fn *p_open; OSSL_FUNC_store_attach_fn *p_attach; OSSL_FUNC_store_settable_ctx_params_fn *p_settable_ctx_params; OSSL_FUNC_store_set_ctx_params_fn *p_set_ctx_params; OSSL_FUNC_store_load_fn *p_load; OSSL_FUNC_store_eof_fn *p_eof; OSSL_FUNC_store_close_fn *p_close; OSSL_FUNC_store_export_object_fn *p_export_object; }; DEFINE_LHASH_OF_EX(OSSL_STORE_LOADER); const OSSL_STORE_LOADER *ossl_store_get0_loader_int(const char *scheme); void ossl_store_destroy_loaders_int(void); #ifdef OPENSSL_NO_DEPRECATED_3_0 /* struct ossl_store_loader_ctx_st is defined differently by each loader */ typedef struct ossl_store_loader_ctx_st OSSL_STORE_LOADER_CTX; #endif /*- * OSSL_STORE_CTX stuff * --------------------- */ struct ossl_store_ctx_st { const OSSL_STORE_LOADER *loader; /* legacy */ OSSL_STORE_LOADER *fetched_loader; OSSL_STORE_LOADER_CTX *loader_ctx; OSSL_STORE_post_process_info_fn post_process; void *post_process_data; int expected_type; char *properties; /* 0 before the first STORE_load(), 1 otherwise */ int loading; /* 1 on load error, only valid for fetched loaders */ int error_flag; /* * Cache of stuff, to be able to return the contents of a PKCS#12 * blob, one object at a time. */ STACK_OF(OSSL_STORE_INFO) *cached_info; struct ossl_passphrase_data_st pwdata; }; /*- * 'file' scheme stuff * ------------------- */ OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp); int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx); /*- * Provider stuff * ------------------- */ OSSL_STORE_LOADER *ossl_store_loader_fetch(OSSL_LIB_CTX *libctx, const char *scheme, const char *properties); /* Standard function to handle the result from OSSL_FUNC_store_load() */ struct ossl_load_result_data_st { OSSL_STORE_INFO *v; /* To be filled in */ OSSL_STORE_CTX *ctx; }; OSSL_CALLBACK ossl_store_handle_load_result;
4,857
26.446328
75
h
openssl
openssl-master/crypto/store/store_meth.c
/* * Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/crypto.h> #include "crypto/store.h" #include "internal/core.h" #include "internal/namemap.h" #include "internal/property.h" #include "internal/provider.h" #include "store_local.h" #include "crypto/context.h" int OSSL_STORE_LOADER_up_ref(OSSL_STORE_LOADER *loader) { int ref = 0; if (loader->prov != NULL) CRYPTO_UP_REF(&loader->refcnt, &ref); return 1; } void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *loader) { if (loader != NULL && loader->prov != NULL) { int i; CRYPTO_DOWN_REF(&loader->refcnt, &i); if (i > 0) return; ossl_provider_free(loader->prov); CRYPTO_FREE_REF(&loader->refcnt); } OPENSSL_free(loader); } /* * OSSL_STORE_LOADER_new() expects the scheme as a constant string, * which we currently don't have, so we need an alternative allocator. */ static OSSL_STORE_LOADER *new_loader(OSSL_PROVIDER *prov) { OSSL_STORE_LOADER *loader; if ((loader = OPENSSL_zalloc(sizeof(*loader))) == NULL || !CRYPTO_NEW_REF(&loader->refcnt, 1)) { OPENSSL_free(loader); return NULL; } loader->prov = prov; ossl_provider_up_ref(prov); return loader; } static int up_ref_loader(void *method) { return OSSL_STORE_LOADER_up_ref(method); } static void free_loader(void *method) { OSSL_STORE_LOADER_free(method); } /* Data to be passed through ossl_method_construct() */ struct loader_data_st { OSSL_LIB_CTX *libctx; int scheme_id; /* For get_loader_from_store() */ const char *scheme; /* For get_loader_from_store() */ const char *propquery; /* For get_loader_from_store() */ OSSL_METHOD_STORE *tmp_store; /* For get_tmp_loader_store() */ unsigned int flag_construct_error_occurred : 1; }; /* * Generic routines to fetch / create OSSL_STORE methods with * ossl_method_construct() */ /* Temporary loader method store, constructor and destructor */ static void *get_tmp_loader_store(void *data) { struct loader_data_st *methdata = data; if (methdata->tmp_store == NULL) methdata->tmp_store = ossl_method_store_new(methdata->libctx); return methdata->tmp_store; } static void dealloc_tmp_loader_store(void *store) { if (store != NULL) ossl_method_store_free(store); } /* Get the permanent loader store */ static OSSL_METHOD_STORE *get_loader_store(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_STORE_LOADER_STORE_INDEX); } static int reserve_loader_store(void *store, void *data) { struct loader_data_st *methdata = data; if (store == NULL && (store = get_loader_store(methdata->libctx)) == NULL) return 0; return ossl_method_lock_store(store); } static int unreserve_loader_store(void *store, void *data) { struct loader_data_st *methdata = data; if (store == NULL && (store = get_loader_store(methdata->libctx)) == NULL) return 0; return ossl_method_unlock_store(store); } /* Get loader methods from a store, or put one in */ static void *get_loader_from_store(void *store, const OSSL_PROVIDER **prov, void *data) { struct loader_data_st *methdata = data; void *method = NULL; int id; if ((id = methdata->scheme_id) == 0) { OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); id = ossl_namemap_name2num(namemap, methdata->scheme); } if (store == NULL && (store = get_loader_store(methdata->libctx)) == NULL) return NULL; if (!ossl_method_store_fetch(store, id, methdata->propquery, prov, &method)) return NULL; return method; } static int put_loader_in_store(void *store, void *method, const OSSL_PROVIDER *prov, const char *scheme, const char *propdef, void *data) { struct loader_data_st *methdata = data; OSSL_NAMEMAP *namemap; int id; if ((namemap = ossl_namemap_stored(methdata->libctx)) == NULL || (id = ossl_namemap_name2num(namemap, scheme)) == 0) return 0; if (store == NULL && (store = get_loader_store(methdata->libctx)) == NULL) return 0; return ossl_method_store_add(store, prov, id, propdef, method, up_ref_loader, free_loader); } static void *loader_from_algorithm(int scheme_id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov) { OSSL_STORE_LOADER *loader = NULL; const OSSL_DISPATCH *fns = algodef->implementation; if ((loader = new_loader(prov)) == NULL) return NULL; loader->scheme_id = scheme_id; loader->propdef = algodef->property_definition; loader->description = algodef->algorithm_description; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_STORE_OPEN: if (loader->p_open == NULL) loader->p_open = OSSL_FUNC_store_open(fns); break; case OSSL_FUNC_STORE_ATTACH: if (loader->p_attach == NULL) loader->p_attach = OSSL_FUNC_store_attach(fns); break; case OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS: if (loader->p_settable_ctx_params == NULL) loader->p_settable_ctx_params = OSSL_FUNC_store_settable_ctx_params(fns); break; case OSSL_FUNC_STORE_SET_CTX_PARAMS: if (loader->p_set_ctx_params == NULL) loader->p_set_ctx_params = OSSL_FUNC_store_set_ctx_params(fns); break; case OSSL_FUNC_STORE_LOAD: if (loader->p_load == NULL) loader->p_load = OSSL_FUNC_store_load(fns); break; case OSSL_FUNC_STORE_EOF: if (loader->p_eof == NULL) loader->p_eof = OSSL_FUNC_store_eof(fns); break; case OSSL_FUNC_STORE_CLOSE: if (loader->p_close == NULL) loader->p_close = OSSL_FUNC_store_close(fns); break; case OSSL_FUNC_STORE_EXPORT_OBJECT: if (loader->p_export_object == NULL) loader->p_export_object = OSSL_FUNC_store_export_object(fns); break; } } if ((loader->p_open == NULL && loader->p_attach == NULL) || loader->p_load == NULL || loader->p_eof == NULL || loader->p_close == NULL) { /* Only set_ctx_params is optionaal */ OSSL_STORE_LOADER_free(loader); ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_LOADER_INCOMPLETE); return NULL; } return loader; } /* * The core fetching functionality passes the scheme of the implementation. * This function is responsible to getting an identity number for them, * then call loader_from_algorithm() with that identity number. */ static void *construct_loader(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov, void *data) { /* * This function is only called if get_loader_from_store() returned * NULL, so it's safe to say that of all the spots to create a new * namemap entry, this is it. Should the scheme already exist there, we * know that ossl_namemap_add() will return its corresponding number. */ struct loader_data_st *methdata = data; OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); const char *scheme = algodef->algorithm_names; int id = ossl_namemap_add_name(namemap, 0, scheme); void *method = NULL; if (id != 0) method = loader_from_algorithm(id, algodef, prov); /* * Flag to indicate that there was actual construction errors. This * helps inner_loader_fetch() determine what error it should * record on inaccessible algorithms. */ if (method == NULL) methdata->flag_construct_error_occurred = 1; return method; } /* Intermediary function to avoid ugly casts, used below */ static void destruct_loader(void *method, void *data) { OSSL_STORE_LOADER_free(method); } /* Fetching support. Can fetch by numeric identity or by scheme */ static OSSL_STORE_LOADER * inner_loader_fetch(struct loader_data_st *methdata, const char *scheme, const char *properties) { OSSL_METHOD_STORE *store = get_loader_store(methdata->libctx); OSSL_NAMEMAP *namemap = ossl_namemap_stored(methdata->libctx); const char *const propq = properties != NULL ? properties : ""; void *method = NULL; int unsupported, id; if (store == NULL || namemap == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } /* If we haven't received a name id yet, try to get one for the name */ id = scheme != NULL ? ossl_namemap_name2num(namemap, scheme) : 0; /* * If we haven't found the name yet, chances are that the algorithm to * be fetched is unsupported. */ unsupported = id == 0; if (id == 0 || !ossl_method_store_cache_get(store, NULL, id, propq, &method)) { OSSL_METHOD_CONSTRUCT_METHOD mcm = { get_tmp_loader_store, reserve_loader_store, unreserve_loader_store, get_loader_from_store, put_loader_in_store, construct_loader, destruct_loader }; OSSL_PROVIDER *prov = NULL; methdata->scheme_id = id; methdata->scheme = scheme; methdata->propquery = propq; methdata->flag_construct_error_occurred = 0; if ((method = ossl_method_construct(methdata->libctx, OSSL_OP_STORE, &prov, 0 /* !force_cache */, &mcm, methdata)) != NULL) { /* * If construction did create a method for us, we know that there * is a correct scheme_id, since those have already been calculated * in get_loader_from_store() and put_loader_in_store() above. */ if (id == 0) id = ossl_namemap_name2num(namemap, scheme); ossl_method_store_cache_set(store, prov, id, propq, method, up_ref_loader, free_loader); } /* * If we never were in the constructor, the algorithm to be fetched * is unsupported. */ unsupported = !methdata->flag_construct_error_occurred; } if ((id != 0 || scheme != NULL) && method == NULL) { int code = unsupported ? ERR_R_UNSUPPORTED : ERR_R_FETCH_FAILED; const char *helpful_msg = unsupported ? ( "No store loader found. For standard store loaders you need " "at least one of the default or base providers available. " "Did you forget to load them? Info: " ) : ""; if (scheme == NULL) scheme = ossl_namemap_num2name(namemap, id, 0); ERR_raise_data(ERR_LIB_OSSL_STORE, code, "%s%s, Scheme (%s : %d), Properties (%s)", helpful_msg, ossl_lib_ctx_get_descriptor(methdata->libctx), scheme == NULL ? "<null>" : scheme, id, properties == NULL ? "<null>" : properties); } return method; } OSSL_STORE_LOADER *OSSL_STORE_LOADER_fetch(OSSL_LIB_CTX *libctx, const char *scheme, const char *properties) { struct loader_data_st methdata; void *method; methdata.libctx = libctx; methdata.tmp_store = NULL; method = inner_loader_fetch(&methdata, scheme, properties); dealloc_tmp_loader_store(methdata.tmp_store); return method; } int ossl_store_loader_store_cache_flush(OSSL_LIB_CTX *libctx) { OSSL_METHOD_STORE *store = get_loader_store(libctx); if (store != NULL) return ossl_method_store_cache_flush_all(store); return 1; } int ossl_store_loader_store_remove_all_provided(const OSSL_PROVIDER *prov) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); OSSL_METHOD_STORE *store = get_loader_store(libctx); if (store != NULL) return ossl_method_store_remove_all_provided(store, prov); return 1; } /* * Library of basic method functions */ const OSSL_PROVIDER *OSSL_STORE_LOADER_get0_provider(const OSSL_STORE_LOADER *loader) { if (!ossl_assert(loader != NULL)) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_NULL_PARAMETER); return 0; } return loader->prov; } const char *OSSL_STORE_LOADER_get0_properties(const OSSL_STORE_LOADER *loader) { if (!ossl_assert(loader != NULL)) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_NULL_PARAMETER); return 0; } return loader->propdef; } int ossl_store_loader_get_number(const OSSL_STORE_LOADER *loader) { if (!ossl_assert(loader != NULL)) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_NULL_PARAMETER); return 0; } return loader->scheme_id; } const char *OSSL_STORE_LOADER_get0_description(const OSSL_STORE_LOADER *loader) { return loader->description; } int OSSL_STORE_LOADER_is_a(const OSSL_STORE_LOADER *loader, const char *name) { if (loader->prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(loader->prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_name2num(namemap, name) == loader->scheme_id; } return 0; } struct do_one_data_st { void (*user_fn)(OSSL_STORE_LOADER *loader, void *arg); void *user_arg; }; static void do_one(ossl_unused int id, void *method, void *arg) { struct do_one_data_st *data = arg; data->user_fn(method, data->user_arg); } void OSSL_STORE_LOADER_do_all_provided(OSSL_LIB_CTX *libctx, void (*user_fn)(OSSL_STORE_LOADER *loader, void *arg), void *user_arg) { struct loader_data_st methdata; struct do_one_data_st data; methdata.libctx = libctx; methdata.tmp_store = NULL; (void)inner_loader_fetch(&methdata, NULL, NULL /* properties */); data.user_fn = user_fn; data.user_arg = user_arg; if (methdata.tmp_store != NULL) ossl_method_store_do_all(methdata.tmp_store, &do_one, &data); ossl_method_store_do_all(get_loader_store(libctx), &do_one, &data); dealloc_tmp_loader_store(methdata.tmp_store); } int OSSL_STORE_LOADER_names_do_all(const OSSL_STORE_LOADER *loader, void (*fn)(const char *name, void *data), void *data) { if (loader == NULL) return 0; if (loader->prov != NULL) { OSSL_LIB_CTX *libctx = ossl_provider_libctx(loader->prov); OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx); return ossl_namemap_doall_names(namemap, loader->scheme_id, fn, data); } return 1; }
15,511
30.40081
85
c
openssl
openssl-master/crypto/store/store_register.c
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include "crypto/ctype.h" #include <assert.h> #include <openssl/err.h> #include <openssl/lhash.h> #include "store_local.h" static CRYPTO_RWLOCK *registry_lock; static CRYPTO_ONCE registry_init = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(do_registry_init) { registry_lock = CRYPTO_THREAD_lock_new(); return registry_lock != NULL; } /* * Functions for manipulating OSSL_STORE_LOADERs */ OSSL_STORE_LOADER *OSSL_STORE_LOADER_new(ENGINE *e, const char *scheme) { OSSL_STORE_LOADER *res = NULL; /* * We usually don't check NULL arguments. For loaders, though, the * scheme is crucial and must never be NULL, or the user will get * mysterious errors when trying to register the created loader * later on. */ if (scheme == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_INVALID_SCHEME); return NULL; } if ((res = OPENSSL_zalloc(sizeof(*res))) == NULL) return NULL; res->engine = e; res->scheme = scheme; return res; } const ENGINE *OSSL_STORE_LOADER_get0_engine(const OSSL_STORE_LOADER *loader) { return loader->engine; } const char *OSSL_STORE_LOADER_get0_scheme(const OSSL_STORE_LOADER *loader) { return loader->scheme; } int OSSL_STORE_LOADER_set_open(OSSL_STORE_LOADER *loader, OSSL_STORE_open_fn open_function) { loader->open = open_function; return 1; } int OSSL_STORE_LOADER_set_open_ex (OSSL_STORE_LOADER *loader, OSSL_STORE_open_ex_fn open_ex_function) { loader->open_ex = open_ex_function; return 1; } int OSSL_STORE_LOADER_set_attach(OSSL_STORE_LOADER *loader, OSSL_STORE_attach_fn attach_function) { loader->attach = attach_function; return 1; } int OSSL_STORE_LOADER_set_ctrl(OSSL_STORE_LOADER *loader, OSSL_STORE_ctrl_fn ctrl_function) { loader->ctrl = ctrl_function; return 1; } int OSSL_STORE_LOADER_set_expect(OSSL_STORE_LOADER *loader, OSSL_STORE_expect_fn expect_function) { loader->expect = expect_function; return 1; } int OSSL_STORE_LOADER_set_find(OSSL_STORE_LOADER *loader, OSSL_STORE_find_fn find_function) { loader->find = find_function; return 1; } int OSSL_STORE_LOADER_set_load(OSSL_STORE_LOADER *loader, OSSL_STORE_load_fn load_function) { loader->load = load_function; return 1; } int OSSL_STORE_LOADER_set_eof(OSSL_STORE_LOADER *loader, OSSL_STORE_eof_fn eof_function) { loader->eof = eof_function; return 1; } int OSSL_STORE_LOADER_set_error(OSSL_STORE_LOADER *loader, OSSL_STORE_error_fn error_function) { loader->error = error_function; return 1; } int OSSL_STORE_LOADER_set_close(OSSL_STORE_LOADER *loader, OSSL_STORE_close_fn close_function) { loader->closefn = close_function; return 1; } /* * Functions for registering OSSL_STORE_LOADERs */ static unsigned long store_loader_hash(const OSSL_STORE_LOADER *v) { return OPENSSL_LH_strhash(v->scheme); } static int store_loader_cmp(const OSSL_STORE_LOADER *a, const OSSL_STORE_LOADER *b) { assert(a->scheme != NULL && b->scheme != NULL); return strcmp(a->scheme, b->scheme); } static LHASH_OF(OSSL_STORE_LOADER) *loader_register = NULL; static int ossl_store_register_init(void) { if (loader_register == NULL) { loader_register = lh_OSSL_STORE_LOADER_new(store_loader_hash, store_loader_cmp); } return loader_register != NULL; } int ossl_store_register_loader_int(OSSL_STORE_LOADER *loader) { const char *scheme = loader->scheme; int ok = 0; /* * Check that the given scheme conforms to correct scheme syntax as per * RFC 3986: * * scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */ if (ossl_isalpha(*scheme)) while (*scheme != '\0' && (ossl_isalpha(*scheme) || ossl_isdigit(*scheme) || strchr("+-.", *scheme) != NULL)) scheme++; if (*scheme != '\0') { ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_INVALID_SCHEME, "scheme=%s", loader->scheme); return 0; } /* Check that functions we absolutely require are present */ if (loader->open == NULL || loader->load == NULL || loader->eof == NULL || loader->error == NULL || loader->closefn == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_LOADER_INCOMPLETE); return 0; } if (!RUN_ONCE(&registry_init, do_registry_init)) { /* Should this error be raised in do_registry_init()? */ ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); return 0; } if (!CRYPTO_THREAD_write_lock(registry_lock)) return 0; if (ossl_store_register_init() && (lh_OSSL_STORE_LOADER_insert(loader_register, loader) != NULL || lh_OSSL_STORE_LOADER_error(loader_register) == 0)) ok = 1; CRYPTO_THREAD_unlock(registry_lock); return ok; } int OSSL_STORE_register_loader(OSSL_STORE_LOADER *loader) { return ossl_store_register_loader_int(loader); } const OSSL_STORE_LOADER *ossl_store_get0_loader_int(const char *scheme) { OSSL_STORE_LOADER template; OSSL_STORE_LOADER *loader = NULL; template.scheme = scheme; template.open = NULL; template.load = NULL; template.eof = NULL; template.closefn = NULL; template.open_ex = NULL; if (!RUN_ONCE(&registry_init, do_registry_init)) { /* Should this error be raised in do_registry_init()? */ ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); return NULL; } if (!CRYPTO_THREAD_write_lock(registry_lock)) return NULL; if (!ossl_store_register_init()) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_INTERNAL_ERROR); else if ((loader = lh_OSSL_STORE_LOADER_retrieve(loader_register, &template)) == NULL) ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_UNREGISTERED_SCHEME, "scheme=%s", scheme); CRYPTO_THREAD_unlock(registry_lock); return loader; } OSSL_STORE_LOADER *ossl_store_unregister_loader_int(const char *scheme) { OSSL_STORE_LOADER template; OSSL_STORE_LOADER *loader = NULL; template.scheme = scheme; template.open = NULL; template.load = NULL; template.eof = NULL; template.closefn = NULL; if (!RUN_ONCE(&registry_init, do_registry_init)) { /* Should this error be raised in do_registry_init()? */ ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); return NULL; } if (!CRYPTO_THREAD_write_lock(registry_lock)) return NULL; if (!ossl_store_register_init()) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_INTERNAL_ERROR); else if ((loader = lh_OSSL_STORE_LOADER_delete(loader_register, &template)) == NULL) ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_UNREGISTERED_SCHEME, "scheme=%s", scheme); CRYPTO_THREAD_unlock(registry_lock); return loader; } OSSL_STORE_LOADER *OSSL_STORE_unregister_loader(const char *scheme) { return ossl_store_unregister_loader_int(scheme); } void ossl_store_destroy_loaders_int(void) { lh_OSSL_STORE_LOADER_free(loader_register); loader_register = NULL; CRYPTO_THREAD_lock_free(registry_lock); registry_lock = NULL; } /* * Functions to list OSSL_STORE loaders */ IMPLEMENT_LHASH_DOALL_ARG_CONST(OSSL_STORE_LOADER, void); int OSSL_STORE_do_all_loaders(void (*do_function) (const OSSL_STORE_LOADER *loader, void *do_arg), void *do_arg) { if (ossl_store_register_init()) lh_OSSL_STORE_LOADER_doall_void(loader_register, do_function, do_arg); return 1; }
8,476
27.162791
78
c
openssl
openssl-master/crypto/store/store_result.c
/* * Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/e_os.h" #include <string.h> #include <openssl/core.h> #include <openssl/core_names.h> #include <openssl/core_object.h> #include <openssl/err.h> #include <openssl/pkcs12.h> #include <openssl/provider.h> #include <openssl/decoder.h> #include <openssl/store.h> #include "internal/provider.h" #include "internal/passphrase.h" #include "crypto/evp.h" #include "crypto/x509.h" #include "store_local.h" #ifndef OSSL_OBJECT_PKCS12 /* * The object abstraction doesn't know PKCS#12, but we want to indicate * it anyway, so we create our own. Since the public macros use positive * numbers, negative ones should be fine. They must never slip out from * this translation unit anyway. */ # define OSSL_OBJECT_PKCS12 -1 #endif /* * ossl_store_handle_load_result() is initially written to be a companion * to our 'file:' scheme provider implementation, but has been made generic * to serve others as well. * * This result handler takes any object abstraction (see provider-object(7)) * and does the best it can with it. If the object is passed by value (not * by reference), the contents are currently expected to be DER encoded. * If an object type is specified, that will be respected; otherwise, this * handler will guess the contents, by trying the following in order: * * 1. Decode it into an EVP_PKEY, using OSSL_DECODER. * 2. Decode it into an X.509 certificate, using d2i_X509 / d2i_X509_AUX. * 3. Decode it into an X.509 CRL, using d2i_X509_CRL. * 4. Decode it into a PKCS#12 structure, using d2i_PKCS12 (*). * * For the 'file:' scheme implementation, this is division of labor. Since * the libcrypto <-> provider interface currently doesn't support certain * structures as first class objects, they must be unpacked from DER here * rather than in the provider. The current exception is asymmetric keys, * which can reside within the provider boundary, most of all thanks to * OSSL_FUNC_keymgmt_load(), which allows loading the key material by * reference. */ struct extracted_param_data_st { int object_type; const char *data_type; const char *data_structure; const char *utf8_data; const void *octet_data; size_t octet_data_size; const void *ref; size_t ref_size; const char *desc; }; static int try_name(struct extracted_param_data_st *, OSSL_STORE_INFO **); static int try_key(struct extracted_param_data_st *, OSSL_STORE_INFO **, OSSL_STORE_CTX *, const OSSL_PROVIDER *, OSSL_LIB_CTX *, const char *); static int try_cert(struct extracted_param_data_st *, OSSL_STORE_INFO **, OSSL_LIB_CTX *, const char *); static int try_crl(struct extracted_param_data_st *, OSSL_STORE_INFO **, OSSL_LIB_CTX *, const char *); static int try_pkcs12(struct extracted_param_data_st *, OSSL_STORE_INFO **, OSSL_STORE_CTX *, OSSL_LIB_CTX *, const char *); int ossl_store_handle_load_result(const OSSL_PARAM params[], void *arg) { struct ossl_load_result_data_st *cbdata = arg; OSSL_STORE_INFO **v = &cbdata->v; OSSL_STORE_CTX *ctx = cbdata->ctx; const OSSL_PROVIDER *provider = OSSL_STORE_LOADER_get0_provider(ctx->fetched_loader); OSSL_LIB_CTX *libctx = ossl_provider_libctx(provider); const char *propq = ctx->properties; const OSSL_PARAM *p; struct extracted_param_data_st helper_data; memset(&helper_data, 0, sizeof(helper_data)); helper_data.object_type = OSSL_OBJECT_UNKNOWN; if ((p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_TYPE)) != NULL && !OSSL_PARAM_get_int(p, &helper_data.object_type)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.data_type)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA); if (p != NULL && !OSSL_PARAM_get_octet_string_ptr(p, &helper_data.octet_data, &helper_data.octet_data_size) && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.utf8_data)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_STRUCTURE); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.data_structure)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE); if (p != NULL && !OSSL_PARAM_get_octet_string_ptr(p, &helper_data.ref, &helper_data.ref_size)) return 0; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DESC); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.desc)) return 0; /* * The helper functions return 0 on actual errors, otherwise 1, even if * they didn't fill out |*v|. */ ERR_set_mark(); if (*v == NULL && !try_name(&helper_data, v)) goto err; ERR_pop_to_mark(); ERR_set_mark(); if (*v == NULL && !try_key(&helper_data, v, ctx, provider, libctx, propq)) goto err; ERR_pop_to_mark(); ERR_set_mark(); if (*v == NULL && !try_cert(&helper_data, v, libctx, propq)) goto err; ERR_pop_to_mark(); ERR_set_mark(); if (*v == NULL && !try_crl(&helper_data, v, libctx, propq)) goto err; ERR_pop_to_mark(); ERR_set_mark(); if (*v == NULL && !try_pkcs12(&helper_data, v, ctx, libctx, propq)) goto err; ERR_pop_to_mark(); if (*v == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_UNSUPPORTED); return (*v != NULL); err: ERR_clear_last_mark(); return 0; } static int try_name(struct extracted_param_data_st *data, OSSL_STORE_INFO **v) { if (data->object_type == OSSL_OBJECT_NAME) { char *newname = NULL, *newdesc = NULL; if (data->utf8_data == NULL) return 0; if ((newname = OPENSSL_strdup(data->utf8_data)) == NULL || (data->desc != NULL && (newdesc = OPENSSL_strdup(data->desc)) == NULL) || (*v = OSSL_STORE_INFO_new_NAME(newname)) == NULL) { OPENSSL_free(newname); OPENSSL_free(newdesc); return 0; } OSSL_STORE_INFO_set0_NAME_description(*v, newdesc); } return 1; } /* * For the rest of the object types, the provider code may not know what * type of data it gave us, so we may need to figure that out on our own. * Therefore, we do check for OSSL_OBJECT_UNKNOWN everywhere below, and * only return 0 on error if the object type is known. */ static EVP_PKEY *try_key_ref(struct extracted_param_data_st *data, OSSL_STORE_CTX *ctx, const OSSL_PROVIDER *provider, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pk = NULL; EVP_KEYMGMT *keymgmt = NULL; void *keydata = NULL; int try_fallback = 2; /* If we have an object reference, we must have a data type */ if (data->data_type == NULL) return 0; keymgmt = EVP_KEYMGMT_fetch(libctx, data->data_type, propq); ERR_set_mark(); while (keymgmt != NULL && keydata == NULL && try_fallback-- > 0) { /* * There are two possible cases * * 1. The keymgmt is from the same provider as the loader, * so we can use evp_keymgmt_load() * 2. The keymgmt is from another provider, then we must * do the export/import dance. */ if (EVP_KEYMGMT_get0_provider(keymgmt) == provider) { /* no point trying fallback here */ try_fallback = 0; keydata = evp_keymgmt_load(keymgmt, data->ref, data->ref_size); } else { struct evp_keymgmt_util_try_import_data_st import_data; OSSL_FUNC_store_export_object_fn *export_object = ctx->fetched_loader->p_export_object; import_data.keymgmt = keymgmt; import_data.keydata = NULL; import_data.selection = OSSL_KEYMGMT_SELECT_ALL; if (export_object != NULL) { /* * No need to check for errors here, the value of * |import_data.keydata| is as much an indicator. */ (void)export_object(ctx->loader_ctx, data->ref, data->ref_size, &evp_keymgmt_util_try_import, &import_data); } keydata = import_data.keydata; } if (keydata == NULL && try_fallback > 0) { EVP_KEYMGMT_free(keymgmt); keymgmt = evp_keymgmt_fetch_from_prov((OSSL_PROVIDER *)provider, data->data_type, propq); if (keymgmt != NULL) { ERR_pop_to_mark(); ERR_set_mark(); } } } if (keydata != NULL) { ERR_pop_to_mark(); pk = evp_keymgmt_util_make_pkey(keymgmt, keydata); } else { ERR_clear_last_mark(); } EVP_KEYMGMT_free(keymgmt); return pk; } static EVP_PKEY *try_key_value(struct extracted_param_data_st *data, OSSL_STORE_CTX *ctx, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pk = NULL; OSSL_DECODER_CTX *decoderctx = NULL; const unsigned char *pdata = data->octet_data; size_t pdatalen = data->octet_data_size; int selection = 0; switch (ctx->expected_type) { case 0: break; case OSSL_STORE_INFO_PARAMS: selection = OSSL_KEYMGMT_SELECT_ALL_PARAMETERS; break; case OSSL_STORE_INFO_PUBKEY: selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS; break; case OSSL_STORE_INFO_PKEY: selection = OSSL_KEYMGMT_SELECT_ALL; break; default: return NULL; } decoderctx = OSSL_DECODER_CTX_new_for_pkey(&pk, NULL, data->data_structure, data->data_type, selection, libctx, propq); (void)OSSL_DECODER_CTX_set_passphrase_cb(decoderctx, cb, cbarg); /* No error if this couldn't be decoded */ (void)OSSL_DECODER_from_data(decoderctx, &pdata, &pdatalen); OSSL_DECODER_CTX_free(decoderctx); return pk; } typedef OSSL_STORE_INFO *store_info_new_fn(EVP_PKEY *); static EVP_PKEY *try_key_value_legacy(struct extracted_param_data_st *data, store_info_new_fn **store_info_new, OSSL_STORE_CTX *ctx, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pk = NULL; const unsigned char *der = data->octet_data, *derp; long der_len = (long)data->octet_data_size; /* Try PUBKEY first, that's a real easy target */ if (ctx->expected_type == 0 || ctx->expected_type == OSSL_STORE_INFO_PUBKEY) { derp = der; pk = d2i_PUBKEY_ex(NULL, &derp, der_len, libctx, propq); if (pk != NULL) *store_info_new = OSSL_STORE_INFO_new_PUBKEY; } /* Try private keys next */ if (pk == NULL && (ctx->expected_type == 0 || ctx->expected_type == OSSL_STORE_INFO_PKEY)) { unsigned char *new_der = NULL; X509_SIG *p8 = NULL; PKCS8_PRIV_KEY_INFO *p8info = NULL; /* See if it's an encrypted PKCS#8 and decrypt it. */ derp = der; p8 = d2i_X509_SIG(NULL, &derp, der_len); if (p8 != NULL) { char pbuf[PEM_BUFSIZE]; size_t plen = 0; if (!cb(pbuf, sizeof(pbuf), &plen, NULL, cbarg)) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_BAD_PASSWORD_READ); } else { const X509_ALGOR *alg = NULL; const ASN1_OCTET_STRING *oct = NULL; int len = 0; X509_SIG_get0(p8, &alg, &oct); /* * No need to check the returned value, |new_der| * will be NULL on error anyway. */ PKCS12_pbe_crypt(alg, pbuf, plen, oct->data, oct->length, &new_der, &len, 0); der_len = len; der = new_der; } X509_SIG_free(p8); } /* * If the encrypted PKCS#8 couldn't be decrypted, * |der| is NULL */ if (der != NULL) { /* Try to unpack an unencrypted PKCS#8, that's easy */ derp = der; p8info = d2i_PKCS8_PRIV_KEY_INFO(NULL, &derp, der_len); if (p8info != NULL) { pk = EVP_PKCS82PKEY_ex(p8info, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8info); } } if (pk != NULL) *store_info_new = OSSL_STORE_INFO_new_PKEY; OPENSSL_free(new_der); } return pk; } static int try_key(struct extracted_param_data_st *data, OSSL_STORE_INFO **v, OSSL_STORE_CTX *ctx, const OSSL_PROVIDER *provider, OSSL_LIB_CTX *libctx, const char *propq) { store_info_new_fn *store_info_new = NULL; if (data->object_type == OSSL_OBJECT_UNKNOWN || data->object_type == OSSL_OBJECT_PKEY) { EVP_PKEY *pk = NULL; /* Prefer key by reference than key by value */ if (data->object_type == OSSL_OBJECT_PKEY && data->ref != NULL) { pk = try_key_ref(data, ctx, provider, libctx, propq); /* * If for some reason we couldn't get a key, it's an error. * It indicates that while decoders could make a key reference, * the keymgmt somehow couldn't handle it, or doesn't have a * OSSL_FUNC_keymgmt_load function. */ if (pk == NULL) return 0; } else if (data->octet_data != NULL) { OSSL_PASSPHRASE_CALLBACK *cb = ossl_pw_passphrase_callback_dec; void *cbarg = &ctx->pwdata; pk = try_key_value(data, ctx, cb, cbarg, libctx, propq); /* * Desperate last maneuver, in case the decoders don't support * the data we have, then we try on our own to at least get an * engine provided legacy key. * This is the same as der2key_decode() does, but in a limited * way and within the walls of libcrypto. */ if (pk == NULL) pk = try_key_value_legacy(data, &store_info_new, ctx, cb, cbarg, libctx, propq); } if (pk != NULL) { data->object_type = OSSL_OBJECT_PKEY; if (store_info_new == NULL) { /* * We determined the object type for OSSL_STORE_INFO, which * makes an explicit difference between an EVP_PKEY with just * (domain) parameters and an EVP_PKEY with actual key * material. * The logic is that an EVP_PKEY with actual key material * always has the public half. */ if (evp_keymgmt_util_has(pk, OSSL_KEYMGMT_SELECT_PRIVATE_KEY)) store_info_new = OSSL_STORE_INFO_new_PKEY; else if (evp_keymgmt_util_has(pk, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)) store_info_new = OSSL_STORE_INFO_new_PUBKEY; else store_info_new = OSSL_STORE_INFO_new_PARAMS; } *v = store_info_new(pk); } if (*v == NULL) EVP_PKEY_free(pk); } return 1; } static int try_cert(struct extracted_param_data_st *data, OSSL_STORE_INFO **v, OSSL_LIB_CTX *libctx, const char *propq) { if (data->object_type == OSSL_OBJECT_UNKNOWN || data->object_type == OSSL_OBJECT_CERT) { /* * In most cases, we can try to interpret the serialized * data as a trusted cert (X509 + X509_AUX) and fall back * to reading it as a normal cert (just X509), but if * |data_type| (the PEM name) specifically declares it as a * trusted cert, then no fallback should be engaged. * |ignore_trusted| tells if the fallback can be used (1) * or not (0). */ int ignore_trusted = 1; X509 *cert = X509_new_ex(libctx, propq); if (cert == NULL) return 0; /* If we have a data type, it should be a PEM name */ if (data->data_type != NULL && (OPENSSL_strcasecmp(data->data_type, PEM_STRING_X509_TRUSTED) == 0)) ignore_trusted = 0; if (d2i_X509_AUX(&cert, (const unsigned char **)&data->octet_data, data->octet_data_size) == NULL && (!ignore_trusted || d2i_X509(&cert, (const unsigned char **)&data->octet_data, data->octet_data_size) == NULL)) { X509_free(cert); cert = NULL; } if (cert != NULL) { /* We determined the object type */ data->object_type = OSSL_OBJECT_CERT; *v = OSSL_STORE_INFO_new_CERT(cert); if (*v == NULL) X509_free(cert); } } return 1; } static int try_crl(struct extracted_param_data_st *data, OSSL_STORE_INFO **v, OSSL_LIB_CTX *libctx, const char *propq) { if (data->object_type == OSSL_OBJECT_UNKNOWN || data->object_type == OSSL_OBJECT_CRL) { X509_CRL *crl; crl = d2i_X509_CRL(NULL, (const unsigned char **)&data->octet_data, data->octet_data_size); if (crl != NULL) /* We determined the object type */ data->object_type = OSSL_OBJECT_CRL; if (crl != NULL && !ossl_x509_crl_set0_libctx(crl, libctx, propq)) { X509_CRL_free(crl); crl = NULL; } if (crl != NULL) *v = OSSL_STORE_INFO_new_CRL(crl); if (*v == NULL) X509_CRL_free(crl); } return 1; } static int try_pkcs12(struct extracted_param_data_st *data, OSSL_STORE_INFO **v, OSSL_STORE_CTX *ctx, OSSL_LIB_CTX *libctx, const char *propq) { int ok = 1; /* There is no specific object type for PKCS12 */ if (data->object_type == OSSL_OBJECT_UNKNOWN) { /* Initial parsing */ PKCS12 *p12; p12 = d2i_PKCS12(NULL, (const unsigned char **)&data->octet_data, data->octet_data_size); if (p12 != NULL) { char *pass = NULL; char tpass[PEM_BUFSIZE + 1]; size_t tpass_len; EVP_PKEY *pkey = NULL; X509 *cert = NULL; STACK_OF(X509) *chain = NULL; data->object_type = OSSL_OBJECT_PKCS12; ok = 0; /* Assume decryption or parse error */ if (!PKCS12_mac_present(p12) || PKCS12_verify_mac(p12, NULL, 0)) { pass = NULL; } else if (PKCS12_verify_mac(p12, "", 0)) { pass = ""; } else { static char prompt_info[] = "PKCS12 import pass phrase"; OSSL_PARAM pw_params[] = { OSSL_PARAM_utf8_string(OSSL_PASSPHRASE_PARAM_INFO, prompt_info, sizeof(prompt_info) - 1), OSSL_PARAM_END }; if (!ossl_pw_get_passphrase(tpass, sizeof(tpass) - 1, &tpass_len, pw_params, 0, &ctx->pwdata)) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR); goto p12_end; } pass = tpass; /* * ossl_pw_get_passphrase() does not NUL terminate but * we must do it for PKCS12_parse() */ pass[tpass_len] = '\0'; if (!PKCS12_verify_mac(p12, pass, tpass_len)) { ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC, tpass_len == 0 ? "empty password" : "maybe wrong password"); goto p12_end; } } if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) { STACK_OF(OSSL_STORE_INFO) *infos = NULL; OSSL_STORE_INFO *osi_pkey = NULL; OSSL_STORE_INFO *osi_cert = NULL; OSSL_STORE_INFO *osi_ca = NULL; ok = 1; /* Parsing went through correctly! */ if ((infos = sk_OSSL_STORE_INFO_new_null()) != NULL) { if (pkey != NULL) { if ((osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL /* clearing pkey here avoids case distinctions */ && (pkey = NULL) == NULL && sk_OSSL_STORE_INFO_push(infos, osi_pkey) != 0) osi_pkey = NULL; else ok = 0; } if (ok && cert != NULL) { if ((osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL /* clearing cert here avoids case distinctions */ && (cert = NULL) == NULL && sk_OSSL_STORE_INFO_push(infos, osi_cert) != 0) osi_cert = NULL; else ok = 0; } while (ok && sk_X509_num(chain) > 0) { X509 *ca = sk_X509_value(chain, 0); if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) != NULL && sk_X509_shift(chain) != NULL && sk_OSSL_STORE_INFO_push(infos, osi_ca) != 0) osi_ca = NULL; else ok = 0; } } EVP_PKEY_free(pkey); X509_free(cert); OSSL_STACK_OF_X509_free(chain); OSSL_STORE_INFO_free(osi_pkey); OSSL_STORE_INFO_free(osi_cert); OSSL_STORE_INFO_free(osi_ca); if (!ok) { sk_OSSL_STORE_INFO_pop_free(infos, OSSL_STORE_INFO_free); infos = NULL; } ctx->cached_info = infos; } p12_end: OPENSSL_cleanse(tpass, sizeof(tpass)); PKCS12_free(p12); } *v = sk_OSSL_STORE_INFO_shift(ctx->cached_info); } return ok; }
23,840
35.62212
83
c
openssl
openssl-master/crypto/store/store_strings.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/store.h> static char *type_strings[] = { "Name", /* OSSL_STORE_INFO_NAME */ "Parameters", /* OSSL_STORE_INFO_PARAMS */ "Public key", /* OSSL_STORE_INFO_PUBKEY */ "Pkey", /* OSSL_STORE_INFO_PKEY */ "Certificate", /* OSSL_STORE_INFO_CERT */ "CRL" /* OSSL_STORE_INFO_CRL */ }; const char *OSSL_STORE_INFO_type_string(int type) { int types = sizeof(type_strings) / sizeof(type_strings[0]); if (type < 1 || type > types) return NULL; return type_strings[type - 1]; }
974
31.5
74
c
openssl
openssl-master/crypto/thread/api.c
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/configuration.h> #include <openssl/thread.h> #include <internal/thread.h> uint32_t OSSL_get_thread_support_flags(void) { int support = 0; #if !defined(OPENSSL_NO_THREAD_POOL) support |= OSSL_THREAD_SUPPORT_FLAG_THREAD_POOL; #endif #if !defined(OPENSSL_NO_DEFAULT_THREAD_POOL) support |= OSSL_THREAD_SUPPORT_FLAG_DEFAULT_SPAWN; #endif return support; } #if defined(OPENSSL_NO_THREAD_POOL) || defined(OPENSSL_NO_DEFAULT_THREAD_POOL) int OSSL_set_max_threads(OSSL_LIB_CTX *ctx, uint64_t max_threads) { return 0; } uint64_t OSSL_get_max_threads(OSSL_LIB_CTX *ctx) { return 0; } #else uint64_t OSSL_get_max_threads(OSSL_LIB_CTX *ctx) { uint64_t ret = 0; OSSL_LIB_CTX_THREADS *tdata = OSSL_LIB_CTX_GET_THREADS(ctx); if (tdata == NULL) goto fail; ossl_crypto_mutex_lock(tdata->lock); ret = tdata->max_threads; ossl_crypto_mutex_unlock(tdata->lock); fail: return ret; } int OSSL_set_max_threads(OSSL_LIB_CTX *ctx, uint64_t max_threads) { OSSL_LIB_CTX_THREADS *tdata; tdata = OSSL_LIB_CTX_GET_THREADS(ctx); if (tdata == NULL) return 0; ossl_crypto_mutex_lock(tdata->lock); tdata->max_threads = max_threads; ossl_crypto_mutex_unlock(tdata->lock); return 1; } #endif
1,623
20.945946
78
c
openssl
openssl-master/crypto/thread/arch.c
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/configuration.h> #include <internal/thread_arch.h> CRYPTO_THREAD *ossl_crypto_thread_native_start(CRYPTO_THREAD_ROUTINE routine, void *data, int joinable) { CRYPTO_THREAD *handle; if (routine == NULL) return NULL; handle = OPENSSL_zalloc(sizeof(*handle)); if (handle == NULL) return NULL; if ((handle->lock = ossl_crypto_mutex_new()) == NULL) goto fail; if ((handle->statelock = ossl_crypto_mutex_new()) == NULL) goto fail; if ((handle->condvar = ossl_crypto_condvar_new()) == NULL) goto fail; handle->data = data; handle->routine = routine; handle->joinable = joinable; if (ossl_crypto_thread_native_spawn(handle) == 1) return handle; fail: ossl_crypto_condvar_free(&handle->condvar); ossl_crypto_mutex_free(&handle->statelock); ossl_crypto_mutex_free(&handle->lock); OPENSSL_free(handle); return NULL; } int ossl_crypto_thread_native_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval) { uint64_t req_state_mask; if (thread == NULL) return 0; ossl_crypto_mutex_lock(thread->statelock); req_state_mask = CRYPTO_THREAD_FINISHED | CRYPTO_THREAD_JOINED; while (!CRYPTO_THREAD_GET_STATE(thread, req_state_mask)) ossl_crypto_condvar_wait(thread->condvar, thread->statelock); if (CRYPTO_THREAD_GET_STATE(thread, CRYPTO_THREAD_JOINED)) goto pass; /* Await concurrent join completion, if any. */ while (CRYPTO_THREAD_GET_STATE(thread, CRYPTO_THREAD_JOIN_AWAIT)) { if (!CRYPTO_THREAD_GET_STATE(thread, CRYPTO_THREAD_JOINED)) ossl_crypto_condvar_wait(thread->condvar, thread->statelock); if (CRYPTO_THREAD_GET_STATE(thread, CRYPTO_THREAD_JOINED)) goto pass; } CRYPTO_THREAD_SET_STATE(thread, CRYPTO_THREAD_JOIN_AWAIT); ossl_crypto_mutex_unlock(thread->statelock); if (ossl_crypto_thread_native_perform_join(thread, retval) == 0) goto fail; ossl_crypto_mutex_lock(thread->statelock); pass: CRYPTO_THREAD_UNSET_ERROR(thread, CRYPTO_THREAD_JOINED); CRYPTO_THREAD_SET_STATE(thread, CRYPTO_THREAD_JOINED); /* * Signal join completion. It is important to signal even if we haven't * performed an actual join. Multiple threads could be awaiting the * CRYPTO_THREAD_JOIN_AWAIT -> CRYPTO_THREAD_JOINED transition, but signal * on actual join would wake only one. Signalling here will always wake one. */ ossl_crypto_condvar_signal(thread->condvar); ossl_crypto_mutex_unlock(thread->statelock); if (retval != NULL) *retval = thread->retval; return 1; fail: ossl_crypto_mutex_lock(thread->statelock); CRYPTO_THREAD_SET_ERROR(thread, CRYPTO_THREAD_JOINED); /* Have another thread that's awaiting join retry to avoid that * thread deadlock. */ CRYPTO_THREAD_UNSET_STATE(thread, CRYPTO_THREAD_JOIN_AWAIT); ossl_crypto_condvar_signal(thread->condvar); ossl_crypto_mutex_unlock(thread->statelock); return 0; } int ossl_crypto_thread_native_clean(CRYPTO_THREAD *handle) { uint64_t req_state_mask; if (handle == NULL) return 0; req_state_mask = 0; req_state_mask |= CRYPTO_THREAD_FINISHED; req_state_mask |= CRYPTO_THREAD_JOINED; ossl_crypto_mutex_lock(handle->statelock); if (CRYPTO_THREAD_GET_STATE(handle, req_state_mask) == 0) { ossl_crypto_mutex_unlock(handle->statelock); return 0; } ossl_crypto_mutex_unlock(handle->statelock); ossl_crypto_mutex_free(&handle->lock); ossl_crypto_mutex_free(&handle->statelock); ossl_crypto_condvar_free(&handle->condvar); OPENSSL_free(handle->handle); OPENSSL_free(handle); return 1; }
4,147
30.18797
87
c
openssl
openssl-master/crypto/thread/internal.c
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/configuration.h> #include <openssl/e_os2.h> #include <openssl/types.h> #include <openssl/crypto.h> #include <internal/thread.h> #include <internal/thread_arch.h> #if !defined(OPENSSL_NO_DEFAULT_THREAD_POOL) static ossl_inline uint64_t _ossl_get_avail_threads(OSSL_LIB_CTX_THREADS *tdata) { /* assumes that tdata->lock is taken */ return tdata->max_threads - tdata->active_threads; } uint64_t ossl_get_avail_threads(OSSL_LIB_CTX *ctx) { uint64_t retval = 0; OSSL_LIB_CTX_THREADS *tdata = OSSL_LIB_CTX_GET_THREADS(ctx); if (tdata == NULL) return retval; ossl_crypto_mutex_lock(tdata->lock); retval = _ossl_get_avail_threads(tdata); ossl_crypto_mutex_unlock(tdata->lock); return retval; } void *ossl_crypto_thread_start(OSSL_LIB_CTX *ctx, CRYPTO_THREAD_ROUTINE start, void *data) { CRYPTO_THREAD *thread; OSSL_LIB_CTX_THREADS *tdata = OSSL_LIB_CTX_GET_THREADS(ctx); if (tdata == NULL) return NULL; ossl_crypto_mutex_lock(tdata->lock); if (tdata == NULL || tdata->max_threads == 0) { ossl_crypto_mutex_unlock(tdata->lock); return NULL; } while (_ossl_get_avail_threads(tdata) == 0) ossl_crypto_condvar_wait(tdata->cond_finished, tdata->lock); tdata->active_threads++; ossl_crypto_mutex_unlock(tdata->lock); thread = ossl_crypto_thread_native_start(start, data, 1); if (thread == NULL) { ossl_crypto_mutex_lock(tdata->lock); tdata->active_threads--; ossl_crypto_mutex_unlock(tdata->lock); goto fail; } thread->ctx = ctx; fail: return (void *) thread; } int ossl_crypto_thread_join(void *vhandle, CRYPTO_THREAD_RETVAL *retval) { CRYPTO_THREAD *handle = vhandle; OSSL_LIB_CTX_THREADS *tdata; if (vhandle == NULL) return 0; tdata = OSSL_LIB_CTX_GET_THREADS(handle->ctx); if (tdata == NULL) return 0; if (ossl_crypto_thread_native_join(handle, retval) == 0) return 0; ossl_crypto_mutex_lock(tdata->lock); tdata->active_threads--; ossl_crypto_condvar_signal(tdata->cond_finished); ossl_crypto_mutex_unlock(tdata->lock); return 1; } int ossl_crypto_thread_clean(void *vhandle) { CRYPTO_THREAD *handle = vhandle; return ossl_crypto_thread_native_clean(handle); } #else ossl_inline uint64_t ossl_get_avail_threads(OSSL_LIB_CTX *ctx) { return 0; } void *ossl_crypto_thread_start(OSSL_LIB_CTX *ctx, CRYPTO_THREAD_ROUTINE start, void *data) { return NULL; } int ossl_crypto_thread_join(void *vhandle, CRYPTO_THREAD_RETVAL *retval) { return 0; } int ossl_crypto_thread_clean(void *vhandle) { return 0; } #endif void *ossl_threads_ctx_new(OSSL_LIB_CTX *ctx) { struct openssl_threads_st *t = OPENSSL_zalloc(sizeof(*t)); if (t == NULL) return NULL; t->lock = ossl_crypto_mutex_new(); t->cond_finished = ossl_crypto_condvar_new(); if (t->lock == NULL || t->cond_finished == NULL) goto fail; return t; fail: ossl_threads_ctx_free((void *)t); return NULL; } void ossl_threads_ctx_free(void *vdata) { OSSL_LIB_CTX_THREADS *t = (OSSL_LIB_CTX_THREADS *) vdata; if (t == NULL) return; ossl_crypto_mutex_free(&t->lock); ossl_crypto_condvar_free(&t->cond_finished); OPENSSL_free(t); }
3,739
22.670886
80
c
openssl
openssl-master/crypto/thread/arch/thread_posix.c
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <internal/thread_arch.h> #if defined(OPENSSL_THREADS_POSIX) # define _GNU_SOURCE # include <errno.h> # include <sys/types.h> # include <unistd.h> static void *thread_start_thunk(void *vthread) { CRYPTO_THREAD *thread; CRYPTO_THREAD_RETVAL ret; thread = (CRYPTO_THREAD *)vthread; ret = thread->routine(thread->data); ossl_crypto_mutex_lock(thread->statelock); CRYPTO_THREAD_SET_STATE(thread, CRYPTO_THREAD_FINISHED); thread->retval = ret; ossl_crypto_condvar_broadcast(thread->condvar); ossl_crypto_mutex_unlock(thread->statelock); return NULL; } int ossl_crypto_thread_native_spawn(CRYPTO_THREAD *thread) { int ret; pthread_attr_t attr; pthread_t *handle; handle = OPENSSL_zalloc(sizeof(*handle)); if (handle == NULL) goto fail; pthread_attr_init(&attr); if (!thread->joinable) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); ret = pthread_create(handle, &attr, thread_start_thunk, thread); pthread_attr_destroy(&attr); if (ret != 0) goto fail; thread->handle = handle; return 1; fail: thread->handle = NULL; OPENSSL_free(handle); return 0; } int ossl_crypto_thread_native_perform_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval) { void *thread_retval; pthread_t *handle; if (thread == NULL || thread->handle == NULL) return 0; handle = (pthread_t *) thread->handle; if (pthread_join(*handle, &thread_retval) != 0) return 0; /* * Join return value may be non-NULL when the thread has been cancelled, * as indicated by thread_retval set to PTHREAD_CANCELLED. */ if (thread_retval != NULL) return 0; return 1; } int ossl_crypto_thread_native_exit(void) { pthread_exit(NULL); return 1; } int ossl_crypto_thread_native_is_self(CRYPTO_THREAD *thread) { return pthread_equal(*(pthread_t *)thread->handle, pthread_self()); } CRYPTO_MUTEX *ossl_crypto_mutex_new(void) { pthread_mutex_t *mutex; if ((mutex = OPENSSL_zalloc(sizeof(*mutex))) == NULL) return NULL; if (pthread_mutex_init(mutex, NULL) != 0) { OPENSSL_free(mutex); return NULL; } return (CRYPTO_MUTEX *)mutex; } int ossl_crypto_mutex_try_lock(CRYPTO_MUTEX *mutex) { pthread_mutex_t *mutex_p; mutex_p = (pthread_mutex_t *)mutex; if (pthread_mutex_trylock(mutex_p) == EBUSY) return 0; return 1; } void ossl_crypto_mutex_lock(CRYPTO_MUTEX *mutex) { pthread_mutex_t *mutex_p; mutex_p = (pthread_mutex_t *)mutex; pthread_mutex_lock(mutex_p); } void ossl_crypto_mutex_unlock(CRYPTO_MUTEX *mutex) { pthread_mutex_t *mutex_p; mutex_p = (pthread_mutex_t *)mutex; pthread_mutex_unlock(mutex_p); } void ossl_crypto_mutex_free(CRYPTO_MUTEX **mutex) { pthread_mutex_t **mutex_p; if (mutex == NULL) return; mutex_p = (pthread_mutex_t **)mutex; if (*mutex_p != NULL) pthread_mutex_destroy(*mutex_p); OPENSSL_free(*mutex_p); *mutex = NULL; } CRYPTO_CONDVAR *ossl_crypto_condvar_new(void) { pthread_cond_t *cv_p; if ((cv_p = OPENSSL_zalloc(sizeof(*cv_p))) == NULL) return NULL; if (pthread_cond_init(cv_p, NULL) != 0) { OPENSSL_free(cv_p); return NULL; } return (CRYPTO_CONDVAR *) cv_p; } void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex) { pthread_cond_t *cv_p; pthread_mutex_t *mutex_p; cv_p = (pthread_cond_t *)cv; mutex_p = (pthread_mutex_t *)mutex; pthread_cond_wait(cv_p, mutex_p); } void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex, OSSL_TIME deadline) { pthread_cond_t *cv_p = (pthread_cond_t *)cv; pthread_mutex_t *mutex_p = (pthread_mutex_t *)mutex; if (ossl_time_is_infinite(deadline)) { /* * No deadline. Some pthread implementations allow * pthread_cond_timedwait to work the same as pthread_cond_wait when * abstime is NULL, but it is unclear whether this is POSIXly correct. */ pthread_cond_wait(cv_p, mutex_p); } else { struct timespec deadline_ts; deadline_ts.tv_sec = ossl_time2seconds(deadline); deadline_ts.tv_nsec = (ossl_time2ticks(deadline) % OSSL_TIME_SECOND) / OSSL_TIME_NS; pthread_cond_timedwait(cv_p, mutex_p, &deadline_ts); } } void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv) { pthread_cond_t *cv_p; cv_p = (pthread_cond_t *)cv; pthread_cond_broadcast(cv_p); } void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv) { pthread_cond_t *cv_p; cv_p = (pthread_cond_t *)cv; pthread_cond_signal(cv_p); } void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv) { pthread_cond_t **cv_p; if (cv == NULL) return; cv_p = (pthread_cond_t **)cv; if (*cv_p != NULL) pthread_cond_destroy(*cv_p); OPENSSL_free(*cv_p); *cv_p = NULL; } #endif
5,387
22.426087
95
c
openssl
openssl-master/crypto/thread/arch/thread_win.c
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <internal/thread_arch.h> #if defined(OPENSSL_THREADS_WINNT) # include <process.h> # include <windows.h> static unsigned __stdcall thread_start_thunk(LPVOID vthread) { CRYPTO_THREAD *thread; CRYPTO_THREAD_RETVAL ret; thread = (CRYPTO_THREAD *)vthread; thread->thread_id = GetCurrentThreadId(); ret = thread->routine(thread->data); ossl_crypto_mutex_lock(thread->statelock); CRYPTO_THREAD_SET_STATE(thread, CRYPTO_THREAD_FINISHED); thread->retval = ret; ossl_crypto_condvar_signal(thread->condvar); ossl_crypto_mutex_unlock(thread->statelock); return 0; } int ossl_crypto_thread_native_spawn(CRYPTO_THREAD *thread) { HANDLE *handle; handle = OPENSSL_zalloc(sizeof(*handle)); if (handle == NULL) goto fail; *handle = (HANDLE)_beginthreadex(NULL, 0, &thread_start_thunk, thread, 0, NULL); if (*handle == NULL) goto fail; thread->handle = handle; return 1; fail: thread->handle = NULL; OPENSSL_free(handle); return 0; } int ossl_crypto_thread_native_perform_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval) { DWORD thread_retval; HANDLE *handle; if (thread == NULL || thread->handle == NULL) return 0; handle = (HANDLE *) thread->handle; if (WaitForSingleObject(*handle, INFINITE) != WAIT_OBJECT_0) return 0; if (GetExitCodeThread(*handle, &thread_retval) == 0) return 0; /* * GetExitCodeThread call followed by this check is to make sure that * the thread exited properly. In particular, thread_retval may be * non-zero when exited via explicit ExitThread/TerminateThread or * if the thread is still active (returns STILL_ACTIVE (259)). */ if (thread_retval != 0) return 0; if (CloseHandle(*handle) == 0) return 0; return 1; } int ossl_crypto_thread_native_exit(void) { _endthreadex(0); return 1; } int ossl_crypto_thread_native_is_self(CRYPTO_THREAD *thread) { return thread->thread_id == GetCurrentThreadId(); } CRYPTO_MUTEX *ossl_crypto_mutex_new(void) { CRITICAL_SECTION *mutex; if ((mutex = OPENSSL_zalloc(sizeof(*mutex))) == NULL) return NULL; InitializeCriticalSection(mutex); return (CRYPTO_MUTEX *)mutex; } void ossl_crypto_mutex_lock(CRYPTO_MUTEX *mutex) { CRITICAL_SECTION *mutex_p; mutex_p = (CRITICAL_SECTION *)mutex; EnterCriticalSection(mutex_p); } int ossl_crypto_mutex_try_lock(CRYPTO_MUTEX *mutex) { CRITICAL_SECTION *mutex_p; mutex_p = (CRITICAL_SECTION *)mutex; if (TryEnterCriticalSection(mutex_p)) return 1; return 0; } void ossl_crypto_mutex_unlock(CRYPTO_MUTEX *mutex) { CRITICAL_SECTION *mutex_p; mutex_p = (CRITICAL_SECTION *)mutex; LeaveCriticalSection(mutex_p); } void ossl_crypto_mutex_free(CRYPTO_MUTEX **mutex) { CRITICAL_SECTION **mutex_p; mutex_p = (CRITICAL_SECTION **)mutex; if (*mutex_p != NULL) DeleteCriticalSection(*mutex_p); OPENSSL_free(*mutex_p); *mutex = NULL; } static int determine_timeout(OSSL_TIME deadline, DWORD *w_timeout_p) { OSSL_TIME now, delta; uint64_t ms; if (ossl_time_is_infinite(deadline)) { *w_timeout_p = INFINITE; return 1; } now = ossl_time_now(); delta = ossl_time_subtract(deadline, now); if (ossl_time_is_zero(delta)) return 0; ms = ossl_time2ms(delta); /* * Amount of time we want to wait is too long for the 32-bit argument to * the Win32 API, so just wait as long as possible. */ if (ms > (uint64_t)(INFINITE - 1)) *w_timeout_p = INFINITE - 1; else *w_timeout_p = (DWORD)ms; return 1; } # if defined(OPENSSL_THREADS_WINNT_LEGACY) CRYPTO_CONDVAR *ossl_crypto_condvar_new(void) { HANDLE h; if ((h = CreateEventA(NULL, FALSE, FALSE, NULL)) == NULL) return NULL; return (CRYPTO_CONDVAR *)h; } void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex) { ossl_crypto_mutex_unlock(mutex); WaitForSingleObject((HANDLE)cv, INFINITE); ossl_crypto_mutex_lock(mutex); } void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex, OSSL_TIME deadline) { DWORD timeout; if (!determine_timeout(deadline, &timeout)) timeout = 1; ossl_crypto_mutex_unlock(mutex); WaitForSingleObject((HANDLE)cv, timeout); ossl_crypto_mutex_lock(mutex); } void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv) { /* Not supported */ } void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv) { HANDLE *cv_p = (HANDLE *)cv; SetEvent(cv_p); } void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv) { HANDLE **cv_p; cv_p = (HANDLE **)cv; if (*cv_p != NULL) CloseHandle(*cv_p); *cv_p = NULL; } # else CRYPTO_CONDVAR *ossl_crypto_condvar_new(void) { CONDITION_VARIABLE *cv_p; if ((cv_p = OPENSSL_zalloc(sizeof(*cv_p))) == NULL) return NULL; InitializeConditionVariable(cv_p); return (CRYPTO_CONDVAR *)cv_p; } void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex) { CONDITION_VARIABLE *cv_p; CRITICAL_SECTION *mutex_p; cv_p = (CONDITION_VARIABLE *)cv; mutex_p = (CRITICAL_SECTION *)mutex; SleepConditionVariableCS(cv_p, mutex_p, INFINITE); } void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex, OSSL_TIME deadline) { DWORD timeout; CONDITION_VARIABLE *cv_p = (CONDITION_VARIABLE *)cv; CRITICAL_SECTION *mutex_p = (CRITICAL_SECTION *)mutex; if (!determine_timeout(deadline, &timeout)) timeout = 1; SleepConditionVariableCS(cv_p, mutex_p, timeout); } void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv) { CONDITION_VARIABLE *cv_p; cv_p = (CONDITION_VARIABLE *)cv; WakeAllConditionVariable(cv_p); } void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv) { CONDITION_VARIABLE *cv_p; cv_p = (CONDITION_VARIABLE *)cv; WakeConditionVariable(cv_p); } void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv) { CONDITION_VARIABLE **cv_p; cv_p = (CONDITION_VARIABLE **)cv; OPENSSL_free(*cv_p); *cv_p = NULL; } # endif void ossl_crypto_mem_barrier(void) { MemoryBarrier(); } #endif
6,686
21.439597
95
c
openssl
openssl-master/crypto/ts/ts_asn1.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/ts.h> #include <openssl/err.h> #include <openssl/asn1t.h> #include "ts_local.h" ASN1_SEQUENCE(TS_MSG_IMPRINT) = { ASN1_SIMPLE(TS_MSG_IMPRINT, hash_algo, X509_ALGOR), ASN1_SIMPLE(TS_MSG_IMPRINT, hashed_msg, ASN1_OCTET_STRING) } static_ASN1_SEQUENCE_END(TS_MSG_IMPRINT) IMPLEMENT_ASN1_FUNCTIONS(TS_MSG_IMPRINT) IMPLEMENT_ASN1_DUP_FUNCTION(TS_MSG_IMPRINT) TS_MSG_IMPRINT *d2i_TS_MSG_IMPRINT_bio(BIO *bp, TS_MSG_IMPRINT **a) { return ASN1_d2i_bio_of(TS_MSG_IMPRINT, TS_MSG_IMPRINT_new, d2i_TS_MSG_IMPRINT, bp, a); } int i2d_TS_MSG_IMPRINT_bio(BIO *bp, const TS_MSG_IMPRINT *a) { return ASN1_i2d_bio_of(TS_MSG_IMPRINT, i2d_TS_MSG_IMPRINT, bp, a); } #ifndef OPENSSL_NO_STDIO TS_MSG_IMPRINT *d2i_TS_MSG_IMPRINT_fp(FILE *fp, TS_MSG_IMPRINT **a) { return ASN1_d2i_fp_of(TS_MSG_IMPRINT, TS_MSG_IMPRINT_new, d2i_TS_MSG_IMPRINT, fp, a); } int i2d_TS_MSG_IMPRINT_fp(FILE *fp, const TS_MSG_IMPRINT *a) { return ASN1_i2d_fp_of(TS_MSG_IMPRINT, i2d_TS_MSG_IMPRINT, fp, a); } #endif ASN1_SEQUENCE(TS_REQ) = { ASN1_SIMPLE(TS_REQ, version, ASN1_INTEGER), ASN1_SIMPLE(TS_REQ, msg_imprint, TS_MSG_IMPRINT), ASN1_OPT(TS_REQ, policy_id, ASN1_OBJECT), ASN1_OPT(TS_REQ, nonce, ASN1_INTEGER), ASN1_OPT(TS_REQ, cert_req, ASN1_FBOOLEAN), ASN1_IMP_SEQUENCE_OF_OPT(TS_REQ, extensions, X509_EXTENSION, 0) } static_ASN1_SEQUENCE_END(TS_REQ) IMPLEMENT_ASN1_FUNCTIONS(TS_REQ) IMPLEMENT_ASN1_DUP_FUNCTION(TS_REQ) TS_REQ *d2i_TS_REQ_bio(BIO *bp, TS_REQ **a) { return ASN1_d2i_bio_of(TS_REQ, TS_REQ_new, d2i_TS_REQ, bp, a); } int i2d_TS_REQ_bio(BIO *bp, const TS_REQ *a) { return ASN1_i2d_bio_of(TS_REQ, i2d_TS_REQ, bp, a); } #ifndef OPENSSL_NO_STDIO TS_REQ *d2i_TS_REQ_fp(FILE *fp, TS_REQ **a) { return ASN1_d2i_fp_of(TS_REQ, TS_REQ_new, d2i_TS_REQ, fp, a); } int i2d_TS_REQ_fp(FILE *fp, const TS_REQ *a) { return ASN1_i2d_fp_of(TS_REQ, i2d_TS_REQ, fp, a); } #endif ASN1_SEQUENCE(TS_ACCURACY) = { ASN1_OPT(TS_ACCURACY, seconds, ASN1_INTEGER), ASN1_IMP_OPT(TS_ACCURACY, millis, ASN1_INTEGER, 0), ASN1_IMP_OPT(TS_ACCURACY, micros, ASN1_INTEGER, 1) } static_ASN1_SEQUENCE_END(TS_ACCURACY) IMPLEMENT_ASN1_FUNCTIONS(TS_ACCURACY) IMPLEMENT_ASN1_DUP_FUNCTION(TS_ACCURACY) ASN1_SEQUENCE(TS_TST_INFO) = { ASN1_SIMPLE(TS_TST_INFO, version, ASN1_INTEGER), ASN1_SIMPLE(TS_TST_INFO, policy_id, ASN1_OBJECT), ASN1_SIMPLE(TS_TST_INFO, msg_imprint, TS_MSG_IMPRINT), ASN1_SIMPLE(TS_TST_INFO, serial, ASN1_INTEGER), ASN1_SIMPLE(TS_TST_INFO, time, ASN1_GENERALIZEDTIME), ASN1_OPT(TS_TST_INFO, accuracy, TS_ACCURACY), ASN1_OPT(TS_TST_INFO, ordering, ASN1_FBOOLEAN), ASN1_OPT(TS_TST_INFO, nonce, ASN1_INTEGER), ASN1_EXP_OPT(TS_TST_INFO, tsa, GENERAL_NAME, 0), ASN1_IMP_SEQUENCE_OF_OPT(TS_TST_INFO, extensions, X509_EXTENSION, 1) } static_ASN1_SEQUENCE_END(TS_TST_INFO) IMPLEMENT_ASN1_FUNCTIONS(TS_TST_INFO) IMPLEMENT_ASN1_DUP_FUNCTION(TS_TST_INFO) TS_TST_INFO *d2i_TS_TST_INFO_bio(BIO *bp, TS_TST_INFO **a) { return ASN1_d2i_bio_of(TS_TST_INFO, TS_TST_INFO_new, d2i_TS_TST_INFO, bp, a); } int i2d_TS_TST_INFO_bio(BIO *bp, const TS_TST_INFO *a) { return ASN1_i2d_bio_of(TS_TST_INFO, i2d_TS_TST_INFO, bp, a); } #ifndef OPENSSL_NO_STDIO TS_TST_INFO *d2i_TS_TST_INFO_fp(FILE *fp, TS_TST_INFO **a) { return ASN1_d2i_fp_of(TS_TST_INFO, TS_TST_INFO_new, d2i_TS_TST_INFO, fp, a); } int i2d_TS_TST_INFO_fp(FILE *fp, const TS_TST_INFO *a) { return ASN1_i2d_fp_of(TS_TST_INFO, i2d_TS_TST_INFO, fp, a); } #endif ASN1_SEQUENCE(TS_STATUS_INFO) = { ASN1_SIMPLE(TS_STATUS_INFO, status, ASN1_INTEGER), ASN1_SEQUENCE_OF_OPT(TS_STATUS_INFO, text, ASN1_UTF8STRING), ASN1_OPT(TS_STATUS_INFO, failure_info, ASN1_BIT_STRING) } static_ASN1_SEQUENCE_END(TS_STATUS_INFO) IMPLEMENT_ASN1_FUNCTIONS(TS_STATUS_INFO) IMPLEMENT_ASN1_DUP_FUNCTION(TS_STATUS_INFO) static int ts_resp_set_tst_info(TS_RESP *a) { long status; status = ASN1_INTEGER_get(a->status_info->status); if (a->token) { if (status != 0 && status != 1) { ERR_raise(ERR_LIB_TS, TS_R_TOKEN_PRESENT); return 0; } TS_TST_INFO_free(a->tst_info); a->tst_info = PKCS7_to_TS_TST_INFO(a->token); if (!a->tst_info) { ERR_raise(ERR_LIB_TS, TS_R_PKCS7_TO_TS_TST_INFO_FAILED); return 0; } } else if (status == 0 || status == 1) { ERR_raise(ERR_LIB_TS, TS_R_TOKEN_NOT_PRESENT); return 0; } return 1; } static int ts_resp_cb(int op, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { TS_RESP *ts_resp = (TS_RESP *)*pval; if (op == ASN1_OP_NEW_POST) { ts_resp->tst_info = NULL; } else if (op == ASN1_OP_FREE_POST) { TS_TST_INFO_free(ts_resp->tst_info); } else if (op == ASN1_OP_D2I_POST) { if (ts_resp_set_tst_info(ts_resp) == 0) return 0; } return 1; } ASN1_SEQUENCE_cb(TS_RESP, ts_resp_cb) = { ASN1_SIMPLE(TS_RESP, status_info, TS_STATUS_INFO), ASN1_OPT(TS_RESP, token, PKCS7), } static_ASN1_SEQUENCE_END_cb(TS_RESP, TS_RESP) IMPLEMENT_ASN1_FUNCTIONS(TS_RESP) IMPLEMENT_ASN1_DUP_FUNCTION(TS_RESP) TS_RESP *d2i_TS_RESP_bio(BIO *bp, TS_RESP **a) { return ASN1_d2i_bio_of(TS_RESP, TS_RESP_new, d2i_TS_RESP, bp, a); } int i2d_TS_RESP_bio(BIO *bp, const TS_RESP *a) { return ASN1_i2d_bio_of(TS_RESP, i2d_TS_RESP, bp, a); } #ifndef OPENSSL_NO_STDIO TS_RESP *d2i_TS_RESP_fp(FILE *fp, TS_RESP **a) { return ASN1_d2i_fp_of(TS_RESP, TS_RESP_new, d2i_TS_RESP, fp, a); } int i2d_TS_RESP_fp(FILE *fp, const TS_RESP *a) { return ASN1_i2d_fp_of(TS_RESP, i2d_TS_RESP, fp, a); } #endif /* Getting encapsulated TS_TST_INFO object from PKCS7. */ TS_TST_INFO *PKCS7_to_TS_TST_INFO(PKCS7 *token) { PKCS7_SIGNED *pkcs7_signed; PKCS7 *enveloped; ASN1_TYPE *tst_info_wrapper; ASN1_OCTET_STRING *tst_info_der; const unsigned char *p; if (!PKCS7_type_is_signed(token)) { ERR_raise(ERR_LIB_TS, TS_R_BAD_PKCS7_TYPE); return NULL; } if (PKCS7_get_detached(token)) { ERR_raise(ERR_LIB_TS, TS_R_DETACHED_CONTENT); return NULL; } pkcs7_signed = token->d.sign; enveloped = pkcs7_signed->contents; if (OBJ_obj2nid(enveloped->type) != NID_id_smime_ct_TSTInfo) { ERR_raise(ERR_LIB_TS, TS_R_BAD_PKCS7_TYPE); return NULL; } tst_info_wrapper = enveloped->d.other; if (tst_info_wrapper->type != V_ASN1_OCTET_STRING) { ERR_raise(ERR_LIB_TS, TS_R_BAD_TYPE); return NULL; } tst_info_der = tst_info_wrapper->value.octet_string; p = tst_info_der->data; return d2i_TS_TST_INFO(NULL, &p, tst_info_der->length); }
7,253
29.868085
77
c
openssl
openssl-master/crypto/ts/ts_conf.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <string.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include <openssl/pem.h> #include <openssl/engine.h> #include <openssl/ts.h> #include <openssl/conf_api.h> /* Macro definitions for the configuration file. */ #define BASE_SECTION "tsa" #define ENV_DEFAULT_TSA "default_tsa" #define ENV_SERIAL "serial" #define ENV_CRYPTO_DEVICE "crypto_device" #define ENV_SIGNER_CERT "signer_cert" #define ENV_CERTS "certs" #define ENV_SIGNER_KEY "signer_key" #define ENV_SIGNER_DIGEST "signer_digest" #define ENV_DEFAULT_POLICY "default_policy" #define ENV_OTHER_POLICIES "other_policies" #define ENV_DIGESTS "digests" #define ENV_ACCURACY "accuracy" #define ENV_ORDERING "ordering" #define ENV_TSA_NAME "tsa_name" #define ENV_ESS_CERT_ID_CHAIN "ess_cert_id_chain" #define ENV_VALUE_SECS "secs" #define ENV_VALUE_MILLISECS "millisecs" #define ENV_VALUE_MICROSECS "microsecs" #define ENV_CLOCK_PRECISION_DIGITS "clock_precision_digits" #define ENV_VALUE_YES "yes" #define ENV_VALUE_NO "no" #define ENV_ESS_CERT_ID_ALG "ess_cert_id_alg" /* Function definitions for certificate and key loading. */ X509 *TS_CONF_load_cert(const char *file) { BIO *cert = NULL; X509 *x = NULL; if ((cert = BIO_new_file(file, "r")) == NULL) goto end; x = PEM_read_bio_X509_AUX(cert, NULL, NULL, NULL); end: if (x == NULL) ERR_raise(ERR_LIB_TS, TS_R_CANNOT_LOAD_CERT); BIO_free(cert); return x; } STACK_OF(X509) *TS_CONF_load_certs(const char *file) { BIO *certs = NULL; STACK_OF(X509) *othercerts = NULL; STACK_OF(X509_INFO) *allcerts = NULL; int i; if ((certs = BIO_new_file(file, "r")) == NULL) goto end; if ((othercerts = sk_X509_new_null()) == NULL) goto end; allcerts = PEM_X509_INFO_read_bio(certs, NULL, NULL, NULL); for (i = 0; i < sk_X509_INFO_num(allcerts); i++) { X509_INFO *xi = sk_X509_INFO_value(allcerts, i); if (xi->x509 != NULL) { if (!X509_add_cert(othercerts, xi->x509, X509_ADD_FLAG_DEFAULT)) { OSSL_STACK_OF_X509_free(othercerts); othercerts = NULL; goto end; } xi->x509 = NULL; } } end: if (othercerts == NULL) ERR_raise(ERR_LIB_TS, TS_R_CANNOT_LOAD_CERT); sk_X509_INFO_pop_free(allcerts, X509_INFO_free); BIO_free(certs); return othercerts; } EVP_PKEY *TS_CONF_load_key(const char *file, const char *pass) { BIO *key = NULL; EVP_PKEY *pkey = NULL; if ((key = BIO_new_file(file, "r")) == NULL) goto end; pkey = PEM_read_bio_PrivateKey(key, NULL, NULL, (char *)pass); end: if (pkey == NULL) ERR_raise(ERR_LIB_TS, TS_R_CANNOT_LOAD_KEY); BIO_free(key); return pkey; } /* Function definitions for handling configuration options. */ static void ts_CONF_lookup_fail(const char *name, const char *tag) { ERR_raise_data(ERR_LIB_TS, TS_R_VAR_LOOKUP_FAILURE, "%s::%s", name, tag); } static void ts_CONF_invalid(const char *name, const char *tag) { ERR_raise_data(ERR_LIB_TS, TS_R_VAR_BAD_VALUE, "%s::%s", name, tag); } const char *TS_CONF_get_tsa_section(CONF *conf, const char *section) { if (!section) { section = NCONF_get_string(conf, BASE_SECTION, ENV_DEFAULT_TSA); if (!section) ts_CONF_lookup_fail(BASE_SECTION, ENV_DEFAULT_TSA); } return section; } int TS_CONF_set_serial(CONF *conf, const char *section, TS_serial_cb cb, TS_RESP_CTX *ctx) { int ret = 0; char *serial = NCONF_get_string(conf, section, ENV_SERIAL); if (!serial) { ts_CONF_lookup_fail(section, ENV_SERIAL); goto err; } TS_RESP_CTX_set_serial_cb(ctx, cb, serial); ret = 1; err: return ret; } #ifndef OPENSSL_NO_ENGINE int TS_CONF_set_crypto_device(CONF *conf, const char *section, const char *device) { int ret = 0; if (device == NULL) device = NCONF_get_string(conf, section, ENV_CRYPTO_DEVICE); if (device && !TS_CONF_set_default_engine(device)) { ts_CONF_invalid(section, ENV_CRYPTO_DEVICE); goto err; } ret = 1; err: return ret; } int TS_CONF_set_default_engine(const char *name) { ENGINE *e = NULL; int ret = 0; if (strcmp(name, "builtin") == 0) return 1; if ((e = ENGINE_by_id(name)) == NULL) goto err; if (strcmp(name, "chil") == 0) ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0); if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) goto err; ret = 1; err: if (!ret) ERR_raise_data(ERR_LIB_TS, TS_R_COULD_NOT_SET_ENGINE, "engine:%s", name); ENGINE_free(e); return ret; } #endif int TS_CONF_set_signer_cert(CONF *conf, const char *section, const char *cert, TS_RESP_CTX *ctx) { int ret = 0; X509 *cert_obj = NULL; if (cert == NULL) { cert = NCONF_get_string(conf, section, ENV_SIGNER_CERT); if (cert == NULL) { ts_CONF_lookup_fail(section, ENV_SIGNER_CERT); goto err; } } if ((cert_obj = TS_CONF_load_cert(cert)) == NULL) goto err; if (!TS_RESP_CTX_set_signer_cert(ctx, cert_obj)) goto err; ret = 1; err: X509_free(cert_obj); return ret; } int TS_CONF_set_certs(CONF *conf, const char *section, const char *certs, TS_RESP_CTX *ctx) { int ret = 0; STACK_OF(X509) *certs_obj = NULL; if (certs == NULL) { /* Certificate chain is optional. */ if ((certs = NCONF_get_string(conf, section, ENV_CERTS)) == NULL) goto end; } if ((certs_obj = TS_CONF_load_certs(certs)) == NULL) goto err; if (!TS_RESP_CTX_set_certs(ctx, certs_obj)) goto err; end: ret = 1; err: OSSL_STACK_OF_X509_free(certs_obj); return ret; } int TS_CONF_set_signer_key(CONF *conf, const char *section, const char *key, const char *pass, TS_RESP_CTX *ctx) { int ret = 0; EVP_PKEY *key_obj = NULL; if (!key) key = NCONF_get_string(conf, section, ENV_SIGNER_KEY); if (!key) { ts_CONF_lookup_fail(section, ENV_SIGNER_KEY); goto err; } if ((key_obj = TS_CONF_load_key(key, pass)) == NULL) goto err; if (!TS_RESP_CTX_set_signer_key(ctx, key_obj)) goto err; ret = 1; err: EVP_PKEY_free(key_obj); return ret; } int TS_CONF_set_signer_digest(CONF *conf, const char *section, const char *md, TS_RESP_CTX *ctx) { int ret = 0; const EVP_MD *sign_md = NULL; if (md == NULL) md = NCONF_get_string(conf, section, ENV_SIGNER_DIGEST); if (md == NULL) { ts_CONF_lookup_fail(section, ENV_SIGNER_DIGEST); goto err; } sign_md = EVP_get_digestbyname(md); if (sign_md == NULL) { ts_CONF_invalid(section, ENV_SIGNER_DIGEST); goto err; } if (!TS_RESP_CTX_set_signer_digest(ctx, sign_md)) goto err; ret = 1; err: return ret; } int TS_CONF_set_def_policy(CONF *conf, const char *section, const char *policy, TS_RESP_CTX *ctx) { int ret = 0; ASN1_OBJECT *policy_obj = NULL; if (policy == NULL) policy = NCONF_get_string(conf, section, ENV_DEFAULT_POLICY); if (policy == NULL) { ts_CONF_lookup_fail(section, ENV_DEFAULT_POLICY); goto err; } if ((policy_obj = OBJ_txt2obj(policy, 0)) == NULL) { ts_CONF_invalid(section, ENV_DEFAULT_POLICY); goto err; } if (!TS_RESP_CTX_set_def_policy(ctx, policy_obj)) goto err; ret = 1; err: ASN1_OBJECT_free(policy_obj); return ret; } int TS_CONF_set_policies(CONF *conf, const char *section, TS_RESP_CTX *ctx) { int ret = 0; int i; STACK_OF(CONF_VALUE) *list = NULL; char *policies = NCONF_get_string(conf, section, ENV_OTHER_POLICIES); /* If no other policy is specified, that's fine. */ if (policies && (list = X509V3_parse_list(policies)) == NULL) { ts_CONF_invalid(section, ENV_OTHER_POLICIES); goto err; } for (i = 0; i < sk_CONF_VALUE_num(list); ++i) { CONF_VALUE *val = sk_CONF_VALUE_value(list, i); const char *extval = val->value ? val->value : val->name; ASN1_OBJECT *objtmp; if ((objtmp = OBJ_txt2obj(extval, 0)) == NULL) { ts_CONF_invalid(section, ENV_OTHER_POLICIES); goto err; } if (!TS_RESP_CTX_add_policy(ctx, objtmp)) goto err; ASN1_OBJECT_free(objtmp); } ret = 1; err: sk_CONF_VALUE_pop_free(list, X509V3_conf_free); return ret; } int TS_CONF_set_digests(CONF *conf, const char *section, TS_RESP_CTX *ctx) { int ret = 0; int i; STACK_OF(CONF_VALUE) *list = NULL; char *digests = NCONF_get_string(conf, section, ENV_DIGESTS); if (digests == NULL) { ts_CONF_lookup_fail(section, ENV_DIGESTS); goto err; } if ((list = X509V3_parse_list(digests)) == NULL) { ts_CONF_invalid(section, ENV_DIGESTS); goto err; } if (sk_CONF_VALUE_num(list) == 0) { ts_CONF_invalid(section, ENV_DIGESTS); goto err; } for (i = 0; i < sk_CONF_VALUE_num(list); ++i) { CONF_VALUE *val = sk_CONF_VALUE_value(list, i); const char *extval = val->value ? val->value : val->name; const EVP_MD *md; if ((md = EVP_get_digestbyname(extval)) == NULL) { ts_CONF_invalid(section, ENV_DIGESTS); goto err; } if (!TS_RESP_CTX_add_md(ctx, md)) goto err; } ret = 1; err: sk_CONF_VALUE_pop_free(list, X509V3_conf_free); return ret; } int TS_CONF_set_accuracy(CONF *conf, const char *section, TS_RESP_CTX *ctx) { int ret = 0; int i; int secs = 0, millis = 0, micros = 0; STACK_OF(CONF_VALUE) *list = NULL; char *accuracy = NCONF_get_string(conf, section, ENV_ACCURACY); if (accuracy && (list = X509V3_parse_list(accuracy)) == NULL) { ts_CONF_invalid(section, ENV_ACCURACY); goto err; } for (i = 0; i < sk_CONF_VALUE_num(list); ++i) { CONF_VALUE *val = sk_CONF_VALUE_value(list, i); if (strcmp(val->name, ENV_VALUE_SECS) == 0) { if (val->value) secs = atoi(val->value); } else if (strcmp(val->name, ENV_VALUE_MILLISECS) == 0) { if (val->value) millis = atoi(val->value); } else if (strcmp(val->name, ENV_VALUE_MICROSECS) == 0) { if (val->value) micros = atoi(val->value); } else { ts_CONF_invalid(section, ENV_ACCURACY); goto err; } } if (!TS_RESP_CTX_set_accuracy(ctx, secs, millis, micros)) goto err; ret = 1; err: sk_CONF_VALUE_pop_free(list, X509V3_conf_free); return ret; } int TS_CONF_set_clock_precision_digits(const CONF *conf, const char *section, TS_RESP_CTX *ctx) { int ret = 0; long digits = 0; /* * If not specified, set the default value to 0, i.e. sec precision */ digits = _CONF_get_number(conf, section, ENV_CLOCK_PRECISION_DIGITS); if (digits < 0 || digits > TS_MAX_CLOCK_PRECISION_DIGITS) { ts_CONF_invalid(section, ENV_CLOCK_PRECISION_DIGITS); goto err; } if (!TS_RESP_CTX_set_clock_precision_digits(ctx, digits)) goto err; return 1; err: return ret; } static int ts_CONF_add_flag(CONF *conf, const char *section, const char *field, int flag, TS_RESP_CTX *ctx) { const char *value = NCONF_get_string(conf, section, field); if (value) { if (strcmp(value, ENV_VALUE_YES) == 0) TS_RESP_CTX_add_flags(ctx, flag); else if (strcmp(value, ENV_VALUE_NO) != 0) { ts_CONF_invalid(section, field); return 0; } } return 1; } int TS_CONF_set_ordering(CONF *conf, const char *section, TS_RESP_CTX *ctx) { return ts_CONF_add_flag(conf, section, ENV_ORDERING, TS_ORDERING, ctx); } int TS_CONF_set_tsa_name(CONF *conf, const char *section, TS_RESP_CTX *ctx) { return ts_CONF_add_flag(conf, section, ENV_TSA_NAME, TS_TSA_NAME, ctx); } int TS_CONF_set_ess_cert_id_chain(CONF *conf, const char *section, TS_RESP_CTX *ctx) { return ts_CONF_add_flag(conf, section, ENV_ESS_CERT_ID_CHAIN, TS_ESS_CERT_ID_CHAIN, ctx); } int TS_CONF_set_ess_cert_id_digest(CONF *conf, const char *section, TS_RESP_CTX *ctx) { int ret = 0; const EVP_MD *cert_md = NULL; const char *md = NCONF_get_string(conf, section, ENV_ESS_CERT_ID_ALG); if (md == NULL) md = "sha1"; cert_md = EVP_get_digestbyname(md); if (cert_md == NULL) { ts_CONF_invalid(section, ENV_ESS_CERT_ID_ALG); goto err; } if (!TS_RESP_CTX_set_ess_cert_id_digest(ctx, cert_md)) goto err; ret = 1; err: return ret; }
13,979
27.016032
78
c
openssl
openssl-master/crypto/ts/ts_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/tserr.h> #include "crypto/tserr.h" #ifndef OPENSSL_NO_TS # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA TS_str_reasons[] = { {ERR_PACK(ERR_LIB_TS, 0, TS_R_BAD_PKCS7_TYPE), "bad pkcs7 type"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_BAD_TYPE), "bad type"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_CANNOT_LOAD_CERT), "cannot load certificate"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_CANNOT_LOAD_KEY), "cannot load private key"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_COULD_NOT_SET_ENGINE), "could not set engine"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_COULD_NOT_SET_TIME), "could not set time"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_DETACHED_CONTENT), "detached content"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_ESS_ADD_SIGNING_CERT_ERROR), "ess add signing cert error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR), "ess add signing cert v2 error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_ESS_SIGNING_CERTIFICATE_ERROR), "ess signing certificate error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_INVALID_NULL_POINTER), "invalid null pointer"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE), "invalid signer certificate purpose"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_MESSAGE_IMPRINT_MISMATCH), "message imprint mismatch"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_NONCE_MISMATCH), "nonce mismatch"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_NONCE_NOT_RETURNED), "nonce not returned"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_NO_CONTENT), "no content"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_NO_TIME_STAMP_TOKEN), "no time stamp token"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_PKCS7_ADD_SIGNATURE_ERROR), "pkcs7 add signature error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR), "pkcs7 add signed attr error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_PKCS7_TO_TS_TST_INFO_FAILED), "pkcs7 to ts tst info failed"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_POLICY_MISMATCH), "policy mismatch"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), "private key does not match certificate"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_RESPONSE_SETUP_ERROR), "response setup error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_SIGNATURE_FAILURE), "signature failure"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_THERE_MUST_BE_ONE_SIGNER), "there must be one signer"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TIME_SYSCALL_ERROR), "time syscall error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TOKEN_NOT_PRESENT), "token not present"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TOKEN_PRESENT), "token present"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TSA_NAME_MISMATCH), "tsa name mismatch"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TSA_UNTRUSTED), "tsa untrusted"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TST_INFO_SETUP_ERROR), "tst info setup error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TS_DATASIGN), "ts datasign"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_UNACCEPTABLE_POLICY), "unacceptable policy"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_UNSUPPORTED_MD_ALGORITHM), "unsupported md algorithm"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_UNSUPPORTED_VERSION), "unsupported version"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_VAR_BAD_VALUE), "var bad value"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_VAR_LOOKUP_FAILURE), "cannot find config variable"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_WRONG_CONTENT_TYPE), "wrong content type"}, {0, NULL} }; # endif int ossl_err_load_TS_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(TS_str_reasons[0].error) == NULL) ERR_load_strings_const(TS_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
4,086
43.423913
80
c
openssl
openssl-master/crypto/ts/ts_lib.c
/* * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/bn.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/ts.h> #include "ts_local.h" int TS_ASN1_INTEGER_print_bio(BIO *bio, const ASN1_INTEGER *num) { BIGNUM *num_bn; int result = 0; char *hex; num_bn = ASN1_INTEGER_to_BN(num, NULL); if (num_bn == NULL) return -1; if ((hex = BN_bn2hex(num_bn))) { result = BIO_write(bio, "0x", 2) > 0; result = result && BIO_write(bio, hex, strlen(hex)) > 0; OPENSSL_free(hex); } BN_free(num_bn); return result; } int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) { char obj_txt[128]; OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); BIO_printf(bio, "%s\n", obj_txt); return 1; } int TS_ext_print_bio(BIO *bio, const STACK_OF(X509_EXTENSION) *extensions) { int i, critical, n; X509_EXTENSION *ex; ASN1_OBJECT *obj; BIO_printf(bio, "Extensions:\n"); n = X509v3_get_ext_count(extensions); for (i = 0; i < n; i++) { ex = X509v3_get_ext(extensions, i); obj = X509_EXTENSION_get_object(ex); if (i2a_ASN1_OBJECT(bio, obj) < 0) return 0; critical = X509_EXTENSION_get_critical(ex); BIO_printf(bio, ":%s\n", critical ? " critical" : ""); if (!X509V3_EXT_print(bio, ex, 0, 4)) { BIO_printf(bio, "%4s", ""); ASN1_STRING_print(bio, X509_EXTENSION_get_data(ex)); } BIO_write(bio, "\n", 1); } return 1; } int TS_X509_ALGOR_print_bio(BIO *bio, const X509_ALGOR *alg) { int i = OBJ_obj2nid(alg->algorithm); return BIO_printf(bio, "Hash Algorithm: %s\n", (i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i)); } int TS_MSG_IMPRINT_print_bio(BIO *bio, TS_MSG_IMPRINT *a) { ASN1_OCTET_STRING *msg; TS_X509_ALGOR_print_bio(bio, a->hash_algo); BIO_printf(bio, "Message data:\n"); msg = a->hashed_msg; BIO_dump_indent(bio, (const char *)ASN1_STRING_get0_data(msg), ASN1_STRING_length(msg), 4); return 1; }
2,474
25.612903
74
c
openssl
openssl-master/crypto/ts/ts_local.h
/* * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /*- * MessageImprint ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * hashedMessage OCTET STRING } */ struct TS_msg_imprint_st { X509_ALGOR *hash_algo; ASN1_OCTET_STRING *hashed_msg; }; /*- * TimeStampResp ::= SEQUENCE { * status PKIStatusInfo, * timeStampToken TimeStampToken OPTIONAL } */ struct TS_resp_st { TS_STATUS_INFO *status_info; PKCS7 *token; TS_TST_INFO *tst_info; }; /*- * TimeStampReq ::= SEQUENCE { * version INTEGER { v1(1) }, * messageImprint MessageImprint, * --a hash algorithm OID and the hash value of the data to be * --time-stamped * reqPolicy TSAPolicyId OPTIONAL, * nonce INTEGER OPTIONAL, * certReq BOOLEAN DEFAULT FALSE, * extensions [0] IMPLICIT Extensions OPTIONAL } */ struct TS_req_st { ASN1_INTEGER *version; TS_MSG_IMPRINT *msg_imprint; ASN1_OBJECT *policy_id; ASN1_INTEGER *nonce; ASN1_BOOLEAN cert_req; STACK_OF(X509_EXTENSION) *extensions; }; /*- * Accuracy ::= SEQUENCE { * seconds INTEGER OPTIONAL, * millis [0] INTEGER (1..999) OPTIONAL, * micros [1] INTEGER (1..999) OPTIONAL } */ struct TS_accuracy_st { ASN1_INTEGER *seconds; ASN1_INTEGER *millis; ASN1_INTEGER *micros; }; /*- * TSTInfo ::= SEQUENCE { * version INTEGER { v1(1) }, * policy TSAPolicyId, * messageImprint MessageImprint, * -- MUST have the same value as the similar field in * -- TimeStampReq * serialNumber INTEGER, * -- Time-Stamping users MUST be ready to accommodate integers * -- up to 160 bits. * genTime GeneralizedTime, * accuracy Accuracy OPTIONAL, * ordering BOOLEAN DEFAULT FALSE, * nonce INTEGER OPTIONAL, * -- MUST be present if the similar field was present * -- in TimeStampReq. In that case it MUST have the same value. * tsa [0] GeneralName OPTIONAL, * extensions [1] IMPLICIT Extensions OPTIONAL } */ struct TS_tst_info_st { ASN1_INTEGER *version; ASN1_OBJECT *policy_id; TS_MSG_IMPRINT *msg_imprint; ASN1_INTEGER *serial; ASN1_GENERALIZEDTIME *time; TS_ACCURACY *accuracy; ASN1_BOOLEAN ordering; ASN1_INTEGER *nonce; GENERAL_NAME *tsa; STACK_OF(X509_EXTENSION) *extensions; }; struct TS_status_info_st { ASN1_INTEGER *status; STACK_OF(ASN1_UTF8STRING) *text; ASN1_BIT_STRING *failure_info; }; struct TS_resp_ctx { X509 *signer_cert; EVP_PKEY *signer_key; const EVP_MD *signer_md; const EVP_MD *ess_cert_id_digest; STACK_OF(X509) *certs; /* Certs to include in signed data. */ STACK_OF(ASN1_OBJECT) *policies; /* Acceptable policies. */ ASN1_OBJECT *default_policy; /* It may appear in policies, too. */ STACK_OF(EVP_MD) *mds; /* Acceptable message digests. */ ASN1_INTEGER *seconds; /* accuracy, 0 means not specified. */ ASN1_INTEGER *millis; /* accuracy, 0 means not specified. */ ASN1_INTEGER *micros; /* accuracy, 0 means not specified. */ unsigned clock_precision_digits; /* fraction of seconds in timestamp * token. */ unsigned flags; /* Optional info, see values above. */ /* Callback functions. */ TS_serial_cb serial_cb; void *serial_cb_data; /* User data for serial_cb. */ TS_time_cb time_cb; void *time_cb_data; /* User data for time_cb. */ TS_extension_cb extension_cb; void *extension_cb_data; /* User data for extension_cb. */ /* These members are used only while creating the response. */ TS_REQ *request; TS_RESP *response; TS_TST_INFO *tst_info; OSSL_LIB_CTX *libctx; char *propq; }; struct TS_verify_ctx { /* Set this to the union of TS_VFY_... flags you want to carry out. */ unsigned flags; /* Must be set only with TS_VFY_SIGNATURE. certs is optional. */ X509_STORE *store; STACK_OF(X509) *certs; /* Must be set only with TS_VFY_POLICY. */ ASN1_OBJECT *policy; /* * Must be set only with TS_VFY_IMPRINT. If md_alg is NULL, the * algorithm from the response is used. */ X509_ALGOR *md_alg; unsigned char *imprint; unsigned imprint_len; /* Must be set only with TS_VFY_DATA. */ BIO *data; /* Must be set only with TS_VFY_TSA_NAME. */ ASN1_INTEGER *nonce; /* Must be set only with TS_VFY_TSA_NAME. */ GENERAL_NAME *tsa_name; };
5,321
33.784314
74
h
openssl
openssl-master/crypto/ts/ts_req_print.c
/* * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/bn.h> #include <openssl/x509v3.h> #include <openssl/ts.h> #include "ts_local.h" int TS_REQ_print_bio(BIO *bio, TS_REQ *a) { int v; ASN1_OBJECT *policy_id; if (a == NULL) return 0; v = TS_REQ_get_version(a); BIO_printf(bio, "Version: %d\n", v); TS_MSG_IMPRINT_print_bio(bio, a->msg_imprint); BIO_printf(bio, "Policy OID: "); policy_id = TS_REQ_get_policy_id(a); if (policy_id == NULL) BIO_printf(bio, "unspecified\n"); else TS_OBJ_print_bio(bio, policy_id); BIO_printf(bio, "Nonce: "); if (a->nonce == NULL) BIO_printf(bio, "unspecified"); else TS_ASN1_INTEGER_print_bio(bio, a->nonce); BIO_write(bio, "\n", 1); BIO_printf(bio, "Certificate required: %s\n", a->cert_req ? "yes" : "no"); TS_ext_print_bio(bio, a->extensions); return 1; }
1,302
24.057692
74
c
openssl
openssl-master/crypto/ts/ts_req_utils.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/x509v3.h> #include <openssl/ts.h> #include "ts_local.h" int TS_REQ_set_version(TS_REQ *a, long version) { return ASN1_INTEGER_set(a->version, version); } long TS_REQ_get_version(const TS_REQ *a) { return ASN1_INTEGER_get(a->version); } int TS_REQ_set_msg_imprint(TS_REQ *a, TS_MSG_IMPRINT *msg_imprint) { TS_MSG_IMPRINT *new_msg_imprint; if (a->msg_imprint == msg_imprint) return 1; new_msg_imprint = TS_MSG_IMPRINT_dup(msg_imprint); if (new_msg_imprint == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_TS_LIB); return 0; } TS_MSG_IMPRINT_free(a->msg_imprint); a->msg_imprint = new_msg_imprint; return 1; } TS_MSG_IMPRINT *TS_REQ_get_msg_imprint(TS_REQ *a) { return a->msg_imprint; } int TS_MSG_IMPRINT_set_algo(TS_MSG_IMPRINT *a, X509_ALGOR *alg) { X509_ALGOR *new_alg; if (a->hash_algo == alg) return 1; new_alg = X509_ALGOR_dup(alg); if (new_alg == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB); return 0; } X509_ALGOR_free(a->hash_algo); a->hash_algo = new_alg; return 1; } X509_ALGOR *TS_MSG_IMPRINT_get_algo(TS_MSG_IMPRINT *a) { return a->hash_algo; } int TS_MSG_IMPRINT_set_msg(TS_MSG_IMPRINT *a, unsigned char *d, int len) { return ASN1_OCTET_STRING_set(a->hashed_msg, d, len); } ASN1_OCTET_STRING *TS_MSG_IMPRINT_get_msg(TS_MSG_IMPRINT *a) { return a->hashed_msg; } int TS_REQ_set_policy_id(TS_REQ *a, const ASN1_OBJECT *policy) { ASN1_OBJECT *new_policy; if (a->policy_id == policy) return 1; new_policy = OBJ_dup(policy); if (new_policy == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_OBJ_LIB); return 0; } ASN1_OBJECT_free(a->policy_id); a->policy_id = new_policy; return 1; } ASN1_OBJECT *TS_REQ_get_policy_id(TS_REQ *a) { return a->policy_id; } int TS_REQ_set_nonce(TS_REQ *a, const ASN1_INTEGER *nonce) { ASN1_INTEGER *new_nonce; if (a->nonce == nonce) return 1; new_nonce = ASN1_INTEGER_dup(nonce); if (new_nonce == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB); return 0; } ASN1_INTEGER_free(a->nonce); a->nonce = new_nonce; return 1; } const ASN1_INTEGER *TS_REQ_get_nonce(const TS_REQ *a) { return a->nonce; } int TS_REQ_set_cert_req(TS_REQ *a, int cert_req) { a->cert_req = cert_req ? 0xFF : 0x00; return 1; } int TS_REQ_get_cert_req(const TS_REQ *a) { return a->cert_req ? 1 : 0; } STACK_OF(X509_EXTENSION) *TS_REQ_get_exts(TS_REQ *a) { return a->extensions; } void TS_REQ_ext_free(TS_REQ *a) { if (!a) return; sk_X509_EXTENSION_pop_free(a->extensions, X509_EXTENSION_free); a->extensions = NULL; } int TS_REQ_get_ext_count(TS_REQ *a) { return X509v3_get_ext_count(a->extensions); } int TS_REQ_get_ext_by_NID(TS_REQ *a, int nid, int lastpos) { return X509v3_get_ext_by_NID(a->extensions, nid, lastpos); } int TS_REQ_get_ext_by_OBJ(TS_REQ *a, const ASN1_OBJECT *obj, int lastpos) { return X509v3_get_ext_by_OBJ(a->extensions, obj, lastpos); } int TS_REQ_get_ext_by_critical(TS_REQ *a, int crit, int lastpos) { return X509v3_get_ext_by_critical(a->extensions, crit, lastpos); } X509_EXTENSION *TS_REQ_get_ext(TS_REQ *a, int loc) { return X509v3_get_ext(a->extensions, loc); } X509_EXTENSION *TS_REQ_delete_ext(TS_REQ *a, int loc) { return X509v3_delete_ext(a->extensions, loc); } int TS_REQ_add_ext(TS_REQ *a, X509_EXTENSION *ex, int loc) { return X509v3_add_ext(&a->extensions, ex, loc) != NULL; } void *TS_REQ_get_ext_d2i(TS_REQ *a, int nid, int *crit, int *idx) { return X509V3_get_d2i(a->extensions, nid, crit, idx); }
4,109
21.336957
74
c
openssl
openssl-master/crypto/ts/ts_rsp_print.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/bn.h> #include <openssl/x509v3.h> #include <openssl/ts.h> #include "ts_local.h" struct status_map_st { int bit; const char *text; }; static int ts_status_map_print(BIO *bio, const struct status_map_st *a, const ASN1_BIT_STRING *v); static int ts_ACCURACY_print_bio(BIO *bio, const TS_ACCURACY *accuracy); int TS_RESP_print_bio(BIO *bio, TS_RESP *a) { BIO_printf(bio, "Status info:\n"); TS_STATUS_INFO_print_bio(bio, a->status_info); BIO_printf(bio, "\nTST info:\n"); if (a->tst_info != NULL) TS_TST_INFO_print_bio(bio, a->tst_info); else BIO_printf(bio, "Not included.\n"); return 1; } int TS_STATUS_INFO_print_bio(BIO *bio, TS_STATUS_INFO *a) { static const char *status_map[] = { "Granted.", "Granted with modifications.", "Rejected.", "Waiting.", "Revocation warning.", "Revoked." }; static const struct status_map_st failure_map[] = { {TS_INFO_BAD_ALG, "unrecognized or unsupported algorithm identifier"}, {TS_INFO_BAD_REQUEST, "transaction not permitted or supported"}, {TS_INFO_BAD_DATA_FORMAT, "the data submitted has the wrong format"}, {TS_INFO_TIME_NOT_AVAILABLE, "the TSA's time source is not available"}, {TS_INFO_UNACCEPTED_POLICY, "the requested TSA policy is not supported by the TSA"}, {TS_INFO_UNACCEPTED_EXTENSION, "the requested extension is not supported by the TSA"}, {TS_INFO_ADD_INFO_NOT_AVAILABLE, "the additional information requested could not be understood " "or is not available"}, {TS_INFO_SYSTEM_FAILURE, "the request cannot be handled due to system failure"}, {-1, NULL} }; long status; int i, lines = 0; BIO_printf(bio, "Status: "); status = ASN1_INTEGER_get(a->status); if (0 <= status && status < (long)OSSL_NELEM(status_map)) BIO_printf(bio, "%s\n", status_map[status]); else BIO_printf(bio, "out of bounds\n"); BIO_printf(bio, "Status description: "); for (i = 0; i < sk_ASN1_UTF8STRING_num(a->text); ++i) { if (i > 0) BIO_puts(bio, "\t"); ASN1_STRING_print_ex(bio, sk_ASN1_UTF8STRING_value(a->text, i), 0); BIO_puts(bio, "\n"); } if (i == 0) BIO_printf(bio, "unspecified\n"); BIO_printf(bio, "Failure info: "); if (a->failure_info != NULL) lines = ts_status_map_print(bio, failure_map, a->failure_info); if (lines == 0) BIO_printf(bio, "unspecified"); BIO_printf(bio, "\n"); return 1; } static int ts_status_map_print(BIO *bio, const struct status_map_st *a, const ASN1_BIT_STRING *v) { int lines = 0; for (; a->bit >= 0; ++a) { if (ASN1_BIT_STRING_get_bit(v, a->bit)) { if (++lines > 1) BIO_printf(bio, ", "); BIO_printf(bio, "%s", a->text); } } return lines; } int TS_TST_INFO_print_bio(BIO *bio, TS_TST_INFO *a) { int v; if (a == NULL) return 0; v = ASN1_INTEGER_get(a->version); BIO_printf(bio, "Version: %d\n", v); BIO_printf(bio, "Policy OID: "); TS_OBJ_print_bio(bio, a->policy_id); TS_MSG_IMPRINT_print_bio(bio, a->msg_imprint); BIO_printf(bio, "Serial number: "); if (a->serial == NULL) BIO_printf(bio, "unspecified"); else TS_ASN1_INTEGER_print_bio(bio, a->serial); BIO_write(bio, "\n", 1); BIO_printf(bio, "Time stamp: "); ASN1_GENERALIZEDTIME_print(bio, a->time); BIO_write(bio, "\n", 1); BIO_printf(bio, "Accuracy: "); if (a->accuracy == NULL) BIO_printf(bio, "unspecified"); else ts_ACCURACY_print_bio(bio, a->accuracy); BIO_write(bio, "\n", 1); BIO_printf(bio, "Ordering: %s\n", a->ordering ? "yes" : "no"); BIO_printf(bio, "Nonce: "); if (a->nonce == NULL) BIO_printf(bio, "unspecified"); else TS_ASN1_INTEGER_print_bio(bio, a->nonce); BIO_write(bio, "\n", 1); BIO_printf(bio, "TSA: "); if (a->tsa == NULL) BIO_printf(bio, "unspecified"); else { STACK_OF(CONF_VALUE) *nval; if ((nval = i2v_GENERAL_NAME(NULL, a->tsa, NULL))) X509V3_EXT_val_prn(bio, nval, 0, 0); sk_CONF_VALUE_pop_free(nval, X509V3_conf_free); } BIO_write(bio, "\n", 1); TS_ext_print_bio(bio, a->extensions); return 1; } static int ts_ACCURACY_print_bio(BIO *bio, const TS_ACCURACY *a) { if (a->seconds != NULL) TS_ASN1_INTEGER_print_bio(bio, a->seconds); else BIO_printf(bio, "unspecified"); BIO_printf(bio, " seconds, "); if (a->millis != NULL) TS_ASN1_INTEGER_print_bio(bio, a->millis); else BIO_printf(bio, "unspecified"); BIO_printf(bio, " millis, "); if (a->micros != NULL) TS_ASN1_INTEGER_print_bio(bio, a->micros); else BIO_printf(bio, "unspecified"); BIO_printf(bio, " micros"); return 1; }
5,525
27.193878
75
c
openssl
openssl-master/crypto/ts/ts_rsp_utils.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/ts.h> #include <openssl/pkcs7.h> #include "ts_local.h" int TS_RESP_set_status_info(TS_RESP *a, TS_STATUS_INFO *status_info) { TS_STATUS_INFO *new_status_info; if (a->status_info == status_info) return 1; new_status_info = TS_STATUS_INFO_dup(status_info); if (new_status_info == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_TS_LIB); return 0; } TS_STATUS_INFO_free(a->status_info); a->status_info = new_status_info; return 1; } TS_STATUS_INFO *TS_RESP_get_status_info(TS_RESP *a) { return a->status_info; } /* Caller loses ownership of PKCS7 and TS_TST_INFO objects. */ void TS_RESP_set_tst_info(TS_RESP *a, PKCS7 *p7, TS_TST_INFO *tst_info) { PKCS7_free(a->token); a->token = p7; TS_TST_INFO_free(a->tst_info); a->tst_info = tst_info; } PKCS7 *TS_RESP_get_token(TS_RESP *a) { return a->token; } TS_TST_INFO *TS_RESP_get_tst_info(TS_RESP *a) { return a->tst_info; } int TS_TST_INFO_set_version(TS_TST_INFO *a, long version) { return ASN1_INTEGER_set(a->version, version); } long TS_TST_INFO_get_version(const TS_TST_INFO *a) { return ASN1_INTEGER_get(a->version); } int TS_TST_INFO_set_policy_id(TS_TST_INFO *a, ASN1_OBJECT *policy) { ASN1_OBJECT *new_policy; if (a->policy_id == policy) return 1; new_policy = OBJ_dup(policy); if (new_policy == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_OBJ_LIB); return 0; } ASN1_OBJECT_free(a->policy_id); a->policy_id = new_policy; return 1; } ASN1_OBJECT *TS_TST_INFO_get_policy_id(TS_TST_INFO *a) { return a->policy_id; } int TS_TST_INFO_set_msg_imprint(TS_TST_INFO *a, TS_MSG_IMPRINT *msg_imprint) { TS_MSG_IMPRINT *new_msg_imprint; if (a->msg_imprint == msg_imprint) return 1; new_msg_imprint = TS_MSG_IMPRINT_dup(msg_imprint); if (new_msg_imprint == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_TS_LIB); return 0; } TS_MSG_IMPRINT_free(a->msg_imprint); a->msg_imprint = new_msg_imprint; return 1; } TS_MSG_IMPRINT *TS_TST_INFO_get_msg_imprint(TS_TST_INFO *a) { return a->msg_imprint; } int TS_TST_INFO_set_serial(TS_TST_INFO *a, const ASN1_INTEGER *serial) { ASN1_INTEGER *new_serial; if (a->serial == serial) return 1; new_serial = ASN1_INTEGER_dup(serial); if (new_serial == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB); return 0; } ASN1_INTEGER_free(a->serial); a->serial = new_serial; return 1; } const ASN1_INTEGER *TS_TST_INFO_get_serial(const TS_TST_INFO *a) { return a->serial; } int TS_TST_INFO_set_time(TS_TST_INFO *a, const ASN1_GENERALIZEDTIME *gtime) { ASN1_GENERALIZEDTIME *new_time; if (a->time == gtime) return 1; new_time = ASN1_STRING_dup(gtime); if (new_time == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB); return 0; } ASN1_GENERALIZEDTIME_free(a->time); a->time = new_time; return 1; } const ASN1_GENERALIZEDTIME *TS_TST_INFO_get_time(const TS_TST_INFO *a) { return a->time; } int TS_TST_INFO_set_accuracy(TS_TST_INFO *a, TS_ACCURACY *accuracy) { TS_ACCURACY *new_accuracy; if (a->accuracy == accuracy) return 1; new_accuracy = TS_ACCURACY_dup(accuracy); if (new_accuracy == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_TS_LIB); return 0; } TS_ACCURACY_free(a->accuracy); a->accuracy = new_accuracy; return 1; } TS_ACCURACY *TS_TST_INFO_get_accuracy(TS_TST_INFO *a) { return a->accuracy; } int TS_ACCURACY_set_seconds(TS_ACCURACY *a, const ASN1_INTEGER *seconds) { ASN1_INTEGER *new_seconds; if (a->seconds == seconds) return 1; new_seconds = ASN1_INTEGER_dup(seconds); if (new_seconds == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB); return 0; } ASN1_INTEGER_free(a->seconds); a->seconds = new_seconds; return 1; } const ASN1_INTEGER *TS_ACCURACY_get_seconds(const TS_ACCURACY *a) { return a->seconds; } int TS_ACCURACY_set_millis(TS_ACCURACY *a, const ASN1_INTEGER *millis) { ASN1_INTEGER *new_millis = NULL; if (a->millis == millis) return 1; if (millis != NULL) { new_millis = ASN1_INTEGER_dup(millis); if (new_millis == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB); return 0; } } ASN1_INTEGER_free(a->millis); a->millis = new_millis; return 1; } const ASN1_INTEGER *TS_ACCURACY_get_millis(const TS_ACCURACY *a) { return a->millis; } int TS_ACCURACY_set_micros(TS_ACCURACY *a, const ASN1_INTEGER *micros) { ASN1_INTEGER *new_micros = NULL; if (a->micros == micros) return 1; if (micros != NULL) { new_micros = ASN1_INTEGER_dup(micros); if (new_micros == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB); return 0; } } ASN1_INTEGER_free(a->micros); a->micros = new_micros; return 1; } const ASN1_INTEGER *TS_ACCURACY_get_micros(const TS_ACCURACY *a) { return a->micros; } int TS_TST_INFO_set_ordering(TS_TST_INFO *a, int ordering) { a->ordering = ordering ? 0xFF : 0x00; return 1; } int TS_TST_INFO_get_ordering(const TS_TST_INFO *a) { return a->ordering ? 1 : 0; } int TS_TST_INFO_set_nonce(TS_TST_INFO *a, const ASN1_INTEGER *nonce) { ASN1_INTEGER *new_nonce; if (a->nonce == nonce) return 1; new_nonce = ASN1_INTEGER_dup(nonce); if (new_nonce == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB); return 0; } ASN1_INTEGER_free(a->nonce); a->nonce = new_nonce; return 1; } const ASN1_INTEGER *TS_TST_INFO_get_nonce(const TS_TST_INFO *a) { return a->nonce; } int TS_TST_INFO_set_tsa(TS_TST_INFO *a, GENERAL_NAME *tsa) { GENERAL_NAME *new_tsa; if (a->tsa == tsa) return 1; new_tsa = GENERAL_NAME_dup(tsa); if (new_tsa == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_ASN1_LIB); return 0; } GENERAL_NAME_free(a->tsa); a->tsa = new_tsa; return 1; } GENERAL_NAME *TS_TST_INFO_get_tsa(TS_TST_INFO *a) { return a->tsa; } STACK_OF(X509_EXTENSION) *TS_TST_INFO_get_exts(TS_TST_INFO *a) { return a->extensions; } void TS_TST_INFO_ext_free(TS_TST_INFO *a) { if (!a) return; sk_X509_EXTENSION_pop_free(a->extensions, X509_EXTENSION_free); a->extensions = NULL; } int TS_TST_INFO_get_ext_count(TS_TST_INFO *a) { return X509v3_get_ext_count(a->extensions); } int TS_TST_INFO_get_ext_by_NID(TS_TST_INFO *a, int nid, int lastpos) { return X509v3_get_ext_by_NID(a->extensions, nid, lastpos); } int TS_TST_INFO_get_ext_by_OBJ(TS_TST_INFO *a, const ASN1_OBJECT *obj, int lastpos) { return X509v3_get_ext_by_OBJ(a->extensions, obj, lastpos); } int TS_TST_INFO_get_ext_by_critical(TS_TST_INFO *a, int crit, int lastpos) { return X509v3_get_ext_by_critical(a->extensions, crit, lastpos); } X509_EXTENSION *TS_TST_INFO_get_ext(TS_TST_INFO *a, int loc) { return X509v3_get_ext(a->extensions, loc); } X509_EXTENSION *TS_TST_INFO_delete_ext(TS_TST_INFO *a, int loc) { return X509v3_delete_ext(a->extensions, loc); } int TS_TST_INFO_add_ext(TS_TST_INFO *a, X509_EXTENSION *ex, int loc) { return X509v3_add_ext(&a->extensions, ex, loc) != NULL; } void *TS_TST_INFO_get_ext_d2i(TS_TST_INFO *a, int nid, int *crit, int *idx) { return X509V3_get_d2i(a->extensions, nid, crit, idx); } int TS_STATUS_INFO_set_status(TS_STATUS_INFO *a, int i) { return ASN1_INTEGER_set(a->status, i); } const ASN1_INTEGER *TS_STATUS_INFO_get0_status(const TS_STATUS_INFO *a) { return a->status; } const STACK_OF(ASN1_UTF8STRING) * TS_STATUS_INFO_get0_text(const TS_STATUS_INFO *a) { return a->text; } const ASN1_BIT_STRING *TS_STATUS_INFO_get0_failure_info(const TS_STATUS_INFO *a) { return a->failure_info; }
8,301
21.68306
83
c
openssl
openssl-master/crypto/ts/ts_rsp_verify.c
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <openssl/objects.h> #include <openssl/ts.h> #include <openssl/pkcs7.h> #include "internal/cryptlib.h" #include "internal/sizes.h" #include "crypto/ess.h" #include "ts_local.h" static int ts_verify_cert(X509_STORE *store, STACK_OF(X509) *untrusted, X509 *signer, STACK_OF(X509) **chain); static int ts_check_signing_certs(const PKCS7_SIGNER_INFO *si, const STACK_OF(X509) *chain); static int int_ts_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token, TS_TST_INFO *tst_info); static int ts_check_status_info(TS_RESP *response); static char *ts_get_status_text(STACK_OF(ASN1_UTF8STRING) *text); static int ts_check_policy(const ASN1_OBJECT *req_oid, const TS_TST_INFO *tst_info); static int ts_compute_imprint(BIO *data, TS_TST_INFO *tst_info, X509_ALGOR **md_alg, unsigned char **imprint, unsigned *imprint_len); static int ts_check_imprints(X509_ALGOR *algor_a, const unsigned char *imprint_a, unsigned len_a, TS_TST_INFO *tst_info); static int ts_check_nonces(const ASN1_INTEGER *a, TS_TST_INFO *tst_info); static int ts_check_signer_name(GENERAL_NAME *tsa_name, X509 *signer); static int ts_find_name(STACK_OF(GENERAL_NAME) *gen_names, GENERAL_NAME *name); /* * This must be large enough to hold all values in ts_status_text (with * comma separator) or all text fields in ts_failure_info (also with comma). */ #define TS_STATUS_BUF_SIZE 256 /* * Local mapping between response codes and descriptions. */ static const char *ts_status_text[] = { "granted", "grantedWithMods", "rejection", "waiting", "revocationWarning", "revocationNotification" }; #define TS_STATUS_TEXT_SIZE OSSL_NELEM(ts_status_text) static struct { int code; const char *text; } ts_failure_info[] = { {TS_INFO_BAD_ALG, "badAlg"}, {TS_INFO_BAD_REQUEST, "badRequest"}, {TS_INFO_BAD_DATA_FORMAT, "badDataFormat"}, {TS_INFO_TIME_NOT_AVAILABLE, "timeNotAvailable"}, {TS_INFO_UNACCEPTED_POLICY, "unacceptedPolicy"}, {TS_INFO_UNACCEPTED_EXTENSION, "unacceptedExtension"}, {TS_INFO_ADD_INFO_NOT_AVAILABLE, "addInfoNotAvailable"}, {TS_INFO_SYSTEM_FAILURE, "systemFailure"} }; /*- * This function carries out the following tasks: * - Checks if there is one and only one signer. * - Search for the signing certificate in 'certs' and in the response. * - Check the extended key usage and key usage fields of the signer * certificate (done by the path validation). * - Build and validate the certificate path. * - Check if the certificate path meets the requirements of the * SigningCertificate ESS signed attribute. * - Verify the signature value. * - Returns the signer certificate in 'signer', if 'signer' is not NULL. */ int TS_RESP_verify_signature(PKCS7 *token, STACK_OF(X509) *certs, X509_STORE *store, X509 **signer_out) { STACK_OF(PKCS7_SIGNER_INFO) *sinfos = NULL; PKCS7_SIGNER_INFO *si; STACK_OF(X509) *untrusted = NULL; STACK_OF(X509) *signers = NULL; X509 *signer; STACK_OF(X509) *chain = NULL; char buf[4096]; int i, j = 0, ret = 0; BIO *p7bio = NULL; /* Some sanity checks first. */ if (!token) { ERR_raise(ERR_LIB_TS, TS_R_INVALID_NULL_POINTER); goto err; } if (!PKCS7_type_is_signed(token)) { ERR_raise(ERR_LIB_TS, TS_R_WRONG_CONTENT_TYPE); goto err; } sinfos = PKCS7_get_signer_info(token); if (!sinfos || sk_PKCS7_SIGNER_INFO_num(sinfos) != 1) { ERR_raise(ERR_LIB_TS, TS_R_THERE_MUST_BE_ONE_SIGNER); goto err; } si = sk_PKCS7_SIGNER_INFO_value(sinfos, 0); if (PKCS7_get_detached(token)) { ERR_raise(ERR_LIB_TS, TS_R_NO_CONTENT); goto err; } /* * Get hold of the signer certificate, search only internal certificates * if it was requested. */ signers = PKCS7_get0_signers(token, certs, 0); if (!signers || sk_X509_num(signers) != 1) goto err; signer = sk_X509_value(signers, 0); untrusted = sk_X509_new_reserve(NULL, sk_X509_num(certs) + sk_X509_num(token->d.sign->cert)); if (untrusted == NULL || !X509_add_certs(untrusted, certs, 0) || !X509_add_certs(untrusted, token->d.sign->cert, 0)) goto err; if (!ts_verify_cert(store, untrusted, signer, &chain)) goto err; if (!ts_check_signing_certs(si, chain)) goto err; p7bio = PKCS7_dataInit(token, NULL); /* We now have to 'read' from p7bio to calculate digests etc. */ while ((i = BIO_read(p7bio, buf, sizeof(buf))) > 0) continue; j = PKCS7_signatureVerify(p7bio, token, si, signer); if (j <= 0) { ERR_raise(ERR_LIB_TS, TS_R_SIGNATURE_FAILURE); goto err; } if (signer_out) { *signer_out = signer; X509_up_ref(signer); } ret = 1; err: BIO_free_all(p7bio); sk_X509_free(untrusted); OSSL_STACK_OF_X509_free(chain); sk_X509_free(signers); return ret; } /* * The certificate chain is returned in chain. Caller is responsible for * freeing the vector. */ static int ts_verify_cert(X509_STORE *store, STACK_OF(X509) *untrusted, X509 *signer, STACK_OF(X509) **chain) { X509_STORE_CTX *cert_ctx = NULL; int i; int ret = 0; *chain = NULL; cert_ctx = X509_STORE_CTX_new(); if (cert_ctx == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_X509_LIB); goto err; } if (!X509_STORE_CTX_init(cert_ctx, store, signer, untrusted)) goto end; X509_STORE_CTX_set_purpose(cert_ctx, X509_PURPOSE_TIMESTAMP_SIGN); i = X509_verify_cert(cert_ctx); if (i <= 0) { int j = X509_STORE_CTX_get_error(cert_ctx); ERR_raise_data(ERR_LIB_TS, TS_R_CERTIFICATE_VERIFY_ERROR, "Verify error:%s", X509_verify_cert_error_string(j)); goto err; } *chain = X509_STORE_CTX_get1_chain(cert_ctx); ret = 1; goto end; err: ret = 0; end: X509_STORE_CTX_free(cert_ctx); return ret; } static ESS_SIGNING_CERT *ossl_ess_get_signing_cert(const PKCS7_SIGNER_INFO *si) { ASN1_TYPE *attr; const unsigned char *p; attr = PKCS7_get_signed_attribute(si, NID_id_smime_aa_signingCertificate); if (attr == NULL) return NULL; p = attr->value.sequence->data; return d2i_ESS_SIGNING_CERT(NULL, &p, attr->value.sequence->length); } static ESS_SIGNING_CERT_V2 *ossl_ess_get_signing_cert_v2(const PKCS7_SIGNER_INFO *si) { ASN1_TYPE *attr; const unsigned char *p; attr = PKCS7_get_signed_attribute(si, NID_id_smime_aa_signingCertificateV2); if (attr == NULL) return NULL; p = attr->value.sequence->data; return d2i_ESS_SIGNING_CERT_V2(NULL, &p, attr->value.sequence->length); } static int ts_check_signing_certs(const PKCS7_SIGNER_INFO *si, const STACK_OF(X509) *chain) { ESS_SIGNING_CERT *ss = ossl_ess_get_signing_cert(si); ESS_SIGNING_CERT_V2 *ssv2 = ossl_ess_get_signing_cert_v2(si); int ret = OSSL_ESS_check_signing_certs(ss, ssv2, chain, 1) > 0; ESS_SIGNING_CERT_free(ss); ESS_SIGNING_CERT_V2_free(ssv2); return ret; } /*- * Verifies whether 'response' contains a valid response with regards * to the settings of the context: * - Gives an error message if the TS_TST_INFO is not present. * - Calls _TS_RESP_verify_token to verify the token content. */ int TS_RESP_verify_response(TS_VERIFY_CTX *ctx, TS_RESP *response) { PKCS7 *token = response->token; TS_TST_INFO *tst_info = response->tst_info; int ret = 0; if (!ts_check_status_info(response)) goto err; if (!int_ts_RESP_verify_token(ctx, token, tst_info)) goto err; ret = 1; err: return ret; } /* * Tries to extract a TS_TST_INFO structure from the PKCS7 token and * calls the internal int_TS_RESP_verify_token function for verifying it. */ int TS_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token) { TS_TST_INFO *tst_info = PKCS7_to_TS_TST_INFO(token); int ret = 0; if (tst_info) { ret = int_ts_RESP_verify_token(ctx, token, tst_info); TS_TST_INFO_free(tst_info); } return ret; } /*- * Verifies whether the 'token' contains a valid timestamp token * with regards to the settings of the context. Only those checks are * carried out that are specified in the context: * - Verifies the signature of the TS_TST_INFO. * - Checks the version number of the response. * - Check if the requested and returned policies math. * - Check if the message imprints are the same. * - Check if the nonces are the same. * - Check if the TSA name matches the signer. * - Check if the TSA name is the expected TSA. */ static int int_ts_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token, TS_TST_INFO *tst_info) { X509 *signer = NULL; GENERAL_NAME *tsa_name = tst_info->tsa; X509_ALGOR *md_alg = NULL; unsigned char *imprint = NULL; unsigned imprint_len = 0; int ret = 0; int flags = ctx->flags; /* Some options require us to also check the signature */ if (((flags & TS_VFY_SIGNER) && tsa_name != NULL) || (flags & TS_VFY_TSA_NAME)) { flags |= TS_VFY_SIGNATURE; } if ((flags & TS_VFY_SIGNATURE) && !TS_RESP_verify_signature(token, ctx->certs, ctx->store, &signer)) goto err; if ((flags & TS_VFY_VERSION) && TS_TST_INFO_get_version(tst_info) != 1) { ERR_raise(ERR_LIB_TS, TS_R_UNSUPPORTED_VERSION); goto err; } if ((flags & TS_VFY_POLICY) && !ts_check_policy(ctx->policy, tst_info)) goto err; if ((flags & TS_VFY_IMPRINT) && !ts_check_imprints(ctx->md_alg, ctx->imprint, ctx->imprint_len, tst_info)) goto err; if ((flags & TS_VFY_DATA) && (!ts_compute_imprint(ctx->data, tst_info, &md_alg, &imprint, &imprint_len) || !ts_check_imprints(md_alg, imprint, imprint_len, tst_info))) goto err; if ((flags & TS_VFY_NONCE) && !ts_check_nonces(ctx->nonce, tst_info)) goto err; if ((flags & TS_VFY_SIGNER) && tsa_name && !ts_check_signer_name(tsa_name, signer)) { ERR_raise(ERR_LIB_TS, TS_R_TSA_NAME_MISMATCH); goto err; } if ((flags & TS_VFY_TSA_NAME) && !ts_check_signer_name(ctx->tsa_name, signer)) { ERR_raise(ERR_LIB_TS, TS_R_TSA_UNTRUSTED); goto err; } ret = 1; err: X509_free(signer); X509_ALGOR_free(md_alg); OPENSSL_free(imprint); return ret; } static int ts_check_status_info(TS_RESP *response) { TS_STATUS_INFO *info = response->status_info; long status = ASN1_INTEGER_get(info->status); const char *status_text = NULL; char *embedded_status_text = NULL; char failure_text[TS_STATUS_BUF_SIZE] = ""; if (status == 0 || status == 1) return 1; /* There was an error, get the description in status_text. */ if (0 <= status && status < (long) OSSL_NELEM(ts_status_text)) status_text = ts_status_text[status]; else status_text = "unknown code"; if (sk_ASN1_UTF8STRING_num(info->text) > 0 && (embedded_status_text = ts_get_status_text(info->text)) == NULL) return 0; /* Fill in failure_text with the failure information. */ if (info->failure_info) { int i; int first = 1; for (i = 0; i < (int)OSSL_NELEM(ts_failure_info); ++i) { if (ASN1_BIT_STRING_get_bit(info->failure_info, ts_failure_info[i].code)) { if (!first) strcat(failure_text, ","); else first = 0; strcat(failure_text, ts_failure_info[i].text); } } } if (failure_text[0] == '\0') strcpy(failure_text, "unspecified"); ERR_raise_data(ERR_LIB_TS, TS_R_NO_TIME_STAMP_TOKEN, "status code: %s, status text: %s, failure codes: %s", status_text, embedded_status_text ? embedded_status_text : "unspecified", failure_text); OPENSSL_free(embedded_status_text); return 0; } static char *ts_get_status_text(STACK_OF(ASN1_UTF8STRING) *text) { return ossl_sk_ASN1_UTF8STRING2text(text, "/", TS_MAX_STATUS_LENGTH); } static int ts_check_policy(const ASN1_OBJECT *req_oid, const TS_TST_INFO *tst_info) { const ASN1_OBJECT *resp_oid = tst_info->policy_id; if (OBJ_cmp(req_oid, resp_oid) != 0) { ERR_raise(ERR_LIB_TS, TS_R_POLICY_MISMATCH); return 0; } return 1; } static int ts_compute_imprint(BIO *data, TS_TST_INFO *tst_info, X509_ALGOR **md_alg, unsigned char **imprint, unsigned *imprint_len) { TS_MSG_IMPRINT *msg_imprint = tst_info->msg_imprint; X509_ALGOR *md_alg_resp = msg_imprint->hash_algo; EVP_MD *md = NULL; EVP_MD_CTX *md_ctx = NULL; unsigned char buffer[4096]; char name[OSSL_MAX_NAME_SIZE]; int length; *md_alg = NULL; *imprint = NULL; if ((*md_alg = X509_ALGOR_dup(md_alg_resp)) == NULL) goto err; OBJ_obj2txt(name, sizeof(name), md_alg_resp->algorithm, 0); (void)ERR_set_mark(); md = EVP_MD_fetch(NULL, name, NULL); if (md == NULL) md = (EVP_MD *)EVP_get_digestbyname(name); if (md == NULL) { (void)ERR_clear_last_mark(); goto err; } (void)ERR_pop_to_mark(); length = EVP_MD_get_size(md); if (length < 0) goto err; *imprint_len = length; if ((*imprint = OPENSSL_malloc(*imprint_len)) == NULL) goto err; md_ctx = EVP_MD_CTX_new(); if (md_ctx == NULL) { ERR_raise(ERR_LIB_TS, ERR_R_EVP_LIB); goto err; } if (!EVP_DigestInit(md_ctx, md)) goto err; EVP_MD_free(md); md = NULL; while ((length = BIO_read(data, buffer, sizeof(buffer))) > 0) { if (!EVP_DigestUpdate(md_ctx, buffer, length)) goto err; } if (!EVP_DigestFinal(md_ctx, *imprint, NULL)) goto err; EVP_MD_CTX_free(md_ctx); return 1; err: EVP_MD_CTX_free(md_ctx); EVP_MD_free(md); X509_ALGOR_free(*md_alg); *md_alg = NULL; OPENSSL_free(*imprint); *imprint_len = 0; *imprint = 0; return 0; } static int ts_check_imprints(X509_ALGOR *algor_a, const unsigned char *imprint_a, unsigned len_a, TS_TST_INFO *tst_info) { TS_MSG_IMPRINT *b = tst_info->msg_imprint; X509_ALGOR *algor_b = b->hash_algo; int ret = 0; if (algor_a) { if (OBJ_cmp(algor_a->algorithm, algor_b->algorithm)) goto err; /* The parameter must be NULL in both. */ if ((algor_a->parameter && ASN1_TYPE_get(algor_a->parameter) != V_ASN1_NULL) || (algor_b->parameter && ASN1_TYPE_get(algor_b->parameter) != V_ASN1_NULL)) goto err; } ret = len_a == (unsigned)ASN1_STRING_length(b->hashed_msg) && memcmp(imprint_a, ASN1_STRING_get0_data(b->hashed_msg), len_a) == 0; err: if (!ret) ERR_raise(ERR_LIB_TS, TS_R_MESSAGE_IMPRINT_MISMATCH); return ret; } static int ts_check_nonces(const ASN1_INTEGER *a, TS_TST_INFO *tst_info) { const ASN1_INTEGER *b = tst_info->nonce; if (!b) { ERR_raise(ERR_LIB_TS, TS_R_NONCE_NOT_RETURNED); return 0; } /* No error if a nonce is returned without being requested. */ if (ASN1_INTEGER_cmp(a, b) != 0) { ERR_raise(ERR_LIB_TS, TS_R_NONCE_MISMATCH); return 0; } return 1; } /* * Check if the specified TSA name matches either the subject or one of the * subject alternative names of the TSA certificate. */ static int ts_check_signer_name(GENERAL_NAME *tsa_name, X509 *signer) { STACK_OF(GENERAL_NAME) *gen_names = NULL; int idx = -1; int found = 0; if (tsa_name->type == GEN_DIRNAME && X509_name_cmp(tsa_name->d.dirn, X509_get_subject_name(signer)) == 0) return 1; gen_names = X509_get_ext_d2i(signer, NID_subject_alt_name, NULL, &idx); while (gen_names != NULL) { found = ts_find_name(gen_names, tsa_name) >= 0; if (found) break; /* * Get the next subject alternative name, although there should be no * more than one. */ GENERAL_NAMES_free(gen_names); gen_names = X509_get_ext_d2i(signer, NID_subject_alt_name, NULL, &idx); } GENERAL_NAMES_free(gen_names); return found; } /* Returns 1 if name is in gen_names, 0 otherwise. */ static int ts_find_name(STACK_OF(GENERAL_NAME) *gen_names, GENERAL_NAME *name) { int i, found; for (i = 0, found = 0; !found && i < sk_GENERAL_NAME_num(gen_names); ++i) { GENERAL_NAME *current = sk_GENERAL_NAME_value(gen_names, i); found = GENERAL_NAME_cmp(current, name) == 0; } return found ? i - 1 : -1; }
17,859
30.223776
80
c
openssl
openssl-master/crypto/ts/ts_verify_ctx.c
/* * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/ts.h> #include "ts_local.h" TS_VERIFY_CTX *TS_VERIFY_CTX_new(void) { TS_VERIFY_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); return ctx; } void TS_VERIFY_CTX_init(TS_VERIFY_CTX *ctx) { OPENSSL_assert(ctx != NULL); memset(ctx, 0, sizeof(*ctx)); } void TS_VERIFY_CTX_free(TS_VERIFY_CTX *ctx) { if (!ctx) return; TS_VERIFY_CTX_cleanup(ctx); OPENSSL_free(ctx); } int TS_VERIFY_CTX_add_flags(TS_VERIFY_CTX *ctx, int f) { ctx->flags |= f; return ctx->flags; } int TS_VERIFY_CTX_set_flags(TS_VERIFY_CTX *ctx, int f) { ctx->flags = f; return ctx->flags; } BIO *TS_VERIFY_CTX_set_data(TS_VERIFY_CTX *ctx, BIO *b) { ctx->data = b; return ctx->data; } X509_STORE *TS_VERIFY_CTX_set_store(TS_VERIFY_CTX *ctx, X509_STORE *s) { ctx->store = s; return ctx->store; } STACK_OF(X509) *TS_VERIFY_CTX_set_certs(TS_VERIFY_CTX *ctx, STACK_OF(X509) *certs) { ctx->certs = certs; return ctx->certs; } unsigned char *TS_VERIFY_CTX_set_imprint(TS_VERIFY_CTX *ctx, unsigned char *hexstr, long len) { OPENSSL_free(ctx->imprint); ctx->imprint = hexstr; ctx->imprint_len = len; return ctx->imprint; } void TS_VERIFY_CTX_cleanup(TS_VERIFY_CTX *ctx) { if (!ctx) return; X509_STORE_free(ctx->store); OSSL_STACK_OF_X509_free(ctx->certs); ASN1_OBJECT_free(ctx->policy); X509_ALGOR_free(ctx->md_alg); OPENSSL_free(ctx->imprint); BIO_free_all(ctx->data); ASN1_INTEGER_free(ctx->nonce); GENERAL_NAME_free(ctx->tsa_name); TS_VERIFY_CTX_init(ctx); } TS_VERIFY_CTX *TS_REQ_to_TS_VERIFY_CTX(TS_REQ *req, TS_VERIFY_CTX *ctx) { TS_VERIFY_CTX *ret = ctx; ASN1_OBJECT *policy; TS_MSG_IMPRINT *imprint; X509_ALGOR *md_alg; ASN1_OCTET_STRING *msg; const ASN1_INTEGER *nonce; OPENSSL_assert(req != NULL); if (ret) TS_VERIFY_CTX_cleanup(ret); else if ((ret = TS_VERIFY_CTX_new()) == NULL) return NULL; ret->flags = TS_VFY_ALL_IMPRINT & ~(TS_VFY_TSA_NAME | TS_VFY_SIGNATURE); if ((policy = req->policy_id) != NULL) { if ((ret->policy = OBJ_dup(policy)) == NULL) goto err; } else ret->flags &= ~TS_VFY_POLICY; imprint = req->msg_imprint; md_alg = imprint->hash_algo; if ((ret->md_alg = X509_ALGOR_dup(md_alg)) == NULL) goto err; msg = imprint->hashed_msg; ret->imprint_len = ASN1_STRING_length(msg); if (ret->imprint_len <= 0) goto err; if ((ret->imprint = OPENSSL_malloc(ret->imprint_len)) == NULL) goto err; memcpy(ret->imprint, ASN1_STRING_get0_data(msg), ret->imprint_len); if ((nonce = req->nonce) != NULL) { if ((ret->nonce = ASN1_INTEGER_dup(nonce)) == NULL) goto err; } else ret->flags &= ~TS_VFY_NONCE; return ret; err: if (ctx) TS_VERIFY_CTX_cleanup(ctx); else TS_VERIFY_CTX_free(ret); return NULL; }
3,433
22.202703
76
c
openssl
openssl-master/crypto/txt_db/txt_db.c
/* * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "internal/cryptlib.h" #include <openssl/buffer.h> #include <openssl/txt_db.h> #undef BUFSIZE #define BUFSIZE 512 TXT_DB *TXT_DB_read(BIO *in, int num) { TXT_DB *ret = NULL; int esc = 0; int i, add, n; int size = BUFSIZE; int offset = 0; char *p, *f; OPENSSL_STRING *pp; BUF_MEM *buf = NULL; if ((buf = BUF_MEM_new()) == NULL) goto err; if (!BUF_MEM_grow(buf, size)) goto err; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) goto err; ret->num_fields = num; ret->index = NULL; ret->qual = NULL; if ((ret->data = sk_OPENSSL_PSTRING_new_null()) == NULL) goto err; if ((ret->index = OPENSSL_malloc(sizeof(*ret->index) * num)) == NULL) goto err; if ((ret->qual = OPENSSL_malloc(sizeof(*(ret->qual)) * num)) == NULL) goto err; for (i = 0; i < num; i++) { ret->index[i] = NULL; ret->qual[i] = NULL; } add = (num + 1) * sizeof(char *); buf->data[size - 1] = '\0'; offset = 0; for (;;) { if (offset != 0) { size += BUFSIZE; if (!BUF_MEM_grow_clean(buf, size)) goto err; } buf->data[offset] = '\0'; BIO_gets(in, &(buf->data[offset]), size - offset); if (buf->data[offset] == '\0') break; if ((offset == 0) && (buf->data[0] == '#')) continue; i = strlen(&(buf->data[offset])); offset += i; if (buf->data[offset - 1] != '\n') continue; else { buf->data[offset - 1] = '\0'; /* blat the '\n' */ if ((p = OPENSSL_malloc(add + offset)) == NULL) goto err; offset = 0; } pp = (char **)p; p += add; n = 0; pp[n++] = p; f = buf->data; esc = 0; for (;;) { if (*f == '\0') break; if (*f == '\t') { if (esc) p--; else { *(p++) = '\0'; f++; if (n >= num) break; pp[n++] = p; continue; } } esc = (*f == '\\'); *(p++) = *(f++); } *(p++) = '\0'; if ((n != num) || (*f != '\0')) { OPENSSL_free(pp); ret->error = DB_ERROR_WRONG_NUM_FIELDS; goto err; } pp[n] = p; if (!sk_OPENSSL_PSTRING_push(ret->data, pp)) { OPENSSL_free(pp); goto err; } } BUF_MEM_free(buf); return ret; err: BUF_MEM_free(buf); if (ret != NULL) { sk_OPENSSL_PSTRING_free(ret->data); OPENSSL_free(ret->index); OPENSSL_free(ret->qual); OPENSSL_free(ret); } return NULL; } OPENSSL_STRING *TXT_DB_get_by_index(TXT_DB *db, int idx, OPENSSL_STRING *value) { OPENSSL_STRING *ret; LHASH_OF(OPENSSL_STRING) *lh; if (idx >= db->num_fields) { db->error = DB_ERROR_INDEX_OUT_OF_RANGE; return NULL; } lh = db->index[idx]; if (lh == NULL) { db->error = DB_ERROR_NO_INDEX; return NULL; } ret = lh_OPENSSL_STRING_retrieve(lh, value); db->error = DB_ERROR_OK; return ret; } int TXT_DB_create_index(TXT_DB *db, int field, int (*qual) (OPENSSL_STRING *), OPENSSL_LH_HASHFUNC hash, OPENSSL_LH_COMPFUNC cmp) { LHASH_OF(OPENSSL_STRING) *idx; OPENSSL_STRING *r, *k; int i, n; if (field >= db->num_fields) { db->error = DB_ERROR_INDEX_OUT_OF_RANGE; return 0; } /* FIXME: we lose type checking at this point */ if ((idx = (LHASH_OF(OPENSSL_STRING) *)OPENSSL_LH_new(hash, cmp)) == NULL) { db->error = DB_ERROR_MALLOC; return 0; } n = sk_OPENSSL_PSTRING_num(db->data); for (i = 0; i < n; i++) { r = sk_OPENSSL_PSTRING_value(db->data, i); if ((qual != NULL) && (qual(r) == 0)) continue; if ((k = lh_OPENSSL_STRING_insert(idx, r)) != NULL) { db->error = DB_ERROR_INDEX_CLASH; db->arg1 = sk_OPENSSL_PSTRING_find(db->data, k); db->arg2 = i; lh_OPENSSL_STRING_free(idx); return 0; } if (lh_OPENSSL_STRING_retrieve(idx, r) == NULL) { db->error = DB_ERROR_MALLOC; lh_OPENSSL_STRING_free(idx); return 0; } } lh_OPENSSL_STRING_free(db->index[field]); db->index[field] = idx; db->qual[field] = qual; return 1; } long TXT_DB_write(BIO *out, TXT_DB *db) { long i, j, n, nn, l, tot = 0; char *p, **pp, *f; BUF_MEM *buf = NULL; long ret = -1; if ((buf = BUF_MEM_new()) == NULL) goto err; n = sk_OPENSSL_PSTRING_num(db->data); nn = db->num_fields; for (i = 0; i < n; i++) { pp = sk_OPENSSL_PSTRING_value(db->data, i); l = 0; for (j = 0; j < nn; j++) { if (pp[j] != NULL) l += strlen(pp[j]); } if (!BUF_MEM_grow_clean(buf, (int)(l * 2 + nn))) goto err; p = buf->data; for (j = 0; j < nn; j++) { f = pp[j]; if (f != NULL) for (;;) { if (*f == '\0') break; if (*f == '\t') *(p++) = '\\'; *(p++) = *(f++); } *(p++) = '\t'; } p[-1] = '\n'; j = p - buf->data; if (BIO_write(out, buf->data, (int)j) != j) goto err; tot += j; } ret = tot; err: BUF_MEM_free(buf); return ret; } int TXT_DB_insert(TXT_DB *db, OPENSSL_STRING *row) { int i; OPENSSL_STRING *r; for (i = 0; i < db->num_fields; i++) { if (db->index[i] != NULL) { if ((db->qual[i] != NULL) && (db->qual[i] (row) == 0)) continue; r = lh_OPENSSL_STRING_retrieve(db->index[i], row); if (r != NULL) { db->error = DB_ERROR_INDEX_CLASH; db->arg1 = i; db->arg_row = r; goto err; } } } for (i = 0; i < db->num_fields; i++) { if (db->index[i] != NULL) { if ((db->qual[i] != NULL) && (db->qual[i] (row) == 0)) continue; (void)lh_OPENSSL_STRING_insert(db->index[i], row); if (lh_OPENSSL_STRING_retrieve(db->index[i], row) == NULL) goto err1; } } if (!sk_OPENSSL_PSTRING_push(db->data, row)) goto err1; return 1; err1: db->error = DB_ERROR_MALLOC; while (i-- > 0) { if (db->index[i] != NULL) { if ((db->qual[i] != NULL) && (db->qual[i] (row) == 0)) continue; (void)lh_OPENSSL_STRING_delete(db->index[i], row); } } err: return 0; } void TXT_DB_free(TXT_DB *db) { int i, n; char **p, *max; if (db == NULL) return; if (db->index != NULL) { for (i = db->num_fields - 1; i >= 0; i--) lh_OPENSSL_STRING_free(db->index[i]); OPENSSL_free(db->index); } OPENSSL_free(db->qual); if (db->data != NULL) { for (i = sk_OPENSSL_PSTRING_num(db->data) - 1; i >= 0; i--) { /* * check if any 'fields' have been allocated from outside of the * initial block */ p = sk_OPENSSL_PSTRING_value(db->data, i); max = p[db->num_fields]; /* last address */ if (max == NULL) { /* new row */ for (n = 0; n < db->num_fields; n++) OPENSSL_free(p[n]); } else { for (n = 0; n < db->num_fields; n++) { if (((p[n] < (char *)p) || (p[n] > max))) OPENSSL_free(p[n]); } } OPENSSL_free(sk_OPENSSL_PSTRING_value(db->data, i)); } sk_OPENSSL_PSTRING_free(db->data); } OPENSSL_free(db); }
8,615
26.352381
80
c
openssl
openssl-master/crypto/ui/ui_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/uierr.h> #include "crypto/uierr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA UI_str_reasons[] = { {ERR_PACK(ERR_LIB_UI, 0, UI_R_COMMON_OK_AND_CANCEL_CHARACTERS), "common ok and cancel characters"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_INDEX_TOO_LARGE), "index too large"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_INDEX_TOO_SMALL), "index too small"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_NO_RESULT_BUFFER), "no result buffer"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_PROCESSING_ERROR), "processing error"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_RESULT_TOO_LARGE), "result too large"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_RESULT_TOO_SMALL), "result too small"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_SYSASSIGN_ERROR), "sys$assign error"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_SYSDASSGN_ERROR), "sys$dassgn error"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_SYSQIOW_ERROR), "sys$qiow error"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_UNKNOWN_CONTROL_COMMAND), "unknown control command"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_UNKNOWN_TTYGET_ERRNO_VALUE), "unknown ttyget errno value"}, {ERR_PACK(ERR_LIB_UI, 0, UI_R_USER_DATA_DUPLICATION_UNSUPPORTED), "user data duplication unsupported"}, {0, NULL} }; #endif int ossl_err_load_UI_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(UI_str_reasons[0].error) == NULL) ERR_load_strings_const(UI_str_reasons); #endif return 1; }
1,820
36.9375
74
c
openssl
openssl-master/crypto/ui/ui_local.h
/* * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_UI_LOCAL_H # define OSSL_CRYPTO_UI_LOCAL_H # include <openssl/ui.h> # include <openssl/crypto.h> # ifdef _ # undef _ # endif struct ui_method_st { char *name; /* * All the functions return 1 or non-NULL for success and 0 or NULL for * failure */ /* * Open whatever channel for this, be it the console, an X window or * whatever. This function should use the ex_data structure to save * intermediate data. */ int (*ui_open_session) (UI *ui); int (*ui_write_string) (UI *ui, UI_STRING *uis); /* * Flush the output. If a GUI dialog box is used, this function can be * used to actually display it. */ int (*ui_flush) (UI *ui); int (*ui_read_string) (UI *ui, UI_STRING *uis); int (*ui_close_session) (UI *ui); /* * Duplicate the ui_data that often comes alongside a ui_method. This * allows some backends to save away UI information for later use. */ void *(*ui_duplicate_data) (UI *ui, void *ui_data); void (*ui_destroy_data) (UI *ui, void *ui_data); /* * Construct a prompt in a user-defined manner. object_desc is a textual * short description of the object, for example "pass phrase", and * object_name is the name of the object (might be a card name or a file * name. The returned string shall always be allocated on the heap with * OPENSSL_malloc(), and need to be free'd with OPENSSL_free(). */ char *(*ui_construct_prompt) (UI *ui, const char *object_desc, const char *object_name); /* * UI_METHOD specific application data. */ CRYPTO_EX_DATA ex_data; }; struct ui_string_st { enum UI_string_types type; /* Input */ const char *out_string; /* Input */ int input_flags; /* Flags from the user */ /* * The following parameters are completely irrelevant for UIT_INFO, and * can therefore be set to 0 or NULL */ char *result_buf; /* Input and Output: If not NULL, * user-defined with size in result_maxsize. * Otherwise, it may be allocated by the UI * routine, meaning result_minsize is going * to be overwritten. */ size_t result_len; union { struct { int result_minsize; /* Input: minimum required size of the * result. */ int result_maxsize; /* Input: maximum permitted size of the * result */ const char *test_buf; /* Input: test string to verify against */ } string_data; struct { const char *action_desc; /* Input */ const char *ok_chars; /* Input */ const char *cancel_chars; /* Input */ } boolean_data; } _; # define OUT_STRING_FREEABLE 0x01 int flags; /* flags for internal use */ }; struct ui_st { const UI_METHOD *meth; STACK_OF(UI_STRING) *strings; /* We might want to prompt for more than * one thing at a time, and with different * echoing status. */ void *user_data; CRYPTO_EX_DATA ex_data; # define UI_FLAG_REDOABLE 0x0001 # define UI_FLAG_DUPL_DATA 0x0002 /* user_data was duplicated */ # define UI_FLAG_PRINT_ERRORS 0x0100 int flags; CRYPTO_RWLOCK *lock; }; #endif
3,862
34.118182
77
h
openssl
openssl-master/crypto/ui/ui_null.c
/* * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "ui_local.h" static const UI_METHOD ui_null = { "OpenSSL NULL UI", NULL, /* opener */ NULL, /* writer */ NULL, /* flusher */ NULL, /* reader */ NULL, /* closer */ NULL }; /* The method with all the built-in thingies */ const UI_METHOD *UI_null(void) { return &ui_null; }
761
27.222222
74
c
openssl
openssl-master/crypto/ui/ui_util.c
/* * Copyright 2002-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/pem.h> /* PEM_def_callback() */ #include "internal/thread_once.h" #include "ui_local.h" #ifndef BUFSIZ #define BUFSIZ 256 #endif int UI_UTIL_read_pw_string(char *buf, int length, const char *prompt, int verify) { char buff[BUFSIZ]; int ret; ret = UI_UTIL_read_pw(buf, buff, (length > BUFSIZ) ? BUFSIZ : length, prompt, verify); OPENSSL_cleanse(buff, BUFSIZ); return ret; } int UI_UTIL_read_pw(char *buf, char *buff, int size, const char *prompt, int verify) { int ok = -2; UI *ui; if (size < 1) return -1; ui = UI_new(); if (ui != NULL) { ok = UI_add_input_string(ui, prompt, 0, buf, 0, size - 1); if (ok >= 0 && verify) ok = UI_add_verify_string(ui, prompt, 0, buff, 0, size - 1, buf); if (ok >= 0) ok = UI_process(ui); UI_free(ui); } return ok; } /* * Wrapper around pem_password_cb, a method to help older APIs use newer * ones. */ struct pem_password_cb_data { pem_password_cb *cb; int rwflag; }; static void ui_new_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { /* * Do nothing, the data is allocated externally and assigned later with * CRYPTO_set_ex_data() */ } static int ui_dup_method_data(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from, void **pptr, int idx, long argl, void *argp) { if (*pptr != NULL) { *pptr = OPENSSL_memdup(*pptr, sizeof(struct pem_password_cb_data)); if (*pptr != NULL) return 1; } return 0; } static void ui_free_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { OPENSSL_free(ptr); } static CRYPTO_ONCE get_index_once = CRYPTO_ONCE_STATIC_INIT; static int ui_method_data_index = -1; DEFINE_RUN_ONCE_STATIC(ui_method_data_index_init) { ui_method_data_index = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI_METHOD, 0, NULL, ui_new_method_data, ui_dup_method_data, ui_free_method_data); return 1; } static int ui_open(UI *ui) { return 1; } static int ui_read(UI *ui, UI_STRING *uis) { switch (UI_get_string_type(uis)) { case UIT_PROMPT: { char result[PEM_BUFSIZE + 1]; const struct pem_password_cb_data *data = UI_method_get_ex_data(UI_get_method(ui), ui_method_data_index); int maxsize = UI_get_result_maxsize(uis); int len = data->cb(result, maxsize > PEM_BUFSIZE ? PEM_BUFSIZE : maxsize, data->rwflag, UI_get0_user_data(ui)); if (len >= 0) result[len] = '\0'; if (len < 0) return len; if (UI_set_result_ex(ui, uis, result, len) >= 0) return 1; return 0; } case UIT_VERIFY: case UIT_NONE: case UIT_BOOLEAN: case UIT_INFO: case UIT_ERROR: break; } return 1; } static int ui_write(UI *ui, UI_STRING *uis) { return 1; } static int ui_close(UI *ui) { return 1; } UI_METHOD *UI_UTIL_wrap_read_pem_callback(pem_password_cb *cb, int rwflag) { struct pem_password_cb_data *data = NULL; UI_METHOD *ui_method = NULL; if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL || (ui_method = UI_create_method("PEM password callback wrapper")) == NULL || UI_method_set_opener(ui_method, ui_open) < 0 || UI_method_set_reader(ui_method, ui_read) < 0 || UI_method_set_writer(ui_method, ui_write) < 0 || UI_method_set_closer(ui_method, ui_close) < 0 || !RUN_ONCE(&get_index_once, ui_method_data_index_init) || !UI_method_set_ex_data(ui_method, ui_method_data_index, data)) { UI_destroy_method(ui_method); OPENSSL_free(data); return NULL; } data->rwflag = rwflag; data->cb = cb != NULL ? cb : PEM_def_callback; return ui_method; }
4,640
27.29878
82
c
openssl
openssl-master/crypto/whrlpool/wp_dgst.c
/* * Copyright 2005-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /** * The Whirlpool hashing function. * * See * P.S.L.M. Barreto, V. Rijmen, * ``The Whirlpool hashing function,'' * NESSIE submission, 2000 (tweaked version, 2001), * <https://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/whirlpool.zip> * * Based on "@version 3.0 (2003.03.12)" by Paulo S.L.M. Barreto and * Vincent Rijmen. Lookup "reference implementations" on * <http://planeta.terra.com.br/informatica/paulobarreto/> * * ============================================================================= * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * OpenSSL-specific implementation notes. * * WHIRLPOOL_Update as well as one-stroke WHIRLPOOL both expect * number of *bytes* as input length argument. Bit-oriented routine * as specified by authors is called WHIRLPOOL_BitUpdate[!] and * does not have one-stroke counterpart. * * WHIRLPOOL_BitUpdate implements byte-oriented loop, essentially * to serve WHIRLPOOL_Update. This is done for performance. * * Unlike authors' reference implementation, block processing * routine whirlpool_block is designed to operate on multi-block * input. This is done for performance. */ /* * Whirlpool low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/crypto.h> #include "wp_local.h" #include <string.h> int WHIRLPOOL_Init(WHIRLPOOL_CTX *c) { memset(c, 0, sizeof(*c)); return 1; } int WHIRLPOOL_Update(WHIRLPOOL_CTX *c, const void *_inp, size_t bytes) { /* * Well, largest suitable chunk size actually is * (1<<(sizeof(size_t)*8-3))-64, but below number is large enough for not * to care about excessive calls to WHIRLPOOL_BitUpdate... */ size_t chunk = ((size_t)1) << (sizeof(size_t) * 8 - 4); const unsigned char *inp = _inp; while (bytes >= chunk) { WHIRLPOOL_BitUpdate(c, inp, chunk * 8); bytes -= chunk; inp += chunk; } if (bytes) WHIRLPOOL_BitUpdate(c, inp, bytes * 8); return 1; } void WHIRLPOOL_BitUpdate(WHIRLPOOL_CTX *c, const void *_inp, size_t bits) { size_t n; unsigned int bitoff = c->bitoff, bitrem = bitoff % 8, inpgap = (8 - (unsigned int)bits % 8) & 7; const unsigned char *inp = _inp; /* * This 256-bit increment procedure relies on the size_t being natural * size of CPU register, so that we don't have to mask the value in order * to detect overflows. */ c->bitlen[0] += bits; if (c->bitlen[0] < bits) { /* overflow */ n = 1; do { c->bitlen[n]++; } while (c->bitlen[n] == 0 && ++n < (WHIRLPOOL_COUNTER / sizeof(size_t))); } #ifndef OPENSSL_SMALL_FOOTPRINT reconsider: if (inpgap == 0 && bitrem == 0) { /* byte-oriented loop */ while (bits) { if (bitoff == 0 && (n = bits / WHIRLPOOL_BBLOCK)) { whirlpool_block(c, inp, n); inp += n * WHIRLPOOL_BBLOCK / 8; bits %= WHIRLPOOL_BBLOCK; } else { unsigned int byteoff = bitoff / 8; bitrem = WHIRLPOOL_BBLOCK - bitoff; /* re-use bitrem */ if (bits >= bitrem) { bits -= bitrem; bitrem /= 8; memcpy(c->data + byteoff, inp, bitrem); inp += bitrem; whirlpool_block(c, c->data, 1); bitoff = 0; } else { memcpy(c->data + byteoff, inp, bits / 8); bitoff += (unsigned int)bits; bits = 0; } c->bitoff = bitoff; } } } else /* bit-oriented loop */ #endif { /*- inp | +-------+-------+------- ||||||||||||||||||||| +-------+-------+------- +-------+-------+-------+-------+------- |||||||||||||| c->data +-------+-------+-------+-------+------- | c->bitoff/8 */ while (bits) { unsigned int byteoff = bitoff / 8; unsigned char b; #ifndef OPENSSL_SMALL_FOOTPRINT if (bitrem == inpgap) { c->data[byteoff++] |= inp[0] & (0xff >> inpgap); inpgap = 8 - inpgap; bitoff += inpgap; bitrem = 0; /* bitoff%8 */ bits -= inpgap; inpgap = 0; /* bits%8 */ inp++; if (bitoff == WHIRLPOOL_BBLOCK) { whirlpool_block(c, c->data, 1); bitoff = 0; } c->bitoff = bitoff; goto reconsider; } else #endif if (bits > 8) { b = ((inp[0] << inpgap) | (inp[1] >> (8 - inpgap))); b &= 0xff; if (bitrem) c->data[byteoff++] |= b >> bitrem; else c->data[byteoff++] = b; bitoff += 8; bits -= 8; inp++; if (bitoff >= WHIRLPOOL_BBLOCK) { whirlpool_block(c, c->data, 1); byteoff = 0; bitoff %= WHIRLPOOL_BBLOCK; } if (bitrem) c->data[byteoff] = b << (8 - bitrem); } else { /* remaining less than or equal to 8 bits */ b = (inp[0] << inpgap) & 0xff; if (bitrem) c->data[byteoff++] |= b >> bitrem; else c->data[byteoff++] = b; bitoff += (unsigned int)bits; if (bitoff == WHIRLPOOL_BBLOCK) { whirlpool_block(c, c->data, 1); byteoff = 0; bitoff %= WHIRLPOOL_BBLOCK; } if (bitrem) c->data[byteoff] = b << (8 - bitrem); bits = 0; } c->bitoff = bitoff; } } } int WHIRLPOOL_Final(unsigned char *md, WHIRLPOOL_CTX *c) { unsigned int bitoff = c->bitoff, byteoff = bitoff / 8; size_t i, j, v; unsigned char *p; bitoff %= 8; if (bitoff) c->data[byteoff] |= 0x80 >> bitoff; else c->data[byteoff] = 0x80; byteoff++; /* pad with zeros */ if (byteoff > (WHIRLPOOL_BBLOCK / 8 - WHIRLPOOL_COUNTER)) { if (byteoff < WHIRLPOOL_BBLOCK / 8) memset(&c->data[byteoff], 0, WHIRLPOOL_BBLOCK / 8 - byteoff); whirlpool_block(c, c->data, 1); byteoff = 0; } if (byteoff < (WHIRLPOOL_BBLOCK / 8 - WHIRLPOOL_COUNTER)) memset(&c->data[byteoff], 0, (WHIRLPOOL_BBLOCK / 8 - WHIRLPOOL_COUNTER) - byteoff); /* smash 256-bit c->bitlen in big-endian order */ p = &c->data[WHIRLPOOL_BBLOCK / 8 - 1]; /* last byte in c->data */ for (i = 0; i < WHIRLPOOL_COUNTER / sizeof(size_t); i++) for (v = c->bitlen[i], j = 0; j < sizeof(size_t); j++, v >>= 8) *p-- = (unsigned char)(v & 0xff); whirlpool_block(c, c->data, 1); if (md) { memcpy(md, c->H.c, WHIRLPOOL_DIGEST_LENGTH); OPENSSL_cleanse(c, sizeof(*c)); return 1; } return 0; } unsigned char *WHIRLPOOL(const void *inp, size_t bytes, unsigned char *md) { WHIRLPOOL_CTX ctx; static unsigned char m[WHIRLPOOL_DIGEST_LENGTH]; if (md == NULL) md = m; WHIRLPOOL_Init(&ctx); WHIRLPOOL_Update(&ctx, inp, bytes); WHIRLPOOL_Final(md, &ctx); return md; }
8,830
32.324528
89
c