I am trying to re-create this openssl command in C#:
openssl enc –e –aes-256-cbc –k SecretPhrase1234 –in profile.xml –out profile.cfg
This encrypted file will then be loaded by a device and the process is described as this:
A lower case –k precedes the secret key, which can be any plain text phrase and is used to generate a random 64-bit salt. Then, in combination with the secret specified with the –k argument, it derives a random 128-bit initial vector, and the actual 256-bit encryption key.
So, in my C# application I need to create a random 64 bit salt using my "SecretPhrase1234". Then I need to derive a 128 bit IV and a 256 bit key. The device already has the secret phrase loaded onto it.
Here is my code:
AesManaged aes = new AesManaged();
// Encrypt the string to an array of bytes.
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("SecretPhrase1234", 8);
byte[] SALT = rfc.Salt;
PasswordDeriveBytes pdb = new PasswordDeriveBytes("SecretPhrase1234", SALT);
byte[] IV = rfc.GetBytes(aes.BlockSize/8);
//The next line doesn't work
byte[] KEY = pdb.CryptDeriveKey("AES", "SHA1", aes.KeySize, IV);
aes.Key = KEY;
aes.IV = IV;
byte[] encrypted = AESEncryption.EncryptStringToBytes(plainConfig,
aes.Key, aes.IV);
tw.WriteLine(Encoding.ASCII.GetString(encrypted));
tw.Close();
I found a .NET implementation of OPENSSL which perfectly suits my needs. It is here:
openssl using only .NET classes
Related
I am searching for C# Code to reproduce the following openssl command.
openssl enc -d -aes-256-cbc -in my_encrypted_file.csv.enc -out my_decrypted_file.csv -pass file:key.bin
Additional information:
The encrypted file in present as byte[]
The key.bin is a byte[] with length of 256 (the key is obtained by a more simple decryption of yet another file, which i managed to realize in C#).
I have been trying out various examples found by searching the web.
The problem is, that all of these examples require an IV (initialization vector). Unfortunately, I don't have an IV and no one on the team knows what this is or how it could be defined.
The openssl command does not seem to need one, so I am a bit confused about this.
Currently, the code, I am trying with, looks as follows:
public static string DecryptAesCbc(byte[] cipheredData, byte[] key)
{
string decrypted;
System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
aes.KeySize = 256;
aes.Key = key;
byte[] iv = new byte[aes.BlockSize / 8];
aes.IV = iv;
aes.Mode = CipherMode.CBC;
ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(cipheredData))
{
using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decrypted = sr.ReadToEnd();
}
}
return decrypted;
}
}
The code fails saying that my byte[256] key has the wrong length for this kind of algorithm.
Thanks for any help with this!
Cheers, Mike
The posted OpenSSL statement uses the -pass file: option and thus a passphrase (which is read from a file), see openssl enc. This causes the encryption process to first generate a random 8 bytes salt and then, together with the passphrase, derive a 32 bytes key and 16 bytes IV using the (not very secure) proprietary OpenSSL function EVP_BytesToKey. This function uses several parameters, e.g. a digest and an iteration count. The default digest for key derivation is MD5 and the iteration count is 1. Note that OpenSSL version 1.1.0 and later uses SHA256 as default digest, i.e. depending on the OpenSSL version used to generate the ciphertext, the appropriate digest must be used for decryption. Preceding the ciphertext is a block whose first 8 bytes is the ASCII encoding of Salted__, followed by the 8 bytes salt.
Therefore, the decryption must first determine the salt. Based on the salt, together with the passphrase, key and IV must be derived and then the rest of the encrypted data can be decrypted. Thus, first of all an implementation of EVP_BytesToKey in C# is required, e.g. here. Then a possible implementation could be (using MD5 as digest):
public static string DecryptAesCbc(byte[] cipheredData, string passphrase)
{
string decrypted = null;
using (MemoryStream ms = new MemoryStream(cipheredData))
{
// Get salt
byte[] salt = new byte[8];
ms.Seek(8, SeekOrigin.Begin);
ms.Read(salt, 0, 8);
// Derive key and IV
OpenSslCompat.OpenSslCompatDeriveBytes db = new OpenSslCompat.OpenSslCompatDeriveBytes(passphrase, salt, "MD5", 1);
byte[] key = db.GetBytes(32);
byte[] iv = db.GetBytes(16);
using (Aes aes = Aes.Create())
{
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = iv;
// Decrypt
ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV);
using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs, Encoding.UTF8))
{
decrypted = sr.ReadToEnd();
}
}
}
}
return decrypted;
}
Note that the 2nd parameter of DecryptAesCbc is the passphrase (as string) and not the key (as byte[]). Also note that StreamReader uses an encoding (UTF-8 by default), which requires compatible data (i.e. text data, but this should be met for csv files). Otherwise (i.e. for binary data as opposed to text data) StreamReader must not be used.
I am using a Java based configuration management tool called Zuul which supports encrypting sensitive configuration information using various encryption schemes.
I have configured it to use below scheme for my data
AES (Bouncy Castle)
Name: PBEWITHSHA256AND128BITAES-CBC-BC
Requirements: Bouncy Castle API and JCE Unlimited Strength Policy Files
Hashing Algorithm: SHA256
Hashing Iterations: 1000
Now when reading my configuration data back, I need to decrypt the information before I can use it and the documentation provides below information around this topic.
The encrypted values produced by Jasypt (and thus Zuul) are are prefixed with the salt (usually 8 or 16 bytes depending on the algorithm requirements). They are then Base64 encoded. Decrypting the results goes something like this:
Convert the Base64 string to bytes
Strip off the first 8 or 16 bytes as the salt
Keep the remaining bytes for the encrypted payload
Invoke the KDF function with the salt, iteration count and the password to create the secret key.
Use the secret key to decrypt the encrypted payload
More details here: Zull Encryption wiki
Based on above details, I have written below code (and my knowledge around security is very limited)
public static string Decrypt(string cipher, string password)
{
const int saltLength = 16;
const int iterations = 1000;
byte[] cipherBytes = Convert.FromBase64String(cipher);
byte[] saltBytes = cipherBytes.Take(saltLength).ToArray();
byte[] encryptedBytes = cipherBytes.Skip(saltLength).ToArray();
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, saltBytes, iterations);
byte[] keyBytes = key.GetBytes(16);
AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider();
aesAlg.KeySize = 256;
aesAlg.BlockSize = 128;
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
MemoryStream msDecrypt = new MemoryStream(encryptedBytes);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
StreamReader srDecrypt = new StreamReader(csDecrypt);
return srDecrypt.ReadToEnd();
}
I configured Zuul to use below password for the encryption
SimplePassword
And now I have an encrypted string given to me by Zuul and I need to decrypt it
p8C9hAHaoo0F25rMueT0+u0O6xYVpGIkjHmWqFJmTOvpV8+cipoDFIUnaOFF5ElQ
When I try to decrypt this string using above code, I get below exception
System.Security.Cryptography.CryptographicException : Padding is invalid and cannot be removed.
As I mentioned earlier, my knowledge around this topic is limited and I am not able to figure out if the information provided in the documentation is not enough, if I am doing something wrong while writing the decryption routine or should I be using bouncy castle for decryption as well.
Any help with this will be much appreciated.
According to Zuul documentation they are deriving both key and iv from the password/salt.
So you should derive 256+128 bits (i.e. 48 bytes), and use first 32 bytes as the key, and next 16 bytes as IV.
And this should be done in one operation, not as consequent calls to key.DeriveBytes.
I resorted to Bouncy Castle for decryption instead since that is used by Zuul as well.
Here is the code that works
public static string Decrypt(string cipher, string password)
{
const int saltLength = 16;
const int iterations = 1000;
const string algSpec = "AES/CBC/NoPadding";
const string algName = "PBEWITHSHA256AND128BITAES-CBC-BC";
byte[] cipherBytes = Convert.FromBase64String(cipher);
byte[] saltBytes = cipherBytes.Take(saltLength).ToArray();
byte[] encryptedBytes = cipherBytes.Skip(saltLength).ToArray();
char[] passwordChars = password.ToCharArray();
Asn1Encodable defParams = PbeUtilities.GenerateAlgorithmParameters(algName, saltBytes, iterations);
IWrapper wrapper = WrapperUtilities.GetWrapper(algSpec);
ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(algName, passwordChars, defParams);
wrapper.Init(false, parameters);
byte[] keyText = wrapper.Unwrap(encryptedBytes, 0, encryptedBytes.Length);
return Encoding.Default.GetString(keyText);
}
I am attempting to use System.Security.Cryptography.AesManaged to encrypt a file in my .net application. It needs to be decrypted in an embedded Linux enviroment, so the .net libraries will not be available to me.
The code I have at the moment looks something like this:
string encPassword = "ABCDABCDABCDABCDABCDABCDABCDABCD";
string sourceFile = "myFile.txt";
string targetFile = "myFile.encrypted.txt";
FileStream fsInput = = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
FileStream fsOutput = new FileStream(targetFile, FileMode.OpenOrCreate, FileAccess.Write);
CryptoStream cryptoStream = null;
try
{
byte[] key = Encoding.ASCII.GetBytes(encPasswd);
byte[] IV = new byte[16];
Array.Copy(key, 0, IV, 0, 16);
AesManaged aes = new AesManaged();
aes.Key = key;
aes.IV = IV;
aes.BlockSize = 128;
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
ICryptoTransform encryptor = aes.CreateEncryptor();
cryptoStream = new CryptoStream(fsOutput, encryptor, CryptoStreamMode.Write);
byte[] buffer = new byte[BUFFER_LENGTH];
long bytesProcessed = 0;
long fileLength = fsInput.Length;
int bytesInCurrentBlock;
do
{
bytesInCurrentBlock = fsInput.Read(buffer, 0, BUFFER_LENGTH);
cryptoStream.Write(buffer, 0, bytesInCurrentBlock);
bytesProcessed = bytesProcessed + bytesInCurrentBlock;
}
while (bytesProcessed < fileLength);
return true;
}
// ...
This encrypts the file okay. Now I am trying to decrypt the file using a 3rd-party utility on Windows that is also supported in Linux, to give me confidence that the Linux developer will be able to decrypt it.
A quick search on SourceForge let me to Enqrypt. However, if I use Enqrypt on the encrypted file like this:
enqrypt.exe -d -aes -256 -cbc -k ABCDABCDABCDABCDABCDABCDABCDABCD myFile.encrypted.txt
where -d indicates decrypt, -256 indicates the key size, -cbc the mode, and -k preceding the key.
it doesn't give me the original file.
I have tried this with a few 3rd party utilities but I can't seem to decrypt it.
Are there any obvious errors with how I am attempting to encrypt and decrypt this file?
Update
In response to recommendations from #Paŭlo, I now have the following test code (don't worry, I plan to change the key and IV to be different):
byte[] key = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 };
byte[] IV = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 };
The block size is still 128 and the key size is still 256 in code.
I now try to decrypt the file using openssl like so:
openssl enc -d -aes-256-cbc -in c:\encrypted.txt -out c:\decrypted.txt -K 11223344556677881122334455667788 -iv 11223344556677881122334455667788
This results in the following error:
bad decrypt 11452:error:06065064:digital envelope routines:EVP_DecryptFinal:bad decrypt:evp_enc.c:450:
Any idea what I am doing wrong?
I found the solution to my problem with decrypting using openssl (in the Update section of the question).
Firstly, my key length was wrong (as suggested by #Paŭlo Ebermann) - it should have been 256 bits.
But the final problem was that I was setting the key size after the key:
AesManaged aes = new AesManaged();
aes.Key = key;
aes.IV = IV;
aes.BlockSize = 128;
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
If I changed the above code to the following, I could decrypt it using openssl:
AesManaged aes = new AesManaged();
aes.BlockSize = 128;
aes.KeySize = 256;
aes.Key = key;
aes.IV = IV;
aes.Mode = CipherMode.CBC;
Thanks to this answer which led me in the right direction, and thanks to everyone else for their answers!
This enqrypt tool seems to be quite silly:
It allows only direct input of the key, no base64 or hexadecimal encoding, which disallows any keys which are not
representable (or not easily typeable as command line parameters) in the used encoding.
It uses a fixed initialization vector of DUMMY_DUMMY_DUMM.
For CBC, the initialization vector should be essentially random, and not predictable by any attacker, if you use the same key for multiple messages.
You can work around the issue of fixed IV: Simply prepend your plaintext with one block (128 bits=16 bytes) of random data, encrypt with the fixed initialization vector, and strip this first block off again after decryption. As each block's ciphertext is used like the initialization vector for the next block, this should give enough randomization for the real data.
But as enqrypt is only A simple demonstrative command line tool, I think you should instead use either the openssl command line tool, as recommended by sarnold, or use the OpenSSL library functions directly (if you are writing a program there).
enqrypt probably should have thrown an error of some sort for not initializing the IV -- you've probably used an IV of all zero bytes (assuming C# initializes memory to zeros for you) when encrypting, so you should try to use all zero bytes when decrypting too. (Be sure to set the IV for real use.)
Update
Thanks for including the exact usage statement -- it made me curious enough to look at the enqrypt source code, which has the solution:
// dummy data, can be used as iv/key
unsigned char *gDummy = (unsigned char*)"DUMMY_DUMMY_DUMMY_DUMMY_DUMMY_DUMMY_DUMMY";
/* ... */
if (ALGO_AES == gAlgorithm) {
unsigned char *iv = (unsigned char*)malloc(AES_BLOCK_SIZE);
memcpy(iv, gDummy, AES_BLOCK_SIZE);
int rc, num=0;
if ((!gMem) && (gMode <= MODE_CBC)) {
// insert padding info for ECB/CBC modes
tblk[0] = gSize % AES_BLOCK_SIZE;
fwrite(tblk, 1, 1, ftar);
}
while (0 != (rc = fread(sblk, 1, AES_BLOCK_SIZE, fsrc))) {
switch (gMode) {
default:
case MODE_ECB: // AES ECB encrypt
AES_ecb_encrypt(sblk, tblk, &gEncAesKey, AES_ENCRYPT);
if (!gMem) fwrite(tblk, 1, AES_BLOCK_SIZE, ftar);
break;
case MODE_CBC: // AES CBC encrypt
AES_cbc_encrypt(sblk, tblk, AES_BLOCK_SIZE, &gEncAesKey, iv, AES_ENCRYPT);
if (!gMem) fwrite(tblk, 1, AES_BLOCK_SIZE, ftar);
break;
/* ... */
You never stood a chance, because the author of enqrypt has hard-coded the IV (not a good idea) to DUMMY_DUMMY_DUMM.
I have my pre generated AES key what i would like to use in C#. Can anybody point me to the right direction how to use pre generated AES key with RijndaelManaged object.
EDIT: I have the key in byte[] array and i need to encrypt a Stream.
I found these code samples online:
private static byte[] Decrypt(byte[] key, byte[] PGPkey)
{
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = key;
//rDel.Mode = CipherMode.ECB; // http://msdn.microsoft.com/en-us/library/system.security.cryptography.ciphermode.aspx
rDel.Padding = PaddingMode.PKCS7; // better lang support
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(PGPkey, 0, PGPkey.Length);
return resultArray;
}
private static byte[] Encrypt(byte[] key, byte[] PGPkey)
{
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = key;
//rDel.Mode = CipherMode.ECB; // http://msdn.microsoft.com/en-us/library/system.security.cryptography.ciphermode.aspx
rDel.Padding = PaddingMode.PKCS7; // better lang support
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(PGPkey, 0, PGPkey.Length);
return resultArray;
}
Im not getting any errors but after decryption the byte array is not the same as it was before going to the ecryption.
EDIT: I think i got it working, had to set the rDel.Mode = CipherMode.ECB;
If it worked when setting it to ECB mode, that is becuase it was using CBC mode before, which uses a randomly generated Initialization Vector when encrypting. Initialization Vectors randomize the cipher text so two identical peiced of data, encrypted with the same key, dont produce the same cipher text. You can grab the byte[] RijndaelManagedInstance.IV property and store that with your cipher text. Then when decrypting, set the same property to the Initialization Vector used to encrypt, and then you should recieve the same plain text after decryption.
You need the key as a byte[]. Then you assign it to the Key property.
For encrypting using the autogenerated IV is fine. But you need to store it with your encrypted data and put it into the decryptor to decrypt your data again.
Don't use ECB, CBC is a much better fit for your use.
I'd like to encrypt very little data (15 bytes to be exact) into a as short as possible (optimally, no longer than 16 bytes) message using a public key cryptography system.
The standard public key system, RSA, unfortunately produces messages as big as its keys, that is about 100 bytes, depending on key size.
To make things more difficult, I can only use .NET framework libraries, i.e. no third party.
I've read a little about elliptic curve cryptography in the wikipedia and the text there seems to suggest that key sizes there are usually much shorter than RSA keys.
Does this translate to short messages as well? Can the .NET ECDiffieHellmanCng class be used to de/encrypt messages? It seems to feature a different class structure then, say, RSA or the symmetric ciphers.
You can use ECDiffieHellman to encrypt messages. You have two options: Static-static ECDH and static-ephemeral ECDH:
For static-static ECDH the receiver will need to know the senders public key (this might or might not be an option in your application). You should also have some data that is unique for this message (it might be a serial-number you get from somewhere else in the protocol or database-row or whatever or it might be a nonce). You then use ECDH to generate a secret key and use that to encrypt your data. This will give you your desired encrypted data length of 16 bytes, but it is not completely asymmetric: the encryptor is also able to decrypt the messages (again: this might or might not be a problem in your application).
Static-ephemeral is a bit different: here the encryptor generates a temporary (ephemeral) EC keypair. He then uses this keypair together with the receivers public key to generate a secret key which can be used to encrypt the data. Finally he sends the public key of the ephemeral keypair to the receiver together with the encrypted data. This might fit better into your application, but the complete encrypted data will now be 2*32+16=80 bytes using ECDH-256 and AES (as GregS notes you can save 32 bytes by only sending the x-coordinate of the public-key, but I do not believe that .NET exposes the functionality to recalculate the y-coordinate).
Here is a small class that will do static-static ECDH:
public static class StaticStaticDiffieHellman
{
private static Aes DeriveKeyAndIv(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] nonce)
{
privateKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
privateKey.HashAlgorithm = CngAlgorithm.Sha256;
privateKey.SecretAppend = nonce;
byte[] keyAndIv = privateKey.DeriveKeyMaterial(publicKey);
byte[] key = new byte[16];
Array.Copy(keyAndIv, 0, key, 0, 16);
byte[] iv = new byte[16];
Array.Copy(keyAndIv, 16, iv, 0, 16);
Aes aes = new AesManaged();
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
return aes;
}
public static byte[] Encrypt(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] nonce, byte[] data){
Aes aes = DeriveKeyAndIv(privateKey, publicKey, nonce);
return aes.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
}
public static byte[] Decrypt(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] nonce, byte[] encryptedData){
Aes aes = DeriveKeyAndIv(privateKey, publicKey, nonce);
return aes.CreateDecryptor().TransformFinalBlock(encryptedData,0, encryptedData.Length);
}
}
// Usage:
ECDiffieHellmanCng key1 = new ECDiffieHellmanCng();
ECDiffieHellmanCng key2 = new ECDiffieHellmanCng();
byte[] data = Encoding.UTF8.GetBytes("TestTestTestTes");
byte[] nonce = Encoding.UTF8.GetBytes("whatever");
byte[] encryptedData = StaticStaticDiffieHellman.Encrypt(key1, key2.PublicKey, nonce, data);
Console.WriteLine(encryptedData.Length); // 16
byte[] decryptedData = StaticStaticDiffieHellman.Decrypt(key2, key1.PublicKey, nonce, encryptedData);
Console.WriteLine(Encoding.UTF8.GetString(decryptedData));
ECDiffieHellmanCNG is a derivation of the original Diffie-Hellman Key Exchange Protocol.
It is not intended for encrypting messages but rather calculating the same secret value on both ends.
Here is some information on ECDiffieHellmanCNG and its purpose.