加密数据为字符串

我是加密和C语言的新手,所以这可能是一个明显的问题,但我找不到解决问题的方法。

我在C上创建一个应用程序,并在Linux中使用openssl进行加密。

我从这个url得到了一个C代码示例,它允许使用SHA加密和解密字符串: http : //wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption

#include  #include  #include  #include  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); 

当我试图这样做时,所有的字符串都被改变了并且无法使用。 我认为问题来自二进制数据被视为字符,这包括控制字符或退格。

有没有办法将此加密数据视为字符串而不改变它? 我应该使用其他类型的加密吗?

ciphertext[128]不是字符串,字符串函数类似于strcat(bigstring,ciphertext); 不应该期望它与它一起工作。

在C中,“ 字符串是由第一个空字符终止并包括第一个空字符的连续字符序列。” ciphertext[128]可能在其中嵌入了'\0' (@ James Black)和/或可能没有终止'\0'

以另一种方式执行连接,可能:

 memcpy(bigstring, &ciphertext[bigstring_len], ciphertext_len); bigstring_len += ciphertext_len; 

如果您正在使用二进制数据,则不得使用str *函数,而应使用mem *函数,例如memcpy(3)。

对于您的SQL查询,我建议您使用除字符串查询之外的其他内容。 例如使用mysql我建议您准备一份声明( http://dev.mysql.com/doc/refman/5.1/en/mysql-stmt-execute.html

另一种解决方案是将您的加密(二进制)数据编码为hex或base64。

假设在打印你试图连接的两个字符串时,答案没有垃圾值等,而不是麻烦使用不同的加密(注意拼写),为什么不用另一种方式工作并尝试写你自己的连接函数? 这对你来说更容易。 如果你愿意,我很乐意帮助你。

它可能与您的问题无关,但使用起来会更安全:

strncat函数

确保复制的字节数不超过您想要的字节数。 此外,您可能需要仔细检查您的类型:strcat将char *作为参数。