First, read man enc
for openssl. -iv
is ignored when -k
is used. You probably want capital -K
. Second, the key and iv values are hexadecimal when used with the openssl tool, if your C# is using the same string as the command line then you need to do appropriate conversions rather than Encoding.ASCII.GetBytes
(a 7 bit encoding is never the right answer anyway).
For your plain text, you might as well use Encoding.UTF8.GetBytes/GetString
since it is backwards compatible with ASCII.
If for some reason you actually want to use lowercase -k
, a password to generate both the key and iv, that is much more difficult as openssl uses it's own key derivation scheme. Also, it is dangerous to use with the -nosalt
flag.
-nosalt:
doesn't use a salt in the key derivation routines. This option SHOULD
NOT be used except for test purposes or compatibility with ancient
versions of OpenSSL and SSLeay.
One of the reasons this is dangerous, is due to the fact that IV's should not be predictable or reused for AES-CBC and if you don't use a salt, the passphrase will always produce the same key with the same IV that opens you up to several attacks and can leak info about the plaintext.
You can find out how to derive from passphrase, the same key and IV as openssl from this blog post Decrypting OpenSSL AES files in C# although it is specifically for AES-128 the comments lead you to how to modify for aes-256, from man EVP_BytesToKey
:
Hash0 = ''
Hash1 = MD5(Hash0 + Password + Salt)
Hash2 = MD5(Hash1 + Password + Salt)
Hash3 = MD5(Hash2 + Password + Salt)
Key = Hash1 + Hash2
IV = Hash3
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…