AES Encryption Windows Phone 8.1 - c#

I need to do 128 bit AES encryption on an application in Windows Phone 8.1. I used the following code for Encrypting and Decrypting the data respectively:
private string GetEncryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Encoding.UTF8.GetBytes(content);
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, null);
return Encoding.UTF8.GetString(cipherText, 0, cipherText.Length);
}
private string GetDecryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Encoding.UTF8.GetBytes(content);
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Decrypt(key, data, null);
return Encoding.UTF8.GetString(cipherText, 0, cipherText.Length);
}
But the encryption and decryption doesn't seem to be working properly. It is getting encrypted to some unicode characters and throwing a crash on decrypting:
Length is not a multiple of block size and no padding is
selected.\r\nParameter name: ciphertext
What am I doing wrong here? Can someone please help?
EDIT
After a lot more time with Google, I found the following methods for encryption and decryption, but they doesn't seem to work either.
public string GetEncryptedContent(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
string encrypted = "";
try
{
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(input));
encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));
return encrypted;
}
catch (Exception ex)
{
return null;
}
}
public string GetDecryptedContent(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
string decrypted = "";
try
{
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
byte[] Decrypted;
CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
decrypted = Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
return decrypted;
}
catch (Exception ex)
{
return null;
}
}
EDIT 2
Finally managed to get the encryption working properly, but the decryption is still not working presumably because the encoding I am passing is not the right one:
private string GetEncryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Encoding.UTF8.GetBytes(content);
byte[] iv = new byte[128 / 8]; // Adding this solved the encryption issue.
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);
return Convert.ToBase64String(cipherText);
}
private string GetDecryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Convert.FromBase64String(content); // Believe this is where the issue is, but not able to figure it out.
byte[] iv = new byte[128 / 8]; // Added this to make the decryption work the same way.
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Decrypt(key, data, iv);
return Convert.ToBase64String(cipherText);
}

I finally solved the problem. The problem was with the text encoding. Using the correct encoding solved the issue. The working code below:
public static string EncryptAES(string content, string password)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(password);
byte[] data = Encoding.UTF8.GetBytes(content);
byte[] iv = new byte[keyMaterial.Length];
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);
return Convert.ToBase64String(cipherText);
}
public static string DecryptAES(string content, string password)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(password);
byte[] data = Convert.FromBase64String(content);
byte[] iv = new byte[keyMaterial.Length];
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Decrypt(key, data, iv);
return Encoding.UTF8.GetString(cipherText, 0, cipherText.Length);
}
WinRTCrypto is available as part of PCLCrypto.

Related

the problem of crypting data by C# on the server side and encrypting it by CryptoJS on the client side

I got stuck also a bit lost in C# and CryptoJS differences.i have two server side
functions to encrypt data by AES256 bit as follows;
public string EncryptText_PBKDF2(string input, string password)
{
// Get the bytes of the strings
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
// Hash the password with SHA256 for AES key
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesEncrypted = AES_Encrypt_PBKDF2(bytesToBeEncrypted, passwordBytes);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
private byte[] AES_Encrypt_PBKDF2(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
using (MemoryStream ms = new MemoryStream())
{
aes.KeySize = 256;
aes.BlockSize = 128;
aes.IV = MD5.Create().ComputeHash(passwordBytes);//16 byte
var PBKDF2_key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
aes.Key = PBKDF2_key.GetBytes(aes.KeySize / 8);//32 byte
aes.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
return encryptedBytes;
}
then i send it to view by a controller action;
string res = aesIsl.EncryptText_PBKDF2("my text", "my key");
ViewBag.Crypted1 = res;
on the client side i get it from a hidden field
<div id="crypted"><input id="hidden1" data-enc="#ViewBag.Crypted1" type="hidden" /></div>
and decrypt it by crypto-js library(i have 4 attempts indicated on top of them)
here is my decrypting function and attempts:
function AesleDesifrele_PBKDF2(ciphertext, pwd) {
var salt = "0000000000000000";
var iv = CryptoJS.MD5(CryptoJS.SHA256(CryptoJS.enc.Utf8.parse(pwd)));
//these are my attempts to decrypt
//ATTEMPT #1:
//returning object contains a word array but converting it to utf8 string
//causes "Malformed UTF-8 data" error
console.log(CryptoJS.AES.decrypt(ciphertext, pwd).toString(CryptoJS.enc.Utf8));
//ATTEMPT #2
var key = CryptoJS.PBKDF2(
CryptoJS.enc.Utf8.parse(pwd).toString(CryptoJS.enc.Utf8),
CryptoJS.enc.Hex.parse(salt),
{ keySize: 128 / 32, iterations: 1000 }
);
var decrypted = CryptoJS.AES.decrypt(
ciphertext,
key,
{ iv: iv }
);
//returning object contains a word array but converting it to utf8 string
//causes "Malformed UTF-8 data" error
console.log(decrypted.toString(CryptoJS.enc.Utf8));
//ATTEMPT #3
var raw = base64UrlDecode(ciphertext);
var iv1 = CryptoJS.lib.WordArray.create(CryptoJS.MD5(CryptoJS.SHA256(CryptoJS.enc.Utf8.parse(pwd))));;
var salt1 = CryptoJS.lib.WordArray.create(CryptoJS.enc.Hex.parse(salt));
var key1 = generateKey(pwd, salt1);
var ciphertextWords = CryptoJS.lib.WordArray.create(raw.words.slice(128 / 32 + 128 / 32));
var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: ciphertextWords });
var plaintextArray = CryptoJS.AES.decrypt(
cipherParams,
key1,
{ iv: iv1 }
);
console.log(CryptoJS.enc.Utf8.stringify(plaintextArray));
//returning object contains a word array but converting it to utf8 string
//returns nothing
//ATTEMPT #4
var iv2 = CryptoJS.MD5(CryptoJS.SHA256(CryptoJS.enc.Utf8.parse(pwd)));
var Pass = CryptoJS.enc.Utf8.parse(pwd);
var Salt = CryptoJS.enc.Utf8.parse(salt);
var key256Bits1000Iterations = CryptoJS.PBKDF2(Pass.toString(CryptoJS.enc.Utf8), Salt, { keySize: 256 / 32, iterations: 1000 });
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
});
var decrypted = CryptoJS.AES.decrypt(cipherParams, key256Bits1000Iterations, { mode: CryptoJS.mode.CBC, iv: iv2, padding: CryptoJS.pad.Pkcs7 });
console.log(decrypted.toString(CryptoJS.enc.Utf8));
//returning object contains a word array but converting it to utf8 string
//returns nothing
}
this is the function to generate key for CryptoJs decrypt
function generateKey(secret, salt) {
return CryptoJS.PBKDF2(
secret,
salt,
{
keySize: this.keySize / 32, // size in Words
iterations: 1000,
hasher: CryptoJS.algo.SHA256
}
);
}
this is the conversion function i use
function base64UrlDecode(str) {
return CryptoJS.enc.Base64.parse(str.replace(/\-/g, '+').replace(/\_/g, '/'));
}
even though i control params on the client(cyphertext,password,IV and the salt) are exactly the same with the server,CryptoJS.decrypt returns nothing without any error.i guess i miss converting something to another in order C# to be compatible with CryptoJs.
any advice welcomes.
thanks in advance.

AES encryption and decryption in ASP

I'm developing an app written by C# and UWP(Universal Windows Platform).
here is my code for UWP :
public string AES_Encrypt(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
string encrypted = "";
try
{
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(input));
encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));
return encrypted;
}
catch (Exception)
{
return null;
}
}
public string AES_Decrypt(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
string decrypted = "";
try
{
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
byte[] Decrypted;
CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
return decrypted;
}
catch (Exception ex)
{
return null;
}
}
This works perfectly but I have to write an decryption for ASP just like this but I don't know how can I write this in ASP because these codes doesn't work on ASP.
I would appreciate it if you help me.
Thanks

C# UTF8 Encoding issue with AES Encryption

I'm creating a TCP based chat client. I'm trying to Encrypt some of the data with AES (more security) I have a AES encryption class and it uses UTF-8 by default as the out going and incoming Encoding type. But for some reason when i pass the information over the TCPClient (using UTF-8) and get it the other side it is throwing an error:
`System.Security.Cryptography.CryptographicException: Length of the data to decrypt is invalid.
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()`
So I recreated the problem without using the TCP client, just taking the AES encrypted data and putting it through a UTF-8 Encoding system that gets the string of the byte array then re-gets the byte array all using UTF-8 (basically the same thing as what happens over the network (without the string))
This method works:
string dataToEncrypt = "Hello World";
byte[] key = Encryption.AesEncryption.GenerateKey(32);
byte[] iv = Encryption.AesEncryption.GenerateKey(16);
byte[] encrypted = Encryption.AesEncryption.EncryptString(dataToEncrypt, key, iv);
string decrypted = Encryption.AesEncryption.DecryptedBytes(encrypted, key, iv);
The method doesn't work (throws the error from above)
Encoding encoding = Encoding.UTF8;
string dataToEncrypt = "Hello World";
byte[] key = Encryption.AesEncryption.GenerateKey(32);
byte[] iv = Encryption.AesEncryption.GenerateKey(16);
byte[] encrypted = Encryption.AesEncryption.EncryptString(dataToEncrypt, key, iv);
string encstring = encoding.GetString(encrypted);
byte[] utf8encrypted = encoding.GetBytes(encstring);
string decrypted = Encryption.AesEncryption.DecryptedBytes(utf8encrypted, key, iv);
What am i doing wrong?
This is my Encryption Class:
public sealed class AesEncryption
{
private byte[] Key;
public Encoding Encoder = Encoding.UTF8;
public AesEncryption(byte[] key)
{
Key = key;
}
public byte[] Encrypt(string text, byte[] iv)
{
var bytes = Encoder.GetBytes(text);
var rm = new RijndaelManaged();
var encrypter = rm.CreateEncryptor(Key, iv);
var ms = new MemoryStream();
var cs = new CryptoStream(ms, encrypter, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
var output = ms.ToArray();
cs.Close();
ms.Close();
return output;
}
public string Decrypt(byte[] encrypted, byte[] iv)
{
var ms = new MemoryStream();
var cs = new CryptoStream(ms,
new RijndaelManaged().CreateDecryptor(Key, iv),
CryptoStreamMode.Write);
cs.Write(encrypted, 0, encrypted.Length);
cs.FlushFinalBlock();
var output = ms.ToArray();
cs.Close();
ms.Close();
return Encoder.GetString(output);
}
public static byte[] EncryptString(string text, byte[] key, byte[] iv)
{
var ec = new AesEncryption(key);
return ec.Encrypt(text, iv);
}
public static string DecryptedBytes(byte[] encrypted, byte[] key, byte[] iv)
{
var ec = new AesEncryption(key);
return ec.Decrypt(encrypted, iv);
}
public static byte[] GenerateKey(int length)
{
Random rnd = new Random();
var chars = "1!2#3#4$5%6^7&8*9(0)-_=+qQwWeErRtTyYuUiIoOpP[{]}\\|aAsSdDfFgGhHjJkKlL;:'\"zZxXcCvVbBnNmM,<.>/?".ToCharArray();
string randomizedKey = "";
for (int i = 0; i < length; i++)
{
randomizedKey += chars[rnd.Next(0, chars.Length)];
}
return randomizedKey.ToByteArray();
}
}
UTF-8 does not perfectly represent the bytes. The short and simple answer is: Transmit bytes, not a UTF-8 string. If you must have a string, encode it in Base64.

AES cbc padding encryption/decryption on cross platform (.net c# and codename one bouncy castle)

Encryption/Decryption won't work in cross platform.
I have used this link to encrypt/decrypt text using bouncy castle AES cipher within codename one.
AES Encryption/Decryption with Bouncycastle Example in J2ME
While from server side (.net) , i am using this link to implement same method.
http://zenu.wordpress.com/2011/09/21/aes-128bit-cross-platform-java-and-c-encryption-compatibility/
now i am not getting any error but encrypted from codename one will not getting fully decrypted on server side and vice a versa.
any one please help me out on this.
Code from Codename one:
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;
public class Test
{
private static PaddedBufferedBlockCipher cipher = null;
public static void main(String[] args)
{
try
{
byte key[] = "MAKV2SPBNI992122".getBytes("UTF-8");
byte[] iv = new byte[16];
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(
new AESEngine()) );
//Encryption
String plainText = "Hello How are you !2#&*()% 123456#";
byte[] plainData = plainText.getBytes("UTF-8");
KeyParameter keyParam = new KeyParameter(key);
CipherParameters ivAndKey = new ParametersWithIV(keyParam, iv);
cipher.init(true, ivAndKey);
byte[] ciptherBytes = cipherData(plainData); //48
String cipherText = new String(Base64.encode(ciptherBytes), "UTF-8");//FileUtil.getStringFromByteArray(Base64.encode(ciptherBytes));
System.out.println("encrypted >> "+cipherText);
//Decryption
byte[] cipherData = Base64.decode(cipherText);
ivAndKey = new ParametersWithIV(keyParam, iv);
cipher.init(false, ivAndKey);
plainText = new String(cipherData(cipherData), "UTF-8");//FileUtil.getStringFromByteArray(cipherData(cipherData));
System.out.println("decrypted >> "+plainText);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static byte[] cipherData(byte[] data)
throws CryptoException
{
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
Code from .net:
public static RijndaelManaged GetRijndaelManaged(String secretKey)
{
var keyBytes = new byte[16];
var secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
Array.Copy(secretKeyBytes, keyBytes, Math.Min(keyBytes.Length, secretKeyBytes.Length));
return new RijndaelManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
KeySize = 128,
BlockSize = 128,
Key = keyBytes,
IV = keyBytes
};
}
public static byte[] EncryptCBC(byte[] plainBytes, RijndaelManaged rijndaelManaged)
{
return rijndaelManaged.CreateEncryptor()
.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
}
public static byte[] DecryptCBC(byte[] encryptedData, RijndaelManaged rijndaelManaged)
{
return rijndaelManaged.CreateDecryptor()
.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
}
public static String EncryptCBCStr(String plainText, String key)
{
var plainBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(EncryptCBC(plainBytes, GetRijndaelManaged(key)));
}
public static String DecryptCBCStr(String encryptedText, String key)
{
var encryptedBytes = Convert.FromBase64String(encryptedText);
return Encoding.UTF8.GetString(DecryptCBC(encryptedBytes, GetRijndaelManaged(key)));
}
// call
var PlainText = "Hello How are you !2#&*()% 123456#";
var EncryptionKey = "MAKV2SPBNI992122";
var cypherCBC = EncryptCBCStr(PlainText, EncryptionKey);
var decryptCBC = DecryptCBCStr(cypherCBC, EncryptionKey);
Thanks in adv.
This issue has been fixed...it is just key/IV bytes issue.as in .net there is same key and IV when in java i have used different IV.
correction in java code:
instead of this
byte key[] = "MAKV2SPBNI992122".getBytes("UTF-8");
byte[] iv = new byte[16];
use this.
byte key[] = "MAKV2SPBNI992122".getBytes("UTF-8");
byte[] iv = "MAKV2SPBNI992122".getBytes("UTF-8");

AES decrypt file data and write to disk

I am trying to decrypt file data and write to disk. It's creating the file but it is corrupted. Could you please let me know if there are any suggestions. I am using AES 256 algorithm.
column_data = string_data //base64 encoded string
byte[] data_bytes = Convert.FromBase64String(column_data);
string decodedString = Encoding.UTF8.GetString(data_bytes);
bytes[] decrypted = DecryptAESText(decodedString, secret, iv);
File.WriteAllBytes(#".\file.gif", decrypted );
// DecryptAESText returns the decrypted text, receives text in Base64
public static byte[] DecryptAESText(string cipheredText, byte[] Key, byte[] IV)
{
IBufferedCipher cipher = InitAESCipher(false, Key, IV);
string plainText = string.Empty;
byte[] plainBytes = null;
try
{
byte[] cipheredBytes = Convert.FromBase64String(cipheredText);
plainBytes = new byte[cipher.GetOutputSize(cipheredBytes.Length)];
plainBytes = cipher.DoFinal(cipheredBytes);
}
catch (Exception e)
{
Console.WriteLine(e.ToString() + "Issue in DecryptAESText column Name:");
}
return plainBytes;
}

Categories

Resources