Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I had a java code and I had to transform it in C# which is as below
Encryption:
public String encrypt(String value)
{
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
AesManaged tdes = new AesManaged();
tdes.Key = UTF8.GetBytes(securityKey);
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform crypt = tdes.CreateEncryptor();
byte[] plain = Encoding.UTF8.GetBytes(value);
byte[] cipher = crypt.TransformFinalBlock(plain, 0, plain.Length);
String encryptedText = Convert.ToBase64String(cipher);
return encryptedText;
}
Now I am trying to write the reversal process
public String decrypt(String value)
{
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
AesManaged tdes = new AesManaged();
tdes.Key = UTF8.GetBytes(securityKey);
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform crypt = tdes.CreateDecryptor();
byte[] plain = Encoding.UTF8.GetBytes(value);
byte[] cipher = crypt.TransformFinalBlock(plain, 0, plain.Length);
String encryptedText = Convert.ToBase64String(cipher);
return encryptedText;
}
But the reversal is not working.
Error: An exception of type
'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll but was not handled in user code
Additional information: Padding is invalid and cannot be removed.
Stack Trace:
System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at redis2.Crypto.AESECBPKCS5PaddingEncryptor.decrypt(String value) in e:\TestApplication\Redis\redis2\redis2\Crypto\AESECBPKCS5PaddingEncryptor.cs:line 53
at redis2.WebForm1.Page_Load(Object sender, EventArgs e) in e:\TestApplication\Redis\redis2\redis2\WebForm1.aspx.cs:line 14
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
update 1
public String decrypt(String value)
{
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
AesManaged tdes = new AesManaged();
tdes.Key = UTF8.GetBytes(securityKey);
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform crypt = tdes.CreateDecryptor();
// value = Convert.FromBase64String(value);
byte[] plain = Convert.FromBase64String(value);
byte[] cipher = crypt.TransformFinalBlock(plain, 0, plain.Length);
String encryptedText = Convert.ToBase64String(cipher);
return encryptedText;
}
With encryption and decryption code, it's not uncommon for you to perform at least one other conversion of the data along it's way through the encryption code. When writing the decryption code, you need to make sure you apply the reverse of each transformation in the reverse order.
So, in your encryption code, we have
[string] --UTF8--> [byte[]] --Encrypt--> [byte[]] --Base64--> [string]
With your original decryption code, we have
[string] --UTF8--> [byte[]] --Decrypt--> [byte[]] --Base64--> [string]
But that's not doing the reverse transforms in the reverse order. Lets put them alongside each other with the decryption one reversed:
[string] --UTF8--> [byte[]] --Encrypt--> [byte[]] --Base64--> [string] --|
|
[gnirts] <--46esaB-- [[]etyb] <--tpyrceD-- [[]etyb] <--8FTU-- [gnirts] <-|
(The extra arrow at the end shows the transfer of the string by some other code from the return from encrypt to supplying it as a parameter to decrypt).
We can see that we're doing something UTF8 related when we should be doing something to undo Base 64 encoding, and we're doing something Base64 related when we should be doing something UTF8 related.
So the correction is to base 64 decode the passed in string to decrypt and to UTF8 decode the result after decryption:
public String decrypt(String value)
{
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
AesManaged tdes = new AesManaged();
tdes.Key = UTF8.GetBytes(securityKey);
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform crypt = tdes.CreateDecryptor();
byte[] plain = Convert.FromBase64String(value);
byte[] cipher = crypt.TransformFinalBlock(plain, 0, plain.Length);
String encryptedText = Encoding.UTF8.GetString(cipher);
return encryptedText;
}
I'd usually recommend that when people are working with decryption, they start as simple as possible and then build up from there. The simplest thing to have gotten right first here would have been something that accepted a byte[] and returned a byte[] (for both methods) and can successfully round trip a byte array. Then add string encoding support for either the plaintext or the ciphertext but not both. Confirm that round trips. Then add another encoding. A zip layer. etc.
(This is also my recommended strategy for encrypt with language 1, decrypt with language 2. First write methods that can round trip successfully in both languages with all necessary transformations, then do the work of making them interoperate)
tdes.Key = UTF8.GetBytes(securityKey);
Is always the wrong way to get a key from a string.
When you have a password, use Rfc2898DeriveBytes
when you need to pass a random binary key, use Convert.FromBase64String()
String encryptedText = Encoding.UTF8.GetString(cipher);
Is the wrong way to transport binary data as text. This won't even round-trip because UTF8 has escape sequences to encode non-ASCII tokens. And you can't break those up.
Use Convert.ToBase64String(byte[])
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I try to convert this code to php, but i can't and always i get different result in C# and PHP
Here is my C# code for encrypt and decrypt :
private static readonly byte[] initVectorBytes = Encoding.ASCII.GetBytes("1234567812345678");
private const int keysize = 256;
private string pass = "sample";
public static string Encrypt(string plainText, string passPhrase)
{
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
return Convert.ToBase64String(cipherTextBytes);
}
public static string Decrypt(string cipherText, string passPhrase)
{
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
and this is my php code :
$iv = "1234567812345678";
$out = null;
$key = "sample";
foreach ($iv as $i) { $out .= chr(ord(substr($i,0,1))); }
$res = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string, MCRYPT_MODE_CBC, implode($out));
The keys are not the same. C# is extending the key with PasswordDeriveBytes which is a good method. PHP mcrypt is extending they key with nulls. You need the extended (256-bit) keys to be the same.
The padding is not the same. Unencrypted data needs to be a multiple of the block size (128-bits for AES) and if it isn't always that padding must to be added. C# is not specifying any padding and will expect the data to be a multiple of the block size (128-bits). PHP will by default add null padding which is non-standard and will not work for binary data. You need to add common padding, the standard is PKCS#7 (aka PKCS#5), See PKCS#7 padding. C# supports PKCS#5 but for mcrypt you will have to do it in your code (the mcrypt developers were Bozos and did not provide standard padding).
Rijndael supports multiple bock sizes, it is not clear what the C# default block size is. If what you want is AES (it should be) the block size needs to be 128-bits.
Given that the MSDN documentation does not specify defaults it is best to explicitly set the block size, key size, mode and padding.
Your PHP code will not run on PHP 5.6 as the key size is wrong, it must be 32 bytes.
Said that, on previous versions PHP was padding the key with \0's to reach the correct key length, but in C# you're creating derived bytes (what indeed is correct) to get enough bytes for your key, which ends in different keys used on C# and PHP.
As a proof, create a key with 32 bytes (32 chars) and use directly those 32 bytes as key, both in PHP and C#, in that way it should work.
But at the end you will need a common way to derive the bytes both on PHP and C# to finally have a consistent keying code, an example can be to use a SHA-256 hash to generate the key.
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'm using this function to Encrypt/Decrypt data using AES because it looked simple and clean (googl'ed code)
public static string Encrypt(string toEncrypt)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes("3a8114db34d5623d4fd1ee0fb0ga7a73"); // 256-AES key
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7; // better lang support
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string toDecrypt)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes("3a8114db34d5623d4fd1ee0fb0ga7a73"); // AES-256 key
byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7; // better lang support
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString(resultArray);
}
I'm trying to encrypt the data "test garbage" and thats what i receive back:
YfhyS3GE/liPCaXR0cMHfQ==
However, I tried the same key/phrase on a lot of online-aes encrypt/decrypt and all of them are returning
U2FsdGVkX184u0/vPgA/B0rxofp5Iuqm7hfn4+QZAhg=
Can anyone actually tell me whats wrong?
"3a8114db34d5623d4fd1ee0fb0ga7a73" is hex encoded 128 bit key not a utf8 encoded 256 bit key.
That said simple and clean doesn't necessarily mean correct. For example, the code your using does use a random IV, but doesn't include it in the wire format, you'll never be able to decrypt what you encrypt.
I have a cut and paste style simple code sample that I try to keep up to date and reviewed that uses authenticated encryption using AES:
Modern Examples of Symmetric Authenticated Encryption of a string. C#
First a few issues with your code. Apparently Google doesn't always return the best code on top.
You are getting a key through the UTF8 encoding, which is silly. This produces a very weak key:
// 256-AES key
byte[] keyArray = UTF8Encoding.UTF8.GetBytes("3a8114db34d5623d4fd1ee0fb0ga7a73");
You are using CBC mode but the IV is not (explicitly) set.
Then you compare to some online-aes encrypt/decrypt services and you see a difference. That's because they probably (hopefully) work different.
The main thing here is that your 2 methods are a match and you can round-trip your data. But a good encryption would use a different way to get Key and IV.
I'm not exactly sure why you see a different (smaller) length encrypted data but that's up to a whole list of settings : Key length, Padding mode etc.
PHP code
define('SECRET', 'Your key here');
$data = 'test';
$enc = mcrypt_cbc(MCRYPT_TRIPLEDES, SECRET, $data, MCRYPT_ENCRYPT, '12345678');
$url .= urlencode($password);
C# code
byte[] key = ec.GetBytes("Your key here");
byte[] iv = ec.GetBytes("12345678");
byte[] data = ec.GetBytes("test");
byte[] enc = new byte[0];
TripleDES tdes = TripleDES.Create();
tdes.IV = iv;
tdes.Key = key;
tdes.Mode = CipherMode.CBC;
tdes.Padding = PaddingMode.Zeros;
ICryptoTransform ict = tdes.CreateEncryptor();
enc = ict.TransformFinalBlock(data, 0, data.Length);
string szEnc = HttpContext.Current.Server.UrlEncode(
Encoding.ASCII.GetString(enc)
);
My problem: The value of $url in PHP and szEnc in c# is not same.
Question: what wrong in my c# code?
A lot of things can go wrong - but I've seen quite a lot of encoding (i.e. non cryptographic) issue when dealing with string and byte[].
Never assume they will convert into anything, including ASCII.
Encoding.ASCII.GetString(enc)
If you have unprintable characters, NUL... then this will not be part of the returned string and won't be url-encoded. This is ask true for PHP but it does not means it follows the same rule in every case.
Also I can't tell you what code like:
ec.GetBytes("Your key here");
will do ?!? If you're using an Unicode encoder then it won't give you the same as an ASCII encoder.
Beside encoding also check that the PaddingMode you use match the one used by PHP.
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.