int SM2_decrypt(const unsigned char *in, size_t inlen, unsigned char *out, size_t *outlen, EC_KEY *ec_key) { const EVP_MD *kdf_md = EVP_sm3(); const EVP_MD *mac_md = EVP_sm3(); point_conversion_form_t point_form = SM2_DEFAULT_POINT_CONVERSION_FORM; return SM2_decrypt_ex(kdf_md, mac_md, point_form, in, inlen, out, outlen, ec_key); }
KDF_FUNC KDF_get_x9_63(const EVP_MD *md) { if (md == EVP_md5()) { return x963_md5kdf; } else if (md == EVP_ripemd160()) { return x963_rmd160kdf; } else if (md == EVP_sha1()) { return x963_sha1kdf; } else if (md == EVP_sha224()) { return x963_sha224kdf; } else if (md == EVP_sha256()) { return x963_sha256kdf; } else if (md == EVP_sha384()) { return x963_sha384kdf; } else if (md == EVP_sha512()) { return x963_sha512kdf; } else if (md == EVP_whirlpool()) { return x963_whirlpoolkdf; } else if (md == EVP_sm3()) { return x963_sm3kdf; } return NULL; }
static int pkey_ec_verifyctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx) { int ret = 0; EC_PKEY_CTX *dctx = ctx->data; EC_KEY *ec_key = ctx->pkey->pkey.ec; const EVP_MD *md = EVP_sm3(); // FIXME: we need to get md from somewhere unsigned char zid[EVP_MAX_MD_SIZE]; unsigned int zidlen; if (dctx->sign_type == NID_sm2sign) { zidlen = sizeof(zid); if (!SM2_compute_id_digest(md, zid, &zidlen, ec_key)) { goto end; } if (!mctx->update(mctx, zid, zidlen)) { goto end; } } ret = 1; end: return ret; }
static int test_sm2_enc(void) { int rv; EC_KEY *ec_key = NULL; char *msg = "Hello world!"; SM2_CIPHERTEXT_VALUE *cv = NULL; unsigned char ctbuf[512]; unsigned char ptbuf[512]; size_t len, len2; BIO *bio = BIO_new_fp(stdout, BIO_NOCLOSE); ec_key = EC_KEY_new_by_curve_name(NID_sm2p256v1); OPENSSL_assert(ec_key); rv = EC_KEY_generate_key(ec_key); OPENSSL_assert(rv == 1); cv = SM2_do_encrypt(EVP_sm3(), EVP_sm3(), (unsigned char *)msg, (size_t)strlen(msg), ec_key); OPENSSL_assert(cv); SM2_CIPHERTEXT_VALUE_print(bio, EC_KEY_get0_group(ec_key), cv, 0, 0); bzero(ptbuf, sizeof(ptbuf)); len = sizeof(ptbuf); rv = SM2_do_decrypt(EVP_sm3(), EVP_sm3(), cv, ptbuf, &len, ec_key); OPENSSL_assert(rv == 1); len = sizeof(ctbuf); rv = SM2_encrypt(EVP_sm3(), EVP_sm3(), SM2_DEFAULT_POINT_CONVERSION_FORM, (unsigned char *)msg, (size_t)strlen(msg), ctbuf, &len, ec_key); OPENSSL_assert(rv == 1); bzero(ptbuf, sizeof(ptbuf)); len2 = sizeof(ptbuf); rv = SM2_decrypt(EVP_sm3(), EVP_sm3(), SM2_DEFAULT_POINT_CONVERSION_FORM, ctbuf, len, ptbuf, &len2, ec_key); OPENSSL_assert(rv == 1); /* printf("original plaintext: %s\n", msg); printf("decrypted plaintext: %s\n", ptbuf); */ printf("%s() success\n", __FUNCTION__); return 0; }
void openssl_add_all_digests_int(void) { #ifndef OPENSSL_NO_MD4 EVP_add_digest(EVP_md4()); #endif #ifndef OPENSSL_NO_MD5 EVP_add_digest(EVP_md5()); EVP_add_digest_alias(SN_md5, "ssl3-md5"); EVP_add_digest(EVP_md5_sha1()); #endif EVP_add_digest(EVP_sha1()); EVP_add_digest_alias(SN_sha1, "ssl3-sha1"); EVP_add_digest_alias(SN_sha1WithRSAEncryption, SN_sha1WithRSA); #if !defined(OPENSSL_NO_MDC2) && !defined(OPENSSL_NO_DES) EVP_add_digest(EVP_mdc2()); #endif #ifndef OPENSSL_NO_RMD160 EVP_add_digest(EVP_ripemd160()); EVP_add_digest_alias(SN_ripemd160, "ripemd"); EVP_add_digest_alias(SN_ripemd160, "rmd160"); #endif EVP_add_digest(EVP_sha224()); EVP_add_digest(EVP_sha256()); EVP_add_digest(EVP_sha384()); EVP_add_digest(EVP_sha512()); EVP_add_digest(EVP_sha512_224()); EVP_add_digest(EVP_sha512_256()); #ifndef OPENSSL_NO_WHIRLPOOL EVP_add_digest(EVP_whirlpool()); #endif #ifndef OPENSSL_NO_SM3 EVP_add_digest(EVP_sm3()); #endif #ifndef OPENSSL_NO_BLAKE2 EVP_add_digest(EVP_blake2b512()); EVP_add_digest(EVP_blake2s256()); #endif EVP_add_digest(EVP_sha3_224()); EVP_add_digest(EVP_sha3_256()); EVP_add_digest(EVP_sha3_384()); EVP_add_digest(EVP_sha3_512()); EVP_add_digest(EVP_shake128()); EVP_add_digest(EVP_shake256()); }
static int pkey_ec_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx) { EC_PKEY_CTX *dctx = ctx->data; EC_KEY *ec_key = ctx->pkey->pkey.ec; const EVP_MD *md = EVP_sm3(); unsigned char zid[EVP_MAX_MD_SIZE]; unsigned int zidlen = sizeof(zid); if (dctx->sign_type == NID_sm2sign) { if (!SM2_compute_id_digest(md, zid, &zidlen, ec_key)) { ECerr(EC_F_PKEY_SM2_SIGNCTX_INIT, ERR_R_SM2_LIB); return 0; } if (!mctx->update(mctx, zid, zidlen)) { ECerr(EC_F_PKEY_SM2_SIGNCTX_INIT, ERR_R_EVP_LIB); return 0; } } return 1; }
static void *x963_sm3kdf(const void *in, size_t inlen, void *out, size_t *outlen) { return x963_kdf(EVP_sm3(), in, inlen, out, outlen); }
int main() { int ret = -1; int verbose = 0; BIO *out = NULL; int id = EVP_PKEY_SM2; const EVP_MD *md = EVP_sm3(); ENGINE *engine = NULL; EVP_PKEY_CTX *pkctx = NULL; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mdctx = NULL; EVP_CIPHER_CTX *cpctx = NULL; unsigned char dgst[EVP_MAX_MD_SIZE] = "hello world"; size_t dgstlen = 32; unsigned char sig[256]; size_t siglen = sizeof(sig); unsigned char msg[] = "hello world this is the message"; size_t msglen = sizeof(msg); unsigned char cbuf[512]; size_t cbuflen = sizeof(cbuf); unsigned char mbuf[512]; size_t mbuflen = sizeof(mbuf); int len; unsigned int ulen; ERR_load_crypto_strings(); out = BIO_new_fp(stdout, BIO_NOCLOSE); if (!(pkctx = EVP_PKEY_CTX_new_id(id, engine))) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (!EVP_PKEY_keygen_init(pkctx)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (!EVP_PKEY_keygen(pkctx, &pkey)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } EVP_PKEY_CTX_free(pkctx); if (0) { EVP_PKEY_print_public(out, pkey, 4, NULL); BIO_printf(out, "\n"); EVP_PKEY_print_private(out, pkey, 4, NULL); BIO_printf(out, "\n"); } if (!(pkctx = EVP_PKEY_CTX_new(pkey, engine))) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } /* EVP_PKEY_sign() */ if (!EVP_PKEY_sign_init(pkctx)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } bzero(sig, sizeof(sig)); siglen = sizeof(sig); dgstlen = 32; if (!EVP_PKEY_sign(pkctx, sig, &siglen, dgst, dgstlen)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (verbose) { size_t i; printf("signature (%zu bytes) = ", siglen); for (i = 0; i < siglen; i++) { printf("%02X", sig[i]); } printf("\n"); } if (!EVP_PKEY_verify_init(pkctx)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (EVP_PKEY_verify(pkctx, sig, siglen, dgst, dgstlen) != SM2_VERIFY_SUCCESS) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (verbose) { printf("signature verification success!\n"); } /* EVP_PKEY_encrypt() */ if (!EVP_PKEY_encrypt_init(pkctx)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } cbuflen = sizeof(cbuf); if (!EVP_PKEY_encrypt(pkctx, cbuf, &cbuflen, msg, msglen)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (verbose) { size_t i; printf("ciphertext (%zu bytes) = ", cbuflen); for (i = 0; i < cbuflen; i++) { printf("%02X", cbuf[i]); } printf("\n"); } if (!EVP_PKEY_decrypt_init(pkctx)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } bzero(mbuf, sizeof(mbuf)); mbuflen = sizeof(mbuf); if (!EVP_PKEY_decrypt(pkctx, mbuf, &mbuflen, cbuf, cbuflen)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (verbose) { printf("original message = %s\n", msg); printf("decrypted message = %s\n", mbuf); } /* EVP_PKEY_encrypt_old */ if ((len = EVP_PKEY_encrypt_old(cbuf, msg, (int)msglen, pkey)) <= 0) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (verbose) { int i; printf("ciphertext (%d bytes) = ", len); for (i = 0; i < len; i++) { printf("%02X", cbuf[i]); } printf("\n"); } bzero(mbuf, sizeof(mbuf)); if ((len = EVP_PKEY_decrypt_old(mbuf, cbuf, len, pkey)) <= 0) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (verbose) { printf("original message = %s\n", msg); printf("decrypted message = %s\n", mbuf); } if (!(mdctx = EVP_MD_CTX_create())) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } /* EVP_SignInit_ex/Update/Final_ex */ if (!EVP_SignInit_ex(mdctx, EVP_sm3(), engine)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (!EVP_SignUpdate(mdctx, msg, msglen)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (!EVP_SignFinal(mdctx, sig, &ulen, pkey)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } siglen = ulen; if (verbose) { size_t i; printf("signature (%zu bytes) = ", siglen); for (i = 0; i < siglen; i++) { printf("%02X", sig[i]); } printf("\n"); } if (!EVP_VerifyInit_ex(mdctx, EVP_sm3(), engine)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (!EVP_VerifyUpdate(mdctx, msg, msglen)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (EVP_VerifyFinal(mdctx, sig, ulen, pkey) != SM2_VERIFY_SUCCESS) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } /* EVP_DigestSignInit/Update/Final() */ // FIXME: return values might be different, not just 1 or 0 if (!EVP_DigestSignInit(mdctx, &pkctx, md, engine, pkey)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (!EVP_DigestSignUpdate(mdctx, msg, msglen)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } siglen = sizeof(sig); if (!EVP_DigestSignFinal(mdctx, sig, &siglen)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } pkctx = NULL; if (!EVP_DigestVerifyInit(mdctx, &pkctx, md, engine, pkey)) { ERR_print_errors_fp(stderr); fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (!EVP_DigestVerifyUpdate(mdctx, msg, msglen)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } if (!EVP_DigestVerifyFinal(mdctx, sig, siglen)) { fprintf(stderr, "error: %s %d\n", __FILE__, __LINE__); goto end; } /* EVP_SealInit/Update/Final() EVP_OpenInit/Update/Final() */ /* EVP_PKEY *pk[NUM_PKEYS] = {0}; unsigned char iv[16]; unsigned char ek[NUM_PKEYS][256]; int eklen[NUM_PKEYS]; RAND_pseudo_bytes(iv, sizeof(iv)); int i; for (i = 0; i < NUM_PKEYS; i++) { } if (!(cpctx = EVP_CIPHER_CTX_new())) { goto end; } if (!EVP_SealInit(cpctx, cipher, ek, &ekl, iv, pubk, npubk)) { goto end; } if (!EVP_SealUpdate(cpctx, msg, msglen)) { goto end; } if (!EVP_SealFinal(cpctx, cbuf, (int *)&cbuflen)) { goto end; } */ printf("test success!\n"); ret = 1; end: ERR_print_errors_fp(stderr); return ret; }
int SSL_library_init(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_cbc()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); # if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__)) EVP_add_cipher(EVP_rc4_hmac_md5()); # endif #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_cbc()); /* * Not actually used for SSL/TLS but this makes PKCS#12 work if an * application only calls SSL_library_init(). */ EVP_add_cipher(EVP_rc2_40_cbc()); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_128_gcm()); EVP_add_cipher(EVP_aes_256_gcm()); # if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1()); # endif # if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA256) EVP_add_cipher(EVP_aes_128_cbc_hmac_sha256()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha256()); # endif #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_256_cbc()); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_cbc()); #endif #ifndef OPENSSL_NO_MD5 EVP_add_digest(EVP_md5()); EVP_add_digest_alias(SN_md5, "ssl2-md5"); EVP_add_digest_alias(SN_md5, "ssl3-md5"); #endif #ifndef OPENSSL_NO_SHA EVP_add_digest(EVP_sha1()); /* RSA with sha1 */ EVP_add_digest_alias(SN_sha1, "ssl3-sha1"); EVP_add_digest_alias(SN_sha1WithRSAEncryption, SN_sha1WithRSA); #endif #ifndef OPENSSL_NO_SHA256 EVP_add_digest(EVP_sha224()); EVP_add_digest(EVP_sha256()); #endif #ifndef OPENSSL_NO_SHA512 EVP_add_digest(EVP_sha384()); EVP_add_digest(EVP_sha512()); #endif #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA) EVP_add_digest(EVP_dss1()); /* DSA with sha1 */ EVP_add_digest_alias(SN_dsaWithSHA1, SN_dsaWithSHA1_2); EVP_add_digest_alias(SN_dsaWithSHA1, "DSS1"); EVP_add_digest_alias(SN_dsaWithSHA1, "dss1"); #endif #ifndef OPENSSL_NO_ECDSA EVP_add_digest(EVP_ecdsa()); #endif #ifndef NO_GMSSL EVP_add_cipher(EVP_sms4_cbc()); EVP_add_digest(EVP_sm3()); #endif /* If you want support for phased out ciphers, add the following */ #if 0 EVP_add_digest(EVP_sha()); EVP_add_digest(EVP_dss()); #endif #ifndef OPENSSL_NO_COMP /* * This will initialise the built-in compression algorithms. The value * returned is a STACK_OF(SSL_COMP), but that can be discarded safely */ (void)SSL_COMP_get_compression_methods(); #endif /* initialize cipher/digest methods table */ ssl_load_ciphers(); return (1); }
static int test_EVP_SM2(void) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_PKEY *params = NULL; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY_CTX *kctx = NULL; EVP_PKEY_CTX *sctx = NULL; size_t sig_len = 0; unsigned char *sig = NULL; EVP_MD_CTX *md_ctx = NULL; EVP_MD_CTX *md_ctx_verify = NULL; EVP_PKEY_CTX *cctx = NULL; uint8_t ciphertext[128]; size_t ctext_len = sizeof(ciphertext); uint8_t plaintext[8]; size_t ptext_len = sizeof(plaintext); uint8_t sm2_id[] = {1, 2, 3, 4, 'l', 'e', 't', 't', 'e', 'r'}; pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL); if (!TEST_ptr(pctx)) goto done; if (!TEST_true(EVP_PKEY_paramgen_init(pctx) == 1)) goto done; if (!TEST_true(EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_sm2))) goto done; if (!TEST_true(EVP_PKEY_paramgen(pctx, ¶ms))) goto done; kctx = EVP_PKEY_CTX_new(params, NULL); if (!TEST_ptr(kctx)) goto done; if (!TEST_true(EVP_PKEY_keygen_init(kctx))) goto done; if (!TEST_true(EVP_PKEY_keygen(kctx, &pkey))) goto done; if (!TEST_true(EVP_PKEY_set_alias_type(pkey, EVP_PKEY_SM2))) goto done; if (!TEST_ptr(md_ctx = EVP_MD_CTX_new())) goto done; if (!TEST_ptr(md_ctx_verify = EVP_MD_CTX_new())) goto done; if (!TEST_ptr(sctx = EVP_PKEY_CTX_new(pkey, NULL))) goto done; EVP_MD_CTX_set_pkey_ctx(md_ctx, sctx); EVP_MD_CTX_set_pkey_ctx(md_ctx_verify, sctx); if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(sctx, sm2_id, sizeof(sm2_id)), 0)) goto done; if (!TEST_true(EVP_DigestSignInit(md_ctx, NULL, EVP_sm3(), NULL, pkey))) goto done; if(!TEST_true(EVP_DigestSignUpdate(md_ctx, kMsg, sizeof(kMsg)))) goto done; /* Determine the size of the signature. */ if (!TEST_true(EVP_DigestSignFinal(md_ctx, NULL, &sig_len))) goto done; if (!TEST_size_t_eq(sig_len, (size_t)EVP_PKEY_size(pkey))) goto done; if (!TEST_ptr(sig = OPENSSL_malloc(sig_len))) goto done; if (!TEST_true(EVP_DigestSignFinal(md_ctx, sig, &sig_len))) goto done; /* Ensure that the signature round-trips. */ if (!TEST_true(EVP_DigestVerifyInit(md_ctx_verify, NULL, EVP_sm3(), NULL, pkey))) goto done; if (!TEST_true(EVP_DigestVerifyUpdate(md_ctx_verify, kMsg, sizeof(kMsg)))) goto done; if (!TEST_true(EVP_DigestVerifyFinal(md_ctx_verify, sig, sig_len))) goto done; /* now check encryption/decryption */ if (!TEST_ptr(cctx = EVP_PKEY_CTX_new(pkey, NULL))) goto done; if (!TEST_true(EVP_PKEY_encrypt_init(cctx))) goto done; if (!TEST_true(EVP_PKEY_encrypt(cctx, ciphertext, &ctext_len, kMsg, sizeof(kMsg)))) goto done; if (!TEST_true(EVP_PKEY_decrypt_init(cctx))) goto done; if (!TEST_true(EVP_PKEY_decrypt(cctx, plaintext, &ptext_len, ciphertext, ctext_len))) goto done; if (!TEST_true(ptext_len == sizeof(kMsg))) goto done; if (!TEST_true(memcmp(plaintext, kMsg, sizeof(kMsg)) == 0)) goto done; ret = 1; done: EVP_PKEY_CTX_free(pctx); EVP_PKEY_CTX_free(kctx); EVP_PKEY_CTX_free(sctx); EVP_PKEY_CTX_free(cctx); EVP_PKEY_free(pkey); EVP_PKEY_free(params); EVP_MD_CTX_free(md_ctx); EVP_MD_CTX_free(md_ctx_verify); OPENSSL_free(sig); return ret; }
static int test_EVP_SM2_verify(void) { /* From https://tools.ietf.org/html/draft-shen-sm2-ecdsa-02#appendix-A */ const char *pubkey = "-----BEGIN PUBLIC KEY-----\n" "MIIBMzCB7AYHKoZIzj0CATCB4AIBATAsBgcqhkjOPQEBAiEAhULWnkwETxjouSQ1\n" "v2/33kVyg5FcRVF9ci7biwjx38MwRAQgeHlotPoyw/0kF4Quc7v+/y88hItoMdfg\n" "7GUiizk35JgEIGPkxtOyOwyEnPhCQUhL/kj2HVmlsWugbm4S0donxSSaBEEEQh3r\n" "1hti6rZ0ZDTrw8wxXjIiCzut1QvcTE5sFH/t1D0GgFEry7QsB9RzSdIVO3DE5df9\n" "/L+jbqGoWEG55G4JogIhAIVC1p5MBE8Y6LkkNb9v990pdyBjBIVijVrnTufDLnm3\n" "AgEBA0IABArkx3mKoPEZRxvuEYJb5GICu3nipYRElel8BP9N8lSKfAJA+I8c1OFj\n" "Uqc8F7fxbwc1PlOhdtaEqf4Ma7eY6Fc=\n" "-----END PUBLIC KEY-----\n"; const char *msg = "message digest"; const char *id = "*****@*****.**"; const uint8_t signature[] = { 0x30, 0x44, 0x02, 0x20, 0x40, 0xF1, 0xEC, 0x59, 0xF7, 0x93, 0xD9, 0xF4, 0x9E, 0x09, 0xDC, 0xEF, 0x49, 0x13, 0x0D, 0x41, 0x94, 0xF7, 0x9F, 0xB1, 0xEE, 0xD2, 0xCA, 0xA5, 0x5B, 0xAC, 0xDB, 0x49, 0xC4, 0xE7, 0x55, 0xD1, 0x02, 0x20, 0x6F, 0xC6, 0xDA, 0xC3, 0x2C, 0x5D, 0x5C, 0xF1, 0x0C, 0x77, 0xDF, 0xB2, 0x0F, 0x7C, 0x2E, 0xB6, 0x67, 0xA4, 0x57, 0x87, 0x2F, 0xB0, 0x9E, 0xC5, 0x63, 0x27, 0xA6, 0x7E, 0xC7, 0xDE, 0xEB, 0xE7 }; int rc = 0; BIO *bio = NULL; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX *pctx = NULL; bio = BIO_new_mem_buf(pubkey, strlen(pubkey)); if (!TEST_true(bio != NULL)) goto done; pkey = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL); if (!TEST_true(pkey != NULL)) goto done; if (!TEST_true(EVP_PKEY_set_alias_type(pkey, EVP_PKEY_SM2))) goto done; if (!TEST_ptr(mctx = EVP_MD_CTX_new())) goto done; if (!TEST_ptr(pctx = EVP_PKEY_CTX_new(pkey, NULL))) goto done; if (!TEST_int_gt(EVP_PKEY_CTX_set1_id(pctx, (const uint8_t *)id, strlen(id)), 0)) goto done; EVP_MD_CTX_set_pkey_ctx(mctx, pctx); if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, EVP_sm3(), NULL, pkey))) goto done; if (!TEST_true(EVP_DigestVerifyUpdate(mctx, msg, strlen(msg)))) goto done; if (!TEST_true(EVP_DigestVerifyFinal(mctx, signature, sizeof(signature)))) goto done; rc = 1; done: BIO_free(bio); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pctx); EVP_MD_CTX_free(mctx); return rc; }
int MAIN(int argc, char **argv) { static const char magic[] = "Salted__"; char mbuf[sizeof magic - 1]; char *strbuf = NULL; unsigned char *buff = NULL, *bufsize = NULL; int bsize = BSIZE, verbose = 0; int ret = 1, inl; int nopad = 0; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char salt[PKCS5_SALT_LEN]; char *str = NULL, *passarg = NULL, *pass = NULL; char *hkey = NULL, *hiv = NULL, *hsalt = NULL; char *md = NULL; int enc = 1, printkey = 0, i, base64 = 0; #ifdef ZLIB int do_zlib = 0; BIO *bzl = NULL; #endif int debug = 0, olb64 = 0, nosalt = 0; const EVP_CIPHER *cipher = NULL, *c; EVP_CIPHER_CTX *ctx = NULL; char *inf = NULL, *outf = NULL; BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio = NULL, *wbio = NULL; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE + 1]; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; #endif const EVP_MD *dgst = NULL; int non_fips_allow = 0; apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; /* first check the program name */ program_name(argv[0], pname, sizeof pname); if (strcmp(pname, "base64") == 0) base64 = 1; #ifdef ZLIB if (strcmp(pname, "zlib") == 0) do_zlib = 1; #endif cipher = EVP_get_cipherbyname(pname); #ifdef ZLIB if (!do_zlib && !base64 && (cipher == NULL) && (strcmp(pname, "enc") != 0)) #else if (!base64 && (cipher == NULL) && (strcmp(pname, "enc") != 0)) #endif { BIO_printf(bio_err, "%s is an unknown cipher\n", pname); goto bad; } argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-e") == 0) enc = 1; else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; inf = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outf = *(++argv); } else if (strcmp(*argv, "-pass") == 0) { if (--argc < 1) goto bad; passarg = *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } #endif else if (strcmp(*argv, "-d") == 0) enc = 0; else if (strcmp(*argv, "-p") == 0) printkey = 1; else if (strcmp(*argv, "-v") == 0) verbose = 1; else if (strcmp(*argv, "-nopad") == 0) nopad = 1; else if (strcmp(*argv, "-salt") == 0) nosalt = 0; else if (strcmp(*argv, "-nosalt") == 0) nosalt = 1; else if (strcmp(*argv, "-debug") == 0) debug = 1; else if (strcmp(*argv, "-P") == 0) printkey = 2; else if (strcmp(*argv, "-A") == 0) olb64 = 1; else if (strcmp(*argv, "-a") == 0) base64 = 1; else if (strcmp(*argv, "-base64") == 0) base64 = 1; #ifdef ZLIB else if (strcmp(*argv, "-z") == 0) do_zlib = 1; #endif else if (strcmp(*argv, "-bufsize") == 0) { if (--argc < 1) goto bad; bufsize = (unsigned char *)*(++argv); } else if (strcmp(*argv, "-k") == 0) { if (--argc < 1) goto bad; str = *(++argv); } else if (strcmp(*argv, "-kfile") == 0) { static char buf[128]; FILE *infile; char *file; if (--argc < 1) goto bad; file = *(++argv); infile = fopen(file, "r"); if (infile == NULL) { BIO_printf(bio_err, "unable to read key from '%s'\n", file); goto bad; } buf[0] = '\0'; if (!fgets(buf, sizeof buf, infile)) { BIO_printf(bio_err, "unable to read key from '%s'\n", file); goto bad; } fclose(infile); i = strlen(buf); if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if (i < 1) { BIO_printf(bio_err, "zero length password\n"); goto bad; } str = buf; } else if (strcmp(*argv, "-K") == 0) { if (--argc < 1) goto bad; hkey = *(++argv); } else if (strcmp(*argv, "-S") == 0) { if (--argc < 1) goto bad; hsalt = *(++argv); } else if (strcmp(*argv, "-iv") == 0) { if (--argc < 1) goto bad; hiv = *(++argv); } else if (strcmp(*argv, "-md") == 0) { if (--argc < 1) goto bad; md = *(++argv); } else if (strcmp(*argv, "-non-fips-allow") == 0) non_fips_allow = 1; else if ((argv[0][0] == '-') && ((c = EVP_get_cipherbyname(&(argv[0][1]))) != NULL)) { cipher = c; } else if (strcmp(*argv, "-none") == 0) cipher = NULL; else { BIO_printf(bio_err, "unknown option '%s'\n", *argv); bad: BIO_printf(bio_err, "options are\n"); BIO_printf(bio_err, "%-14s input file\n", "-in <file>"); BIO_printf(bio_err, "%-14s output file\n", "-out <file>"); BIO_printf(bio_err, "%-14s pass phrase source\n", "-pass <arg>"); BIO_printf(bio_err, "%-14s encrypt\n", "-e"); BIO_printf(bio_err, "%-14s decrypt\n", "-d"); BIO_printf(bio_err, "%-14s base64 encode/decode, depending on encryption flag\n", "-a/-base64"); BIO_printf(bio_err, "%-14s passphrase is the next argument\n", "-k"); BIO_printf(bio_err, "%-14s passphrase is the first line of the file argument\n", "-kfile"); BIO_printf(bio_err, "%-14s the next argument is the md to use to create a key\n", "-md"); BIO_printf(bio_err, "%-14s from a passphrase. One of md2, md5, sha or sha1\n", ""); BIO_printf(bio_err, "%-14s salt in hex is the next argument\n", "-S"); BIO_printf(bio_err, "%-14s key/iv in hex is the next argument\n", "-K/-iv"); BIO_printf(bio_err, "%-14s print the iv/key (then exit if -P)\n", "-[pP]"); BIO_printf(bio_err, "%-14s buffer size\n", "-bufsize <n>"); BIO_printf(bio_err, "%-14s disable standard block padding\n", "-nopad"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, "%-14s use engine e, possibly a hardware device.\n", "-engine e"); #endif BIO_printf(bio_err, "Cipher Types\n"); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, show_ciphers, bio_err); BIO_printf(bio_err, "\n"); goto end; } argc--; argv++; } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif if (cipher && EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) { BIO_printf(bio_err, "AEAD ciphers not supported by the enc utility\n"); goto end; } if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)) { BIO_printf(bio_err, "Ciphers in XTS mode are not supported by the enc utility\n"); goto end; } if (md && (dgst = EVP_get_digestbyname(md)) == NULL) { BIO_printf(bio_err, "%s is an unsupported message digest type\n", md); goto end; } if (dgst == NULL) { #ifndef OPENSSL_NO_GMSSL dgst = EVP_sm3(); #else dgst = EVP_md5(); #endif } if (bufsize != NULL) { unsigned long n; for (n = 0; *bufsize; bufsize++) { i = *bufsize; if ((i <= '9') && (i >= '0')) n = n * 10 + i - '0'; else if (i == 'k') { n *= 1024; bufsize++; break; } } if (*bufsize != '\0') { BIO_printf(bio_err, "invalid 'bufsize' specified.\n"); goto end; } /* It must be large enough for a base64 encoded line */ if (base64 && n < 80) n = 80; bsize = (int)n; if (verbose) BIO_printf(bio_err, "bufsize=%d\n", bsize); } strbuf = OPENSSL_malloc(SIZE); buff = (unsigned char *)OPENSSL_malloc(EVP_ENCODE_LENGTH(bsize)); if ((buff == NULL) || (strbuf == NULL)) { BIO_printf(bio_err, "OPENSSL_malloc failure %ld\n", (long)EVP_ENCODE_LENGTH(bsize)); goto end; } in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(in, BIO_debug_callback); BIO_set_callback(out, BIO_debug_callback); BIO_set_callback_arg(in, (char *)bio_err); BIO_set_callback_arg(out, (char *)bio_err); } if (inf == NULL) { #ifndef OPENSSL_NO_SETVBUF_IONBF if (bufsize != NULL) setvbuf(stdin, (char *)NULL, _IONBF, 0); #endif /* ndef OPENSSL_NO_SETVBUF_IONBF */ BIO_set_fp(in, stdin, BIO_NOCLOSE); } else { if (BIO_read_filename(in, inf) <= 0) { perror(inf); goto end; } } if (!str && passarg) { if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } str = pass; } if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) { for (;;) { char buf[200]; BIO_snprintf(buf, sizeof buf, "enter %s %s password:"******"encryption" : "decryption"); strbuf[0] = '\0'; i = EVP_read_pw_string((char *)strbuf, SIZE, buf, enc); if (i == 0) { if (strbuf[0] == '\0') { ret = 1; goto end; } str = strbuf; break; } if (i < 0) { BIO_printf(bio_err, "bad password read\n"); goto end; } } } if (outf == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); #ifndef OPENSSL_NO_SETVBUF_IONBF if (bufsize != NULL) setvbuf(stdout, (char *)NULL, _IONBF, 0); #endif /* ndef OPENSSL_NO_SETVBUF_IONBF */ #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { if (BIO_write_filename(out, outf) <= 0) { perror(outf); goto end; } } rbio = in; wbio = out; #ifdef ZLIB if (do_zlib) { if ((bzl = BIO_new(BIO_f_zlib())) == NULL) goto end; if (enc) wbio = BIO_push(bzl, wbio); else rbio = BIO_push(bzl, rbio); } #endif if (base64) { if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; if (debug) { BIO_set_callback(b64, BIO_debug_callback); BIO_set_callback_arg(b64, (char *)bio_err); } if (olb64) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); if (enc) wbio = BIO_push(b64, wbio); else rbio = BIO_push(b64, rbio); } if (cipher != NULL) { /* * Note that str is NULL if a key was passed on the command line, so * we get no salt in that case. Is this a bug? */ if (str != NULL) { /* * Salt handling: if encrypting generate a salt and write to * output BIO. If decrypting read salt from input BIO. */ unsigned char *sptr; if (nosalt) sptr = NULL; else { if (enc) { if (hsalt) { if (!set_hex(hsalt, salt, sizeof salt)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } } else if (RAND_pseudo_bytes(salt, sizeof salt) < 0) goto end; /* * If -P option then don't bother writing */ if ((printkey != 2) && (BIO_write(wbio, magic, sizeof magic - 1) != sizeof magic - 1 || BIO_write(wbio, (char *)salt, sizeof salt) != sizeof salt)) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf || BIO_read(rbio, (unsigned char *)salt, sizeof salt) != sizeof salt) { BIO_printf(bio_err, "error reading input file\n"); goto end; } else if (memcmp(mbuf, magic, sizeof magic - 1)) { BIO_printf(bio_err, "bad magic number\n"); goto end; } sptr = salt; } EVP_BytesToKey(cipher, dgst, sptr, (unsigned char *)str, strlen(str), 1, key, iv); /* * zero the complete buffer or the string passed from the command * line bug picked up by Larry J. Hughes Jr. <*****@*****.**> */ if (str == strbuf) OPENSSL_cleanse(str, SIZE); else OPENSSL_cleanse(str, strlen(str)); } if (hiv != NULL) { int siz = EVP_CIPHER_iv_length(cipher); if (siz == 0) { BIO_printf(bio_err, "warning: iv not use by this cipher\n"); } else if (!set_hex(hiv, iv, sizeof iv)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } } if ((hiv == NULL) && (str == NULL) && EVP_CIPHER_iv_length(cipher) != 0) { /* * No IV was explicitly set and no IV was generated during * EVP_BytesToKey. Hence the IV is undefined, making correct * decryption impossible. */ BIO_printf(bio_err, "iv undefined\n"); goto end; } if ((hkey != NULL) && !set_hex(hkey, key, EVP_CIPHER_key_length(cipher))) { BIO_printf(bio_err, "invalid hex key value\n"); goto end; } if ((benc = BIO_new(BIO_f_cipher())) == NULL) goto end; /* * Since we may be changing parameters work on the encryption context * rather than calling BIO_set_cipher(). */ BIO_get_cipher_ctx(benc, &ctx); if (non_fips_allow) EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_NON_FIPS_ALLOW); if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (nopad) EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(benc, BIO_debug_callback); BIO_set_callback_arg(benc, (char *)bio_err); } if (printkey) { if (!nosalt) { printf("salt="); for (i = 0; i < (int)sizeof(salt); i++) printf("%02X", salt[i]); printf("\n"); } if (cipher->key_len > 0) { printf("key="); for (i = 0; i < cipher->key_len; i++) printf("%02X", key[i]); printf("\n"); } if (cipher->iv_len > 0) { printf("iv ="); for (i = 0; i < cipher->iv_len; i++) printf("%02X", iv[i]); printf("\n"); } if (printkey == 2) { ret = 0; goto end; } } } /* Only encrypt/decrypt as we write the file */ if (benc != NULL) wbio = BIO_push(benc, wbio); for (;;) { inl = BIO_read(rbio, (char *)buff, bsize); if (inl <= 0) break; if (BIO_write(wbio, (char *)buff, inl) != inl) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } if (!BIO_flush(wbio)) { BIO_printf(bio_err, "bad decrypt\n"); goto end; } ret = 0; if (verbose) { BIO_printf(bio_err, "bytes read :%8ld\n", BIO_number_read(in)); BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out)); } end: ERR_print_errors(bio_err); if (strbuf != NULL) OPENSSL_free(strbuf); if (buff != NULL) OPENSSL_free(buff); if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (benc != NULL) BIO_free(benc); if (b64 != NULL) BIO_free(b64); #ifdef ZLIB if (bzl != NULL) BIO_free(bzl); #endif if (pass) OPENSSL_free(pass); apps_shutdown(); OPENSSL_EXIT(ret); }
static int pkey_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { EC_PKEY_CTX *dctx = ctx->data; EC_GROUP *group; switch (type) { case EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID: group = EC_GROUP_new_by_curve_name(p1); if (group == NULL) { ECerr(EC_F_PKEY_EC_CTRL, EC_R_INVALID_CURVE); return 0; } EC_GROUP_free(dctx->gen_group); dctx->gen_group = group; return 1; case EVP_PKEY_CTRL_EC_PARAM_ENC: if (!dctx->gen_group) { ECerr(EC_F_PKEY_EC_CTRL, EC_R_NO_PARAMETERS_SET); return 0; } EC_GROUP_set_asn1_flag(dctx->gen_group, p1); return 1; #ifndef OPENSSL_NO_EC case EVP_PKEY_CTRL_EC_ECDH_COFACTOR: if (p1 == -2) { if (dctx->cofactor_mode != -1) return dctx->cofactor_mode; else { EC_KEY *ec_key = ctx->pkey->pkey.ec; return EC_KEY_get_flags(ec_key) & EC_FLAG_COFACTOR_ECDH ? 1 : 0; } } else if (p1 < -1 || p1 > 1) return -2; dctx->cofactor_mode = p1; if (p1 != -1) { EC_KEY *ec_key = ctx->pkey->pkey.ec; if (!ec_key->group) return -2; /* If cofactor is 1 cofactor mode does nothing */ if (BN_is_one(ec_key->group->cofactor)) return 1; if (!dctx->co_key) { dctx->co_key = EC_KEY_dup(ec_key); if (!dctx->co_key) return 0; } if (p1) EC_KEY_set_flags(dctx->co_key, EC_FLAG_COFACTOR_ECDH); else EC_KEY_clear_flags(dctx->co_key, EC_FLAG_COFACTOR_ECDH); } else { EC_KEY_free(dctx->co_key); dctx->co_key = NULL; } return 1; #endif case EVP_PKEY_CTRL_EC_KDF_TYPE: if (p1 == -2) return dctx->kdf_type; if (p1 != EVP_PKEY_ECDH_KDF_NONE && p1 != EVP_PKEY_ECDH_KDF_X9_62) return -2; dctx->kdf_type = p1; return 1; #ifndef OPENSSL_NO_SM2 case EVP_PKEY_CTRL_EC_SCHEME: if (p1 == -2) { return dctx->ec_scheme; } if (p1 != NID_secg_scheme && p1 != NID_sm_scheme) { ECerr(EC_F_PKEY_EC_CTRL, EC_R_INVALID_EC_SCHEME); return 0; } dctx->ec_scheme = p1; return 1; case EVP_PKEY_CTRL_SIGNER_ID: if (!p2 || !strlen((char *)p2) || strlen((char *)p2) > SM2_MAX_ID_LENGTH) { ECerr(EC_F_PKEY_EC_CTRL, EC_R_INVALID_SIGNER_ID); return 0; } else { char *id = NULL; if (!(id = OPENSSL_strdup((char *)p2))) { ECerr(EC_F_PKEY_EC_CTRL, ERR_R_MALLOC_FAILURE); return 0; } if (dctx->signer_id) OPENSSL_free(dctx->signer_id); dctx->signer_id = id; if (dctx->ec_scheme == NID_sm_scheme) { EC_KEY *ec_key = ctx->pkey->pkey.ec; unsigned char zid[SM3_DIGEST_LENGTH]; size_t zidlen = SM3_DIGEST_LENGTH; if (!SM2_compute_id_digest(EVP_sm3(), dctx->signer_id, strlen(dctx->signer_id), zid, &zidlen, ec_key)) { ECerr(EC_F_PKEY_EC_CTRL, ERR_R_SM2_LIB); return 0; } if (!dctx->signer_zid) { if (!(dctx->signer_zid = OPENSSL_malloc(zidlen))) { ECerr(EC_F_PKEY_EC_CTRL, ERR_R_MALLOC_FAILURE); return 0; } } memcpy(dctx->signer_zid, zid, zidlen); } } return 1; case EVP_PKEY_CTRL_GET_SIGNER_ID: *(const char **)p2 = dctx->signer_id; return 1; case EVP_PKEY_CTRL_GET_SIGNER_ZID: if (dctx->ec_scheme != NID_sm_scheme) { *(const unsigned char **)p2 = NULL; return -2; } if (!dctx->signer_zid) { EC_KEY *ec_key = ctx->pkey->pkey.ec; unsigned char *zid; size_t zidlen = SM3_DIGEST_LENGTH; if (!(zid = OPENSSL_malloc(zidlen))) { ECerr(EC_F_PKEY_EC_CTRL, ERR_R_MALLOC_FAILURE); return 0; } if (!SM2_compute_id_digest(EVP_sm3(), SM2_DEFAULT_ID, SM2_DEFAULT_ID_LENGTH, zid, &zidlen, ec_key)) { ECerr(EC_F_PKEY_EC_CTRL, ERR_R_SM2_LIB); OPENSSL_free(zid); return 0; } dctx->signer_zid = zid; } *(const unsigned char **)p2 = dctx->signer_zid; return 1; case EVP_PKEY_CTRL_EC_ENCRYPT_PARAM: if (p1 == -2) { return dctx->ec_encrypt_param; } dctx->ec_encrypt_param = p1; return 1; #endif case EVP_PKEY_CTRL_EC_KDF_MD: dctx->kdf_md = p2; return 1; case EVP_PKEY_CTRL_GET_EC_KDF_MD: *(const EVP_MD **)p2 = dctx->kdf_md; return 1; case EVP_PKEY_CTRL_EC_KDF_OUTLEN: if (p1 <= 0) return -2; dctx->kdf_outlen = (size_t)p1; return 1; case EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN: *(int *)p2 = dctx->kdf_outlen; return 1; case EVP_PKEY_CTRL_EC_KDF_UKM: OPENSSL_free(dctx->kdf_ukm); dctx->kdf_ukm = p2; if (p2) dctx->kdf_ukmlen = p1; else dctx->kdf_ukmlen = 0; return 1; case EVP_PKEY_CTRL_GET_EC_KDF_UKM: *(unsigned char **)p2 = dctx->kdf_ukm; return dctx->kdf_ukmlen; case EVP_PKEY_CTRL_MD: if (EVP_MD_type((const EVP_MD *)p2) != NID_sha1 && #ifndef OPENSSL_NO_SM3 EVP_MD_type((const EVP_MD *)p2) != NID_sm3 && #endif EVP_MD_type((const EVP_MD *)p2) != NID_ecdsa_with_SHA1 && EVP_MD_type((const EVP_MD *)p2) != NID_sha224 && EVP_MD_type((const EVP_MD *)p2) != NID_sha256 && EVP_MD_type((const EVP_MD *)p2) != NID_sha384 && EVP_MD_type((const EVP_MD *)p2) != NID_sha512) { ECerr(EC_F_PKEY_EC_CTRL, EC_R_INVALID_DIGEST_TYPE); return 0; } dctx->md = p2; return 1; case EVP_PKEY_CTRL_GET_MD: *(const EVP_MD **)p2 = dctx->md; return 1; case EVP_PKEY_CTRL_PEER_KEY: /* Default behaviour is OK */ case EVP_PKEY_CTRL_DIGESTINIT: case EVP_PKEY_CTRL_PKCS7_SIGN: case EVP_PKEY_CTRL_CMS_SIGN: return 1; default: return -2; } }
int EVP_PBE_scrypt(const char *pass, size_t passlen, const unsigned char *salt, size_t saltlen, uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem, unsigned char *key, size_t keylen) { int rv = 0; unsigned char *B; uint32_t *X, *V, *T; uint64_t i, Blen, Vlen; size_t allocsize; const EVP_MD *md; #ifndef OPENSSL_NO_SHA md = EVP_sha256(); #elif !defined(OPENSSL_NO_SM3) md = EVP_sm3(); #else EVPerr(EVP_F_EVP_PBE_SCRYPT, EVP_R_NO_AVAIABLE_DIGEST); return 0; #endif /* Sanity check parameters */ /* initial check, r,p must be non zero, N >= 2 and a power of 2 */ if (r == 0 || p == 0 || N < 2 || (N & (N - 1))) return 0; /* Check p * r < SCRYPT_PR_MAX avoiding overflow */ if (p > SCRYPT_PR_MAX / r) return 0; /* * Need to check N: if 2^(128 * r / 8) overflows limit this is * automatically satisfied since N <= UINT64_MAX. */ if (16 * r <= LOG2_UINT64_MAX) { if (N >= (((uint64_t)1) << (16 * r))) return 0; } /* Memory checks: check total allocated buffer size fits in uint64_t */ /* * B size in section 5 step 1.S * Note: we know p * 128 * r < UINT64_MAX because we already checked * p * r < SCRYPT_PR_MAX */ Blen = p * 128 * r; /* * Check 32 * r * (N + 2) * sizeof(uint32_t) fits in * uint64_t and also size_t (their sizes are unrelated). * This is combined size V, X and T (section 4) */ i = UINT64_MAX / (32 * sizeof(uint32_t)); if (N + 2 > i / r) return 0; Vlen = 32 * r * (N + 2) * sizeof(uint32_t); /* check total allocated size fits in uint64_t */ if (Blen > UINT64_MAX - Vlen) return 0; /* check total allocated size fits in size_t */ if (Blen > SIZE_MAX - Vlen) return 0; allocsize = (size_t)(Blen + Vlen); if (maxmem == 0) maxmem = SCRYPT_MAX_MEM; if (allocsize > maxmem) { EVPerr(EVP_F_EVP_PBE_SCRYPT, EVP_R_MEMORY_LIMIT_EXCEEDED); return 0; } /* If no key return to indicate parameters are OK */ if (key == NULL) return 1; B = OPENSSL_malloc(allocsize); if (B == NULL) return 0; X = (uint32_t *)(B + Blen); T = X + 32 * r; V = T + 32 * r; if (PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, 1, md, Blen, B) == 0) goto err; for (i = 0; i < p; i++) scryptROMix(B + 128 * r * i, r, N, X, T, V); if (PKCS5_PBKDF2_HMAC(pass, passlen, B, Blen, 1, md, keylen, key) == 0) goto err; rv = 1; err: OPENSSL_clear_free(B, allocsize); return rv; }
// unsigned char *pM 输出,明文 // unsigned char *pPDKey 私钥 // unsigned char *pC 密文 // unsigned long Clen 密文长度 unsigned char eccDecrypt(unsigned char *pM, unsigned char *pPDKey, unsigned char *pC, unsigned long Clen) { EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_sm2p256v1); EC_GROUP *ec_group = EC_GROUP_new_by_curve_name(NID_sm2p256v1); KDF_FUNC kdf = KDF_get_x9_63(EVP_sm3()); // 设置私钥 BIGNUM *pri_key = BN_new(); BN_bin2bn(pPDKey, 32, pri_key); EC_KEY_set_private_key(ec_key, pri_key); int ret = 1; EC_POINT *point = NULL; BIGNUM *n = NULL; BIGNUM *h = NULL; BN_CTX *bn_ctx = NULL; EVP_MD_CTX *md_ctx = NULL; unsigned char buf[(OPENSSL_ECC_MAX_FIELD_BITS + 7)/4 + 1]; unsigned char mac[EVP_MAX_MD_SIZE]; unsigned int maclen; int nbytes; size_t size; size_t i; if (!ec_group || !pri_key) { goto end; } if (!kdf) { goto end; } EC_POINT *ephem_point = EC_POINT_new(ec_group); EC_POINT_oct2point(ec_group, ephem_point, pC, 65, NULL); /* init vars */ point = EC_POINT_new(ec_group); n = BN_new(); h = BN_new(); bn_ctx = BN_CTX_new(); md_ctx = EVP_MD_CTX_create(); if (!point || !n || !h || !bn_ctx || !md_ctx) { goto end; } /* init ec domain parameters */ if (!EC_GROUP_get_order(ec_group, n, bn_ctx)) { goto end; } if (!EC_GROUP_get_cofactor(ec_group, h, bn_ctx)) { goto end; } nbytes = (EC_GROUP_get_degree(ec_group) + 7) / 8; /* B2: check [h]C1 != O */ if (!EC_POINT_mul(ec_group, point, NULL, ephem_point, h, bn_ctx)) { goto end; } if (EC_POINT_is_at_infinity(ec_group, point)) { goto end; } /* B3: compute ECDH [d]C1 = (x2, y2) */ if (!EC_POINT_mul(ec_group, point, NULL, ephem_point, pri_key, bn_ctx)) { goto end; } if (!(size = EC_POINT_point2oct(ec_group, point, POINT_CONVERSION_UNCOMPRESSED, buf, sizeof(buf), bn_ctx))) { goto end; } OPENSSL_assert(size == 1 + nbytes * 2); /* B4: compute t = KDF(x2 || y2, clen) */ size_t len = 0; size_t *outlen = &len; *outlen = Clen - 97; //FIXME: duplicated code unsigned char *out = (unsigned char *)OPENSSL_malloc(*outlen); kdf(buf + 1, size - 1, out, outlen); unsigned char *ciphertext = pC + 65; /* B5: compute M = C2 xor t */ for (i = 0; i < len; i++) { out[i] ^= ciphertext[i]; } *outlen = len; if (1) { /* B6: check Hash(x2 || M || y2) == C3 */ if (!EVP_DigestInit_ex(md_ctx, EVP_sm3(), NULL)) { goto end; } if (!EVP_DigestUpdate(md_ctx, buf + 1, nbytes)) { goto end; } if (!EVP_DigestUpdate(md_ctx, out, *outlen)) { goto end; } if (!EVP_DigestUpdate(md_ctx, buf + 1 + nbytes, nbytes)) { goto end; } if (!EVP_DigestFinal_ex(md_ctx, mac, &maclen)) { goto end; } /* GmSSL specific */ if (memcmp(mac, pC + 129, 32)) { goto end; } } for (i = 0; i < len; i++) { pM[i] = out[i] ; } ret = 0; end: if (point) EC_POINT_free(point); if (n) BN_free(n); if (h) BN_free(h); if (bn_ctx) BN_CTX_free(bn_ctx); if (md_ctx) EVP_MD_CTX_destroy(md_ctx); return ret; }
// unsigned char *pC 输出,密文 // unsigned char *pPxKey, unsigned char *pPyKey 公钥 // unsigned char *pM 明文 // unsigned long MLen 明文长度 unsigned char eccEncrypt(unsigned char *pC, unsigned char *pPxKey, unsigned char *pPyKey, unsigned char *pM, unsigned long MLen) { // NID_sm2p256v1 EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_sm2p256v1); //// 相当于 //EC_KEY *ret = EC_KEY_new(); EC_GROUP *ec_group = EC_GROUP_new_by_curve_name(NID_sm2p256v1); KDF_FUNC kdf = KDF_get_x9_63(EVP_sm3());; EC_POINT *point = NULL; //// 设置私钥 //BIGNUM *d = NULL; //BN_hex2bn(&d, pPDKey); //EC_KEY_set_private_key(ec_key, d); int ret = 1; BIGNUM *x = BN_new();; BIGNUM *y = BN_new();; if (!BN_bin2bn(pPxKey, 32, x)) { goto end; } if (!BN_bin2bn(pPyKey, 32, y)) { goto end; } if (!EC_KEY_set_public_key_affine_coordinates(ec_key, x, y)) { goto end; } const EC_POINT *pub_key = EC_KEY_get0_public_key(ec_key); /* init ec domain parameters */ BIGNUM *n = NULL; BIGNUM *h = NULL; BIGNUM *k = NULL; n = BN_new(); h = BN_new(); k = BN_new(); BN_CTX *bn_ctx = NULL; bn_ctx = BN_CTX_new(); if (!EC_GROUP_get_order(ec_group, n, bn_ctx)) { goto end; } if (!EC_GROUP_get_cofactor(ec_group, h, bn_ctx)) { goto end; } int nbytes = (EC_GROUP_get_degree(ec_group) + 7) / 8; EC_POINT *ec_point = EC_POINT_new(ec_group); point = EC_POINT_new(ec_group); unsigned char buf[(OPENSSL_ECC_MAX_FIELD_BITS + 7)/4 + 1]; size_t len; char *ciphertext = (char *)OPENSSL_malloc(MLen); size_t ciphertext_size = MLen; do { /* A1: rand k in [1, n-1] */ do { BN_rand_range(k, n); } while (BN_is_zero(k)); /* A2: C1 = [k]G = (x1, y1) */ if (!EC_POINT_mul(ec_group, ec_point, k, NULL, NULL, bn_ctx)) { goto end; } #if 1 if (!(len = EC_POINT_point2oct(ec_group, ec_point, POINT_CONVERSION_UNCOMPRESSED, buf, sizeof(buf), bn_ctx))) { goto end; } BN_bin2bn(buf, 65, n); printf(BN_bn2hex(n)); printf("\n"); printf(BN_bn2hex(k)); #endif /* A3: check [h]P_B != O */ if (!EC_POINT_mul(ec_group, point, NULL, pub_key, h, bn_ctx)) { goto end; } if (EC_POINT_is_at_infinity(ec_group, point)) { goto end; } /* A4: compute ECDH [k]P_B = (x2, y2) */ if (!EC_POINT_mul(ec_group, point, NULL, pub_key, k, bn_ctx)) { goto end; } if (!(len = EC_POINT_point2oct(ec_group, point, POINT_CONVERSION_UNCOMPRESSED, buf, sizeof(buf), bn_ctx))) { goto end; } OPENSSL_assert(len == nbytes * 2 + 1); /* A5: t = KDF(x2 || y2, klen) */ kdf(buf + 1, len - 1, (unsigned char *)ciphertext, &ciphertext_size); // 防止全0 size_t i = 0; for (i = 0; i < ciphertext_size; i++) { if (ciphertext[i]) { break; } } if (i == ciphertext_size) { continue; } break; } while (1); /* A6: C2 = M xor t */ for (size_t i = 0; i < MLen; i++) { ciphertext[i] ^= pM[i]; } unsigned char dgst[EVP_MAX_MD_SIZE]; unsigned int dgstlen; EVP_MD_CTX *md_ctx = EVP_MD_CTX_create(); if (1) { /* A7: C3 = Hash(x2 || M || y2) */ if (!EVP_DigestInit_ex(md_ctx, EVP_sm3(), NULL)) { goto end; } if (!EVP_DigestUpdate(md_ctx, buf + 1, nbytes)) { goto end; } if (!EVP_DigestUpdate(md_ctx, pM, MLen)) { goto end; } if (!EVP_DigestUpdate(md_ctx, buf + 1 + nbytes, nbytes)) { goto end; } if (!EVP_DigestFinal_ex(md_ctx, dgst, &dgstlen)) { goto end; } } EC_POINT_point2oct(ec_group, point, POINT_CONVERSION_UNCOMPRESSED, pC, 65, NULL); memcpy(&pC[65], ciphertext, MLen); memcpy(&pC[65 + MLen], dgst, dgstlen); ret = 0; end: if (point) EC_POINT_free(point); if (n) BN_free(n); if (h) BN_free(h); if (k) BN_free(k); if (bn_ctx) BN_CTX_free(bn_ctx); if (md_ctx) EVP_MD_CTX_destroy(md_ctx); return ret; }