OpenSSL加解密程式
阿新 • • 發佈:2019-02-18
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
/* 加解密 */
void encrypt_decrypt_test() {
uint8_t key[EVP_MAX_KEY_LENGTH];
uint8_t iv[EVP_MAX_KEY_LENGTH];
EVP_CIPHER_CTX ctx;
uint8_t out[1024];
int out_len;
for (int i = 0; i < EVP_MAX_KEY_LENGTH; i++) {
key[i] = i;
iv[i] = i;
}
EVP_CIPHER_CTX_init(&ctx);
int ret = EVP_EncryptInit(&ctx, EVP_des_ede3_cbc(), key, iv);
if (ret != 1) {
printf("encrypt init error\n");
return;
}
char* msg = "hello world";
int in_len = 12;
ret = EVP_EncryptUpdate(&ctx, out, &out_len, (uint8_t*)msg, in_len);
int out_left_len;
ret = EVP_EncryptFinal(&ctx, out + out_len, &out_left_len);
out_len += out_left_len;
printf("原文:%s\n", msg);
printf("密文:");
for (int i = 0; i < out_len; i++) {
printf("0x%02x ", out[i]);
}
printf("\n");
ret = EVP_DecryptInit(&ctx, EVP_des_ede3_cbc(), key, iv);
uint8_t decrypt[128];
int decrypt_len;
ret = EVP_DecryptUpdate(&ctx, decrypt, &decrypt_len, out, out_len);
ret = EVP_DecryptFinal(&ctx, decrypt + decrypt_len, &decrypt_len);
EVP_CIPHER_CTX_cleanup(&ctx);
printf("解密:%s\n", decrypt);
printf("\n-----------------------\n");
}
#include <stdint.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
/* 加解密 */
void encrypt_decrypt_test() {
uint8_t key[EVP_MAX_KEY_LENGTH];
uint8_t iv[EVP_MAX_KEY_LENGTH];
EVP_CIPHER_CTX ctx;
uint8_t out[1024];
int out_len;
for (int i = 0; i < EVP_MAX_KEY_LENGTH; i++) {
key[i] = i;
iv[i] = i;
}
EVP_CIPHER_CTX_init(&ctx);
int ret = EVP_EncryptInit(&ctx, EVP_des_ede3_cbc(), key, iv);
if (ret != 1) {
printf("encrypt init error\n");
return;
}
char* msg = "hello world";
int in_len = 12;
ret = EVP_EncryptUpdate(&ctx, out, &out_len, (uint8_t*)msg, in_len);
int out_left_len;
ret = EVP_EncryptFinal(&ctx, out + out_len, &out_left_len);
out_len += out_left_len;
printf("原文:%s\n", msg);
printf("密文:");
for (int i = 0; i < out_len; i++) {
printf("0x%02x ", out[i]);
}
printf("\n");
ret = EVP_DecryptInit(&ctx, EVP_des_ede3_cbc(), key, iv);
uint8_t decrypt[128];
int decrypt_len;
ret = EVP_DecryptUpdate(&ctx, decrypt, &decrypt_len, out, out_len);
ret = EVP_DecryptFinal(&ctx, decrypt + decrypt_len, &decrypt_len);
EVP_CIPHER_CTX_cleanup(&ctx);
printf("解密:%s\n", decrypt);
printf("\n-----------------------\n");
}