尝试使用openssl的evp函数加密和解密字符串。我尝试了以下源代码,但得到了意想不到的结果(乱码输出(。
我缺少什么?
#include <stdio.h>
#include <unistd.h>
#if 1
#include <openssl/evp.h>
char *se_evp_encrypt(char *ssid, char *data, int inl, char *ret, int *rb)
{
int i, tmp, ol;
EVP_CIPHER_CTX evpctx;
char key[EVP_MAX_KEY_LENGTH] = {0};
char iv[EVP_MAX_IV_LENGTH] = {0};
*ret = ' ';
strncpy(key, ssid, EVP_MAX_KEY_LENGTH);
strncpy(iv, ssid, EVP_MAX_IV_LENGTH);
EVP_EncryptInit(&evpctx, EVP_bf_cbc(), key, iv);
EVP_EncryptUpdate(&evpctx, ret, &ol, data, inl);
*rb = ol;
EVP_EncryptFinal(&evpctx, ret, &ol);
return ret;
}
char *se_evp_decrypt(char *ssid, char *ct, int inl, char *pt)
{
int ol;
EVP_CIPHER_CTX evpctx;
char key[EVP_MAX_KEY_LENGTH] = {0};
char iv[EVP_MAX_IV_LENGTH] = {0};
char final[EVP_MAX_BLOCK_LENGTH];
*pt = ' ';
strncpy(key, ssid, EVP_MAX_KEY_LENGTH);
strncpy(iv, ssid, EVP_MAX_IV_LENGTH);
EVP_DecryptInit(&evpctx, EVP_bf_cbc(), key, iv);
EVP_DecryptUpdate(&evpctx, pt, &ol, ct, inl);
if (!ol) /* there's no block to decrypt */
{
return "";
}
pt[ol] = 0;
EVP_DecryptFinal(&evpctx, final, &inl);
return pt;
}
int main(int argc, char *argv[])
{
char str[] = "abcdef123456789";
char buf[256] = "", buf2[256] = "";
int i;
se_evp_encrypt("anyssid", str, strlen(str), buf, &i);
printf("Ciphertext is %d bytes. %dn", i, strlen(str));
se_evp_decrypt("anyssid", buf, i, buf2);
printf("Decrypted: >>%s<<n", buf2);
}
#endif
以这种方式修复了源代码
#include <stdio.h>
#include <unistd.h>
#if 1
#include <openssl/evp.h>
char *se_evp_encrypt(char *ssid, char *data, int inl, char *ret, int *rb)
{
int i, tmp, ol;
EVP_CIPHER_CTX evpctx = {0};
char key[EVP_MAX_KEY_LENGTH] = {0};
char iv[EVP_MAX_IV_LENGTH] = {0};
*ret = ' ';
strncpy(key, ssid, EVP_MAX_KEY_LENGTH);
strncpy(iv, ssid, EVP_MAX_IV_LENGTH);
EVP_EncryptInit(&evpctx, EVP_bf_cbc(), key, iv);
EVP_EncryptUpdate(&evpctx, ret, &ol, data, inl);
EVP_EncryptFinal(&evpctx, ret + ol, &tmp);
*rb = ol + tmp;
return ret;
}
char *se_evp_decrypt(char *ssid, char *ct, int inl, char *pt)
{
int ol, tmp;
EVP_CIPHER_CTX evpctx;
char key[EVP_MAX_KEY_LENGTH] = {0};
char iv[EVP_MAX_IV_LENGTH] = {0};
char final[EVP_MAX_BLOCK_LENGTH];
*pt = ' ';
strncpy(key, ssid, EVP_MAX_KEY_LENGTH);
strncpy(iv, ssid, EVP_MAX_IV_LENGTH);
EVP_DecryptInit(&evpctx, EVP_bf_cbc(), key, iv);
EVP_DecryptUpdate(&evpctx, pt, &ol, ct, inl);
EVP_DecryptFinal(&evpctx, pt+ol , &tmp);
pt[ol+tmp] = 0;
return pt;
}
int main(int argc, char *argv[])
{
char str[] = "abcdef123456789";
char buf[256] = "", buf2[256] = "";
int i;
se_evp_encrypt("anyssid", str, strlen(str), buf, &i);
printf("Ciphertext is %d bytes. %dn", i, strlen(str));
se_evp_decrypt("anyssid", buf, i, buf2);
printf("Decrypted: >>%s<<n", buf2);
}
#endif