openssl 对称加密
时间: 2023-10-24 18:06:42 浏览: 117
对称加密代码
OpenSSL 是一个开源的加密库,支持对称加密、非对称加密、哈希算法等多种加密方式。对称加密是指加密和解密使用相同的密钥,常见的对称加密算法有 DES、3DES、AES 等。
在 OpenSSL 中,使用 EVP 接口进行对称加密操作。下面是一个使用 AES-256-CBC 算法进行加密和解密的示例代码:
```c
#include <openssl/evp.h>
#include <string.h>
int aes_encrypt(const unsigned char *plaintext, int plaintext_len,
const unsigned char *key, const unsigned char *iv,
unsigned char *ciphertext)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) return -1;
/* Initialise the encryption operation. */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
return -1;
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
return -1;
ciphertext_len = len;
/* Finalise the encryption. */
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) return -1;
ciphertext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int aes_decrypt(const unsigned char *ciphertext, int ciphertext_len,
const unsigned char *key, const unsigned char *iv,
unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
int ret;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) return -1;
/* Initialise the decryption operation. */
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
return -1;
/* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
return -1;
plaintext_len = len;
/* Finalise the decryption. */
ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
if(ret > 0) {
plaintext_len += len;
} else {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return -1;
}
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
```
其中,`aes_encrypt` 函数用于加密,`aes_decrypt` 函数用于解密。`plaintext` 是明文,`plaintext_len` 是明文长度,`key` 是密钥,`iv` 是初始化向量,`ciphertext` 是密文,`ciphertext_len` 是密文长度,`plaintext` 是解密后的明文。
阅读全文