给定以下openssl 示例程序
#include <openssl/evp.h>
int do_crypt(FILE* in, FILE* out, int do_encrypt)
{
/* Allow enough space in output buffer for additional block */
unsigned char inbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
int inlen, outlen;
EVP_CIPHER_CTX* ctx;
/* Bogus key and IV: we'd normally set these from
* another source.
*/
unsigned char key[] = "0123456789abcdeF";
unsigned char iv[] = "1234567887654321";
/* Don't set key or IV right away; we want to check lengths */
ctx = EVP_CIPHER_CTX_new();
EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, NULL, NULL, do_encrypt);
OPENSSL_assert(EVP_CIPHER_CTX_key_length(ctx) == 16);
OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) == 16);
/* Now we can set key and IV */
EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, do_encrypt);
for (;;) {
inlen = fread(inbuf, 1, 1024, in);
if (inlen <= 0)
break;
if (!EVP_CipherUpdate(ctx, outbuf, &outlen, inbuf, inlen)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
fwrite(outbuf, 1, outlen, out);
}
if (!EVP_CipherFinal_ex(ctx, outbuf, &outlen)) {
/* Error */
EVP_CIPHER_CTX_free(ctx);
return 0;
}
fwrite(outbuf, 1, outlen, out);
EVP_CIPHER_CTX_free(ctx);
return 1;
}
int main(int argc, char* argv[])
{
FILE *fpIn;
FILE *fpOut;
fpIn = fopen("text-in.txt", "rb");
fpOut = fopen("text-out.txt", "wb");
int test = do_crypt(fpIn, fpOut, 1);
fclose(fpIn);
fclose(fpOut);
return 0;
}
我希望
openssl aes-128-cbc -in text-in.txt -K 0123456789abcdeF -iv 1234567887654321
将创建相同的输出。但事实并非如此。C 程序可以解密它加密的文件。但它无法解密使用 openssl 加密的文件。
加密密钥和 IV 实际上不是文本数据,而是二进制数据。
在命令行上执行加密时,-K
和 -iv
参数需要以十六进制输入。
所以你传入的密钥实际上是:
x01x23x45x67x89xabxcdxefx00x00x00x00x00x00x00x00
IV是:
x12x34x56x78x87x65x43x21x00x00x00x00x00x00x00x00
两者都有 0 的尾部填充,因为指定的键太短。
为了匹配程序的输出,您需要传入指定字符的十六进制代码。 例如,1
是30
、2
是31
、a
是61
、F
是46
,依此类推:
openssl aes-128-cbc -in text-in.txt -K 30313233343536373839616263646546 -iv 31323334353637383837363534333231