我对加密和 C 语言很陌生,所以这可能是一个明显的问题,但我找不到解决问题的方法。
我正在用 C 语言制作一个应用程序,并在 Linux 中使用 openssl 进行加密。
我从这个 url 中获得了一个 C 代码示例,该代码允许使用 SHA 加密和解密字符串: http://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <string.h>
int main(int arc, char *argv[])
{
unsigned char *key = "01234567890123456789012345678901";
unsigned char *iv = "01234567890123456";
/* Message to be encrypted */
unsigned char *plaintext = "The quick brown fox jumps over the lazy dog";
unsigned char ciphertext[128];
unsigned char decryptedtext[128];
int decryptedtext_len, ciphertext_len;
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
OPENSSL_config(NULL);
ciphertext_len = encrypt(plaintext, strlen(plaintext), key, iv,ciphertext);
printf("Ciphertext is:\n");
BIO_dump_fp(stdout, ciphertext, ciphertext_len);
EVP_cleanup();
ERR_free_strings();
return 0;
}
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
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())) handleErrors();
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
handleErrors();
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
我工作得很好,而且我已经让它完美地工作了。我所看到的是,我需要将加密结果作为字符串处理,并将其附加到更大的字符串(实际上是 SQL 命令)。代码调用方式如下:
ciphertext_len = encrypt(it, strlen(it), key, iv,ciphertext);
strcat(bigstring,ciphertext);
当我尝试执行此操作时,所有字符串都被更改且无法使用。我认为问题来自于将二进制数据视为字符,其中包括控制字符或退格键。
有没有一种方法可以将这些加密数据视为字符串而不改变它? 我应该使用另一种加密吗?
最佳答案
如果您正在处理二进制数据,则不得使用 str* 函数,而应使用 mem* 函数,例如您的情况下的 memcpy(3) 。
对于您的 SQL 查询,我建议您使用字符串查询以外的其他内容。例如,对于 mysql,我建议您使用准备好的语句( http://dev.mysql.com/doc/refman/5.1/en/mysql-stmt-execute.html )
另一种解决方案可能是将加密(二进制)数据编码为十六进制或 Base64。
关于c - 加密数据作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21530922/