Convert "AES-128-ECB" encryption code from PHP to C# - c#

I have a requirement where I need to convert some PHP code to C#.. following is the PHP Code that needs to be converted:
$data = "Hello World!";
$key = "RTc0MDkwMEEwMDYxQjc4Mg=="
$encRaw = openssl_encrypt($data, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
To convert this openssl encryption, I am using below C# code:
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
//aesAlg.IV = IV;
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
But somehow this is not giving me same result that PHP function is returning.
Can someone please help me to identify the issue in my code? Or suggest me what other changes should I do in my code so that I get the similar result that PHP function is returning.

Related

Decrypting stored in database encrypted data throws exception, using AES Encryption

I'm using Aes to encrypt and decrypt data. I have tested my Encrypt and Decrypt functions and they work, but when I try to decrypt stored in my database data it throws me
System.Security.Cryptography.CryptographicException: The input data is
not a complete block.
What I do before storing the bytes encryption is
string encryptedData = Encoding.UTF8.GetString(_securityService.AesEncryptToBytes(data));
// Proceed in adding the encryptedData to the database.
This is how I decrypt my encrypted data pulled from the database.
string data = _securityService.AesDecryptFromBytes(Encoding.UTF8.GetBytes(encryptedDataPulledFromMyDataBase));
My encryption method:
public byte[] AesEncryptToBytes(string plainText)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = IV;
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
My Decryption method:
public string AesDecryptFromBytes(byte[] cipherText)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
What I've done is basically copy pasting the code from Microsoft Docs. Both methods work when testing them, but when I try to Decrypt the Encrypted data which is the encryption bytes converted to string I get thrown the exception.

AES CTR decryption in C#

I've been given the task of decrypting some data in C# that was originally encrypted using PHP. Below is the PHP code
$opts = OPENSSL_RAW_DATA;
$res = openssl_decrypt($raw, 'aes-256-ctr', $keyhash, $opts, base64_decode($iv));
$raw is a byte array with a length of 312, $keyhash is 32 bytes and $iv is 16 bytes.
My problem is when I duplicate this code in C# I receive the following CryptographicException -
The input data is not a complete block.
Not being a crypto guy, I've tried many, many C# examples to try to get this to work, but pretty much always end up with the same error. This is one sample of the C# code I've tried.
static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an AesManaged object
// with the specified key and IV.
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.PKCS7;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
I've implemented the code in PHP and it works fine. I've also checked all the input byte arrays and they all exactly the same for both PHP and C#. In desperation I even implemented this in Java and again it works no problem.
SecretKeySpec keySpec = new SecretKeySpec(keyHash, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte [] original = cipher.doFinal(encData);
String plaintext = new String(original);
So what's up with the C# code and how can I make it work?
Thanks in advance.
OK. This is a duplicate question which has already been answered. I just missed the easy answer, which is here - Aes128CounterMode.cs. And this code will generate the correct result -
byte[] plainText = new byte[encData.Length];
Aes128CounterMode am = new Aes128CounterMode(iv);
ICryptoTransform ict = am.CreateEncryptor(keyHash, null);
ict.TransformBlock(encData, 0, encData.Length, plainText, 0);
return Encoding.UTF8.GetString(plainText);

AES/CBC encryption difference between C and C# implementations

I'm attempting to write C# implementation for AES CBC encryption of messages. The goal is to "properly" encrypt a message in C# so that the C implementation could properly decrypt it.
The C decryption implementation looks like the following (using openssl):
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) {
handleErrors();
}
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (unsigned char*)key, (unsigned char*)iv)) {
handleErrors();
}
if(1 != EVP_DecryptUpdate(ctx, (unsigned char*)plaintext, &len, (unsigned char*)encrypted_text, encrypted_text_len)) {
handleErrors();
}
plaintext_len = len;
if(1 != EVP_DecryptFinal_ex(ctx, (unsigned char*)plaintext + len, &len)) {
//Error happens here...
}
I get the following error:
error: digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:evp_enc.c:518:
C# code:
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
I have tried all of the padding modes, no luck. Any ideas of what the issue could be?
The error indicates that encrypted_text_len % 16 != 0.
You should double check that you aren't getting an accidental newline into your buffer if you're reading from a file.

