1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
| #include <openssl/evp.h> #include <trace/trace.h>
#define ALGO_NAME "RSA"
#define DATA_BUF_LEN 1024
static unsigned char DATA_BUF[DATA_BUF_LEN] = { 0 };
struct BIN_DATA { unsigned char *data; size_t len; };
int asym_encrypt(EVP_PKEY_CTX *ctx, struct BIN_DATA *in, struct BIN_DATA *enc) { size_t blen = 0;
if (!ctx || !in || !enc) { return 0; }
if (EVP_PKEY_encrypt(ctx, NULL, &blen, in->data, in->len) != 1) { return 0; }
if (blen > enc->len) { TRACE("缓冲区不足!\n"); return 0; }
if (EVP_PKEY_encrypt(ctx, enc->data, &enc->len, in->data, in->len) != 1) { return 0; } return 1; }
int asym_decrypt(EVP_PKEY_CTX *ctx, struct BIN_DATA *enc, struct BIN_DATA *dec) { size_t blen = 0;
if (!ctx || !enc || !dec) { return 0; }
if (EVP_PKEY_decrypt(ctx, NULL, &blen, enc->data, enc->len) != 1) { return 0; }
if (blen > dec->len) { TRACE("缓冲区不足!\n"); return 0; }
if (EVP_PKEY_decrypt(ctx, dec->data, &dec->len, enc->data, enc->len) != 1) { return 0; } return 1; }
int main(int argc, char *argv[]) { EVP_PKEY_CTX *ectx = NULL; EVP_PKEY_CTX *dctx = NULL;
char data[] = "12345678901234567890abcdefgABCDEFGIOPBNM12356789"; int len = sizeof(data);
struct BIN_DATA in = { (unsigned char *)data, len };
struct BIN_DATA enc = { DATA_BUF, DATA_BUF_LEN / 2 };
struct BIN_DATA dec = { DATA_BUF + DATA_BUF_LEN / 2, DATA_BUF_LEN / 2 };
EVP_PKEY *pair = EVP_PKEY_Q_keygen(NULL, NULL, ALGO_NAME, 2048);
if (!pair) { TRACE("生成密钥失败\n"); return 0; }
ectx = EVP_PKEY_CTX_new_from_pkey(NULL, pair, NULL); if (!ectx) { TRACE("生成非对称算法上下文失败\n"); goto end; }
if (EVP_PKEY_encrypt_init_ex(ectx, NULL) != 1) { TRACE("初始化非对称算法上下文失败\n"); goto end; }
if (asym_encrypt(ectx, &in, &enc) != 1) { TRACE("加密失败\n"); goto end; }
dctx = EVP_PKEY_CTX_new_from_pkey(NULL, pair, NULL); if (!dctx) { TRACE("生成非对称算法上下文失败\n"); goto end; }
if (EVP_PKEY_decrypt_init_ex(dctx, NULL) != 1) { TRACE("初始化非对称算法上下文失败\n"); goto end; }
if (asym_decrypt(dctx, &enc, &dec) != 1) { TRACE("解密失败\n"); goto end; }
TRACE_BIN("原文数据", in.data, in.len);
TRACE_BIN("加密数据", enc.data, enc.len);
TRACE_BIN("解密数据", dec.data, dec.len);
end: if (dctx) { EVP_PKEY_CTX_free(dctx); }
if (ectx) { EVP_PKEY_CTX_free(ectx); }
EVP_PKEY_free(pair); return 0; }
|