如何为 openssl decrypt 命令提供字符串 IV 和 Key?

How to provide string IV and Key to openssl decrypt command?

我正在使用来自以下 wiki 的加密和解密函数: https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption

它使用 AES-256-cbc 算法,密钥 =“01234567890123456789012345678901”,iv =“0123456789012345”。 我能够加密我的文本,将其写入文件 encrypted.enc 并从文件返回解密。

我只是简单地使用以下代码将加密后的密文写入文件:

fd = fopen ("/var/local/encrypted.enc", "w");
fwrite ((const char *)ciphertext, sizeof(char), ciphertext_len, fd);
fclose(fd);

现在我想从 bash 提示符(不使用上面的代码)解密这个文件。我尝试了不同的标志,但无法弄清楚如何做到这一点。

我试过这个:

openssl enc -aes-256-cbc -d -out decrypted.txt -in encrypted.enc -iv 0123456789012345 -k 01234567890123456789012345678901

但在十六进制宽度方面出现错误。因此,将这些值转换为十六进制并尝试:

openssl enc -aes-256-cbc -d -out decrypted.txt -in encrypted.enc -iv 30313233343536373839303132333435 -k 3031323334353637383930313233343536373839303132333435363738393031

但现在我收到“Bad Magic Number”错误...

如何使用 openssl 实用程序解密文件?

openssl enc 命令在加密时默认使用随机生成的盐值。它以该值开始输出,前面是表示字符 Salted__ 的“幻数”。使用命令的 enc 版本,您可以在此处看到说明:

$ printf 1234567890123456 | openssl enc -aes-256-cbc -iv 0123456789012345 -k 01234567890123456789012345678901 | hexdump -C
00000000  53 61 6c 74 65 64 5f 5f  ed 6c b5 aa e2 92 4a 00  |Salted__.l....J.|
00000010  68 f7 b2 40 d2 44 44 8b  fa 4c 05 95 99 cf 76 32  |h..@.DD..L....v2|
00000020  4e 15 37 65 93 00 d6 b2  ff 4d 1b 6c af 46 64 f6  |N.7e.....M.l.Fd.|
00000030

解密时,需要同样的幻数。您的文件不包含它,因此出现错误。这是 OpenSSL 专有的东西。

使用 -nosalt 选项可以(但不推荐)避免加盐:

$ printf 1234567890123456 | openssl enc -aes-256-cbc  -iv 0123456789012345 -k 01234567890123456789012345678901 -nosalt | hexdump -C
00000000  54 05 6a fb c3 60 a9 32  3d 2e e0 4c 2a 21 4a a1  |T.j..`.2=..L*!J.|
00000010  3c a7 34 f3 8f c4 15 33  99 dd 08 f7 e5 ef ea 57  |<.4....3.......W|
00000020

在解密命令中使用相同的 -nosalt 选项,您应该不会再得到 bad magic number。您 可能 仍然 运行 陷入其他问题,具体取决于您在加密数据时使用的填充类型(如果有),但您没有提供足够的信息来得出任何结论


如评论中所述,-k 小写和 -K 大写之间存在差异。它与您的情况相关,您可能使用了错误的情况。查看 the openssl enc man page 了解更多信息,并阅读有关 -nosalt 选项的更多信息。