Esempio n. 1
0
int SM2_encrypt(const EVP_MD *kdf_md, const EVP_MD *mac_md,
	point_conversion_form_t point_form,
	const unsigned char *in, size_t inlen,
	unsigned char *out, size_t *outlen, EC_KEY *ec_key)
{
	int ret = 0;
	const EC_GROUP *ec_group = EC_KEY_get0_group(ec_key);
	SM2_CIPHERTEXT_VALUE *cv = NULL;
	int len;

	if (!(len = SM2_CIPHERTEXT_VALUE_size(ec_group, point_form, inlen, mac_md))) {
		goto end;
	}

	if (!out) {
		*outlen = (size_t)len;
		return 1;

	} else if (*outlen < (size_t)len) {
		return 0;
	}

	if (!(cv = SM2_do_encrypt(kdf_md, mac_md, in, inlen, ec_key))) {
		goto end;
	}
	if (!SM2_CIPHERTEXT_VALUE_encode(cv, ec_group, point_form, out, outlen)) {
		goto end;
	}
	
	ret = 1;
end:
	if (cv) SM2_CIPHERTEXT_VALUE_free(cv);
	return ret;
}
Esempio n. 2
0
int SM2_encrypt(int type, const unsigned char *in, size_t inlen,
	unsigned char *out, size_t *outlen, EC_KEY *ec_key)
{
	int ret = 0;
	SM2CiphertextValue *cv = NULL;
	const EVP_MD *md;
	int len;

	if (!(md = EVP_get_digestbynid(type))) {
		SM2err(SM2_F_SM2_ENCRYPT, SM2_R_INVALID_DIGEST_ALGOR);
		return 0;
	}

	if (!(cv = SM2_do_encrypt(md, in, inlen, ec_key))) {
		SM2err(SM2_F_SM2_ENCRYPT, SM2_R_ENCRYPT_FAILURE);
		goto end;
	}

	if (!out) {
		*outlen = i2d_SM2CiphertextValue(cv, NULL);
		ret = 1;
	} else if (*outlen < i2d_SM2CiphertextValue(cv, NULL)) {
		SM2err(SM2_F_SM2_ENCRYPT, SM2_R_BUFFER_TOO_SMALL);
		ret = 0;
	} else {
		len = i2d_SM2CiphertextValue(cv, &out);
		*outlen = len;
		ret = 1;
	}

end:
	SM2CiphertextValue_free(cv);
	return ret;
}
Esempio n. 3
0
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;
}