Encryption Decryption in windows phone8 c#

I am trying to encrypt my data using the AES algorith.I got the functions from the MSDN site encryption decryption. What i am doing is i'm encrypting the data and storing it as a string using the following method
byte[] encrypted = EncryptStringToBytes_Aes(response, myAes.Key, myAes.IV);
string saveresponse = Convert.ToBase64String(encrypted);
and then i save it in IsolatedStorageSettings
settings.Add(merchantId, saveresponse);
But the problem i am facing is when the user comes after sometime and hits my page i check first in the IsolatedStorageSettings object if the data is present i pass that data to decrypt and process further.The step i use to decrypt is as follows
byte[] temp = Convert.FromBase64String(response);
response = DecryptStringFromBytes_Aes(temp, myAes.Key, myAes.IV);
But the above line gives me error "Value can not be null.
Parameter name: inputBuffer"
I am unable to find where i am going wrong.Can u guys please let me know what steps should be taken to make it up and running.
Here is the Encryption Code
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an AesManaged object
// with the specified key and IV.
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
and here is the decryption code
static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
try
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an AesManaged object
// with the specified key and IV.
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
catch (Exception ex) {
return "Error";
}
}
and on button1 click i call the encryption method
using (AesManaged myAes = new AesManaged())
{
byte[] encrypted = EncryptStringToBytes_Aes(response, myAes.Key, myAes.IV);
string saveresponse = Convert.ToBase64String(encrypted);
}
and on button 2 i call decryption method
using (AesManaged myAes = new AesManaged())
{
byte[] temp= Convert.FromBase64String(response)
response = DecryptStringFromBytes_Aes(temp, myAes.Key, myAes.IV);
}
The problem was the using (AesManaged myAes = new AesManaged()){} block what it does it generates the new key and IV for encryption and decryption.So while decryption the key and IV doesnt match hence the error generates.Just remove the using block and declare the Aesmanaged myAes object at global level and the problem is solved. So the final code would look like
AesManaged myAes = new AesManaged();
On button one click to encrypt;
byte[] encrypted = EncryptStringToBytes_Aes(response, myAes.Key, myAes.IV);
string saveresponse = Convert.ToBase64String(encrypted);
and button2 click to decrypt
byte[] temp = Convert.FromBase64String(response);
response = DecryptStringFromBytes_Aes(temp, myAes.Key, myAes.IV);
Thats it, happpy coding.

Reading encrypted cookie

I have used this example as a base, to read and write an encrypted cookie. Problem is that the decrypted string that gets returned contains invalid characters. i.e. the cookie value is
'MyValue'
and what gets returned is
Z!������3z�^��
This is the code I use:
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie myCookie = new HttpCookie("MyCookie");
string valString = "MyValue";
string keyAsString = "BJF8hXsXce7dhCWjGICNrnq1Gc8mWyMlODbiYvXTXCo=";
byte[] myKey = Convert.FromBase64String(keyAsString);
// Create a new instance of the AesManaged
// class. This generates a new key and initialization
// vector (IV).
using (AesManaged myAes = new AesManaged())
{
//Set default values as padding mode and ciphermode not supported in Silverlight
byte[] encrypted = EncryptStringToBytes_Aes(valString, myKey, myAes.IV);
myCookie.Value = Convert.ToBase64String(encrypted, 0, (int)encrypted.Length);
string roundtrip = DecryptStringFromBytes_Aes(Convert.FromBase64String(myCookie.Value), myAes.Key, myAes.IV);
}
//
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
}
And the encryption/decryption functions are:
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an AesManaged object
// with the specified key and IV.
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.ECB;
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an AesManaged object
// with the specified key and IV.
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.None;
aesAlg.Mode = CipherMode.ECB;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
Looks like some sort of encoding issue. At first I thought the problem was reading the cookie value itself. But even if I try to decrypt the value just encrypted i.e.
string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key,
myAes.IV);
I still get the same issue.
Not sure if this will help but the main goal is to just READ the cookie. Initially, the cookie will get created from a 3rd party PHP app using a shared key (hence I used the ECB CipherMode). This code is just a sample to make sure that I can read encrypted cookies.

Categories