openssl evp RSA 加密解密

时间:2022-12-10 02:30:24

openssl evp RSA 加密解密

可以直接使用RSA.h 提供的接口

如下测试使用EVP提供的RSA接口

1. EVP提供的RSA 加密解密

主要接口:

int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx,
unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen);
int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx,
unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen);

测试代码

先生成 EVP_KEY

    //生成密钥对
RSA *r = RSA_new();
int bits = ;
BIGNUM *e = BN_new();
BN_set_word(e, );
RSA_generate_key_ex(r, bits, e, NULL); EVP_PKEY *key;
key = EVP_PKEY_new();
EVP_PKEY_set1_RSA(key, r);

测试加密解密

    //默认使用的是 RSA_PKCS1_PADDING,即这里最大加密块为64-11=53,大量数组需要分组处理
char *srcStr = "";
//char *srcStr = "hello world";
int enclen = ;
char encData[] = {};
char decData[] = {};
int declen = ;
printf("src=%s\n",srcStr); //加密
EVP_PKEY_CTX *ectx;
ectx = EVP_PKEY_CTX_new(key, NULL);
EVP_PKEY_encrypt_init(ectx);
EVP_PKEY_encrypt(ectx, encData, &enclen, srcStr, strlen(srcStr)); //解密
EVP_PKEY_CTX *dctx;
dctx = EVP_PKEY_CTX_new(key, NULL);
EVP_PKEY_decrypt_init(dctx);
EVP_PKEY_decrypt(dctx, decData, &declen, encData, enclen);
printf("dec=%s\n",decData); EVP_PKEY_CTX_free(ectx);
EVP_PKEY_CTX_free(dctx); EVP_PKEY_free(key);
BN_free(e);
RSA_free(r);

执行结果:

src=
dec=
Program ended with exit code:

上述测试也是RSA的分组加密,如果加密数据比较长的时候,需要多次调用;

补位方式:RSA_PKCS1_PADDING 则,最大分组真为RSA_size(r) -11

2. 另外evp提供的签名与验签接口还有

int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_sign(EVP_PKEY_CTX *ctx,
unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen);
int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_verify(EVP_PKEY_CTX *ctx,
const unsigned char *sig, size_t siglen,
const unsigned char *tbs, size_t tbslen);
int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_verify_recover(EVP_PKEY_CTX *ctx,
unsigned char *rout, size_t *routlen,
const unsigned char *sig, size_t siglen);

3.  关于数字信封,签名信封,打开信封接口

__owur int EVP_OpenInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
const unsigned char *ek, int ekl,
const unsigned char *iv, EVP_PKEY *priv);
__owur int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); __owur int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
unsigned char **ek, int *ekl, unsigned char *iv,
EVP_PKEY **pubk, int npubk);
__owur int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);

参考:https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_encrypt.html

https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_verify.html