static int pkey_ec_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen) { EC_PKEY_CTX *dctx = ctx->data; EC_KEY *ec_key = ctx->pkey->pkey.ec; switch (dctx->ec_scheme) { case NID_sm_scheme: if (!SM2_decrypt(dctx->ec_encrypt_param, in, inlen, out, outlen, ec_key)) { ECerr(EC_F_PKEY_EC_DECRYPT, EC_R_SM2_DECRYPT_FAILED); return 0; } break; case NID_secg_scheme: if (!ECIES_decrypt(dctx->ec_encrypt_param, in, inlen, out, outlen, ec_key)) { ECerr(EC_F_PKEY_EC_DECRYPT, EC_R_ECIES_DECRYPT_FAILED); return 0; } break; default: ECerr(EC_F_PKEY_EC_DECRYPT, EC_R_INVALID_ENC_TYPE); return 0; } return 1; }
static int pkey_sm2_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen) { EC_PKEY_CTX *ec_ctx = ctx->data; EC_KEY *ec_key = ctx->pkey->pkey.ec; const EVP_MD *kdf_md = ec_ctx->kdf_md; const EVP_MD *mac_md = ec_ctx->md; point_conversion_form_t point_form = SM2_DEFAULT_POINT_CONVERSION_FORM; return SM2_decrypt(kdf_md, mac_md, point_form, in, inlen, out, outlen, ec_key); }
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; }