I am getting exception of invalid length in time of decryption in AES algorithm in C#, while it's working fine in android code.
Android Code:
public byte[] decryp_decompress(byte[] raw, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
GZip gzip = new GZip();
byte[] decompressData = gzip.decompresses(decrypted);
return decompressData;
}
C# Code:
public byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
{
try
{
return rijndaelManaged.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
}
catch
{
throw;
}
}
And
public RijndaelManaged GetRijndaelManaged()
{
try
{
byte[] AESKey = new byte[] { **** };
var keyBytes = new byte[16];
var secretKeyBytes = AESKey;
Array.Copy(secretKeyBytes, keyBytes, Math.Min(keyBytes.Length, secretKeyBytes.Length));
return new RijndaelManaged
{
Mode = CipherMode.ECB,
Padding = PaddingMode.None,
KeySize = 128,
BlockSize = 128,
Key = keyBytes
};
}
catch
{
throw;
}
}
Getting exception in time of decryption of invalid length.
What could the issue be?
Edit:
I have made changes for decryption:
KeyParameter par = new KeyParameter(AESKey);
// SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IBufferedCipher cipher = CipherUtilities.GetCipher("AES/ECB/NoPadding");
cipher.Init(true, par);
// Gives me "pad block corrupted" error
byte[] output = new byte[(encryptedData.Length)];
int len = cipher.ProcessBytes(encryptedData, 0, encryptedData.Length, output, 0);
cipher.DoFinal(output, encryptedData.Length);
// byte[] output = cipher.DoFinal(encryptedData);
return output;
but getting exception of data not block size aligned.
My data saved in little endian format . so any please help me where i need to update the code.
Related
I'm creating an C# MVC application by calling Api, Its token encryption method is in PHP i want to convert it to C# code.Can any one help in conversion on below php code to c#?
PHP Code
<?php
//ini_set("display_errors", 1);
//ini_set("display_startup_errors", 1);
function encryptToken($token)
{
$cipher_method = 'aes-128-ctr';
$enc_key = openssl_digest
('*****************************', 'SHA256', TRUE);
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
$crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
unset($token, $cipher_method, $enc_key, $enc_iv);
return $crypted_token;
}
function createAccessToken(){
//$date = new DateTime("now", new DateTimeZone('Asia/Kolkata') );
//$now = $date('YmdHis');
$now = date("YmdHis");
$secret ='********************************';
$plainText = $now."::".$secret;
$encrypted = encryptToken($plainText);
return $encrypted;
}
$value="";
if($_POST){
if(isset($_POST['test'])){
$value= createAccessToken();
}
}
?>
So far i tried this much. But the token generated using this C# code will not validate in Api by using the same secret and password.
C# Code
public string GenerateToken()
{
var Date = DateTime.Now.ToString("yyyyMMddHHmmss");
var secret = "#############################";
string plainText = Date + "::" + secret;
var accessToken = EncryptString(plainText);
return accessToken;
}
public string EncryptString(string plainText)
{
try
{
string password = "************************";
// Create sha256 hash
SHA256 mySHA256 = SHA256Managed.Create();
byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
// Instantiate a new Aes object to perform string symmetric encryption
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.ECB;
encryptor.Padding = PaddingMode.None;
encryptor.BlockSize = 128;
// Create secret IV
var iv = generateIV();
// Set key and IV
byte[] aesKey = new byte[32];
Array.Copy(key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = iv;
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our Aes object
ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
// Convert the plainText string into a byte array
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
// Encrypt the input plaintext string
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
// Complete the encryption process
cryptoStream.FlushFinalBlock();
// Convert the encrypted data from a MemoryStream to a byte array
byte[] cipherBytes = memoryStream.ToArray();
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
// Convert the encrypted byte array to a base64 encoded string
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length) + "::" + ByteArrayToString(iv);
// Return the encrypted data as a string
return cipherText;
}
catch (Exception)
{
throw;
}
}
private static byte[] generateIV()
{
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] nonce = new byte[IV_LENGTH];
rng.GetBytes(nonce);
return nonce;
}
}
I had andriod code and I tried to convert it to c#. It's a simple Encryption class. But when I try to decrypt data with it I catch: Wrong algorithm: AES or Rijndael required.
Here is my converted code:
public static string decrypt(string data)
{
byte[] dataBytes = Convert.FromBase64String(data);
SecretKey secretKey = getSecretKey(hashTheKey("ABCD"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(2, secretKey, new IvParameterSpec(new byte[16]),
SecureRandom.getInstance("SHA1PRNG"));
var x = cipher.doFinal(dataBytes);
return System.Text.Encoding.UTF8.GetString(x);
}
public static SecretKey getSecretKey(char[] key)
{
var secretKeyType = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
var secretkey = secretKeyType.generateSecret(new PBEKeySpec(key,
System.Text.Encoding.UTF8
.GetBytes("ABCD"),
100, 128)).getEncoded();
return new SecretKeySpec(secretkey, "AES/CBC/PKCS5Padding");
}
public static char[] hashTheKey(string key)
{
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(System.Text.Encoding.UTF8.GetBytes(key));
return Convert.ToBase64String(messageDigest.digest()).ToCharArray();
}
Here is my original android code:
private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(key.getBytes());
return Base64.encodeToString(messageDigest.digest(),
Base64.NO_PADDING).toCharArray();
}
private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
return new SecretKeySpec(
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
.generateSecret(new PBEKeySpec(key,
"ABCD".getBytes("UTF8"),
100, 128)).getEncoded(), "AES");
}
public String decrypt(String data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeySpecException {
byte[] dataBytes = Base64.decode(data, Base64.DEFAULT);
SecretKey secretKey = getSecretKey(hashTheKey("ABCD"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(2, secretKey, new IvParameterSpec(new byte[16]),
SecureRandom.getInstance("SHA1PRNG"));
return new String(cipher.doFinal(dataBytes));
}
c# and java are using the same well-estabilished cryptography algorithms, but differs in approach how to invoke them. It is still possible to convert the code though.
One key point is difference in base64 encoding - C# always use padding.
Converted code goes like:
const int KeySize = 128;
static string HashTheKey(string key) {
String hashKey;
using (var sha = new SHA1Managed()) {
hashKey = Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(key)));
}
// beware - you're on C# now so remove the padding and add the newline to match java
return hashKey.Replace("=", "") + "\n";
}
static byte[] GetSecretKey(string password) {
var salt = Encoding.UTF8.GetBytes("JVAaVhAiddKAaghraikhmaini");
using (var pass = new Rfc2898DeriveBytes(password, salt, 65536)) {
return pass.GetBytes(KeySize / 8);
}
}
static void Main(string[] args) {
string encrypted = "vtlkQHTz7/oz2weuAAkLz2Q5c2yj2LGukF7SHJjT+TA8oRLixTQSXQ7dG1O736hyT1HJxcz0P4DzzVaO5chWKKSJQ2uPEpDQJu/fZGguqDw=";
byte[] encryptedBytes = Convert.FromBase64String(encrypted);
using (var aes = new AesManaged()) {
aes.KeySize = KeySize;
aes.Padding = PaddingMode.PKCS7;
aes.Key = GetSecretKey(HashTheKey("Android"));
// you're using the same init vector in your android code
aes.IV = new byte[16];
using (var decryptor = aes.CreateDecryptor()) {
// dumps {"barcode":"12345678","token":"cad603fc-1e53-4a95-9150-f1694baa07f9"}
Console.Out.WriteLine(Encoding.UTF8.GetString(decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length)));
}
}
}
C# does not handle the encryption algorithms as Android or java do you have to use either AES or Rijndael algorithm as you can see the error to covert to the simple text into Encrypted Base64 and vice versa you can use the following class in C#
public static class Stringcipher
{
// This constant is used to determine the keysize of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private const int Keysize = 256;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 1000;
public static string Encrypt(string plainText, string passPhrase)
{
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = Generate256BitsOfRandomEntropy();
var ivStringBytes = Generate256BitsOfRandomEntropy();
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 256;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
public static string Decrypt(string cipherText, string passPhrase)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 256;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
private static byte[] Generate256BitsOfRandomEntropy()
{
var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
using (var rngCsp = new RNGCryptoServiceProvider())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
}
I have a problem related to AES decryption on my server side.
When encrypting data in the android client and sending it to the WCF server, the server always return an exception like
System.Security.Cryptography.CryptographicException: Padding is
invalid and cannot be removed. at
System.Security.Cryptography.CapiSymmetricAlgorithm.DepadBlock(Byte[]
block, Int32 offset, Int32 count) at
System.Security.Cryptography.CapiSymmetricAlgorithm.TransformFinalBlock(Byte[]
inputBuffer, Int32 inputOffset, Int32 inputCount) at
System.Security.Cryptography.CryptoStream.FlushFinalBlock() at
WindowsFormsApplication1.Form1.Decrypt(Byte[] p_EncryptedMsg, Byte[]
p_key, Byte[] p_iv) in c:\users\omr\documents\visual studio
2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line
76 at WindowsFormsApplication1.Form1.button1_Click(Object sender,
EventArgs e) in c:\users\omr\documents\visual studio
2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line
94}
my android encryption is
public static String enc(String message) {
byte[] keyInBytes = KEY.getBytes();
byte[] encryptedData = null;
KeyGenerator kgen;
try {
kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(keyInBytes);
kgen.init(256, secureRandom);
SecretKey skey = kgen.generateKey();
key = skey.getEncoded();
try {
encryptedData = encrypt(key, message.getBytes());
Log.w("ENC ", new String(encryptedData));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return Base64.encodeToString(encryptedData, Base64.DEFAULT);
// return message;
}
private static byte[] encrypt(byte[] raw, byte[] testMessage)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, /* "PBEWithSHA1And128BitAES-CBC-BC" */
"AES");
final byte[] iv = KEY.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(testMessage);
try {
decrypt(raw, encrypted);
} catch (Exception e) {
e.getMessage();
// TODO: handle exception
}
return encrypted;
}
and my C# code is
public String Decrypt(byte[] p_EncryptedMsg, byte[] p_key, byte[] p_iv)
{
m_key = new byte[32];
m_iv = new byte[16];
Array.Clear(m_key, 0, 32);
Array.Clear(m_iv, 0, 16);
Array.Copy(p_key, m_key, p_key.Length > 32 ? 32 : p_key.Length);
Array.Copy(p_iv, m_iv, p_iv.Length > 16 ? 16 : p_iv.Length);
if (m_key == null || m_iv == null)
throw new ArgumentNullException("Key or IV is equal to null");
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
aesProvider.Key = m_key;
aesProvider.IV = m_iv;
aesProvider.Mode = CipherMode.CBC;
aesProvider.Padding = PaddingMode.PKCS7;
using (MemoryStream memStream = new MemoryStream())
{
CryptoStream decStream = new CryptoStream(memStream, aesProvider.CreateDecryptor(), CryptoStreamMode.Write);
decStream.Write(p_EncryptedMsg, 0, p_EncryptedMsg.Length);
decStream.FlushFinalBlock();
String res = System.Text.Encoding.Default.GetString(memStream.ToArray());
return res;
}
}
}
NOTE:
I can encrypt and decrypt the text again correctly in the android side.
Well, one problem I see is that your CipherMode on the .Net side should be ECB to match the Java side. Give that a shot and see if that works.
i found that the problem happened as a result of using SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
as the server side take only the keyInBytes from me not the randomized one, so he can't generate the correct decryption key.
C# code example
using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider())
{
aesCryptoServiceProvider.Key = key;
aesCryptoServiceProvider.IV = iv;
aesCryptoServiceProvider.Mode = CipherMode.CBC;
aesCryptoServiceProvider.Padding = PaddingMode.PKCS7;
using (MemoryStream memoryStream = new MemoryStream())
{
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesCryptoServiceProvider.CreateDecryptor(), CryptoStreamMode.Write);
cryptoStream.Write(p_EncryptedMsg, 0, encryptedMsg.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
I am using Windows Live Id service for logging and authentication for my application. I get a token in the response sent by the Windows Live Id Service after the user get authenticated. I wish to decode this token in order to obtain the Unique Identifier out of it.Here is the link which explains this better:
http://msdn.microsoft.com/en-us/library/bb676622.aspx
I see exceptions while debugging in visual studio when I try to create a CryptoStream Object although the code does not break.
But when I try to convert the stream to bytes it throws an error and the code breaks.
It says:
"Length of the data to decrypt is invalid"
Here is the code that I am using:
string token=""; //Token Sent by the service
string SecretKey = ""; //SecretKey Obtained while registering my application
byte[] cryptKey = derive(secretKey, "ENCRYPTION");
static byte[] derive(string secret, string prefix)
{
using(HashAlgorithm hashAlg = HashAlgorithm.Create("SHA256"))
{
const int keyLength = 16;
byte[] data = Encoding.Default.GetBytes(prefix+secret);
byte[] hashOutput = hashAlg.ComputeHash(data);
byte[] byteKey = new byte[keyLength];
Array.Copy(hashOutput, byteKey, keyLength);
return byteKey;
}
}
const int ivLength = 16;
token = HttpUtility.UrlDecode(token);
byte[] ivAndEncryptedValue = Convert.FromBase64String(token);
aesAlg = new RijndaelManaged();
aesAlg.KeySize = 128;
aesAlg.Key = cryptKey;
aesAlg.Padding = PaddingMode.PKCS7;
memStream = new MemoryStream(ivAndEncryptedValue);
byte[] iv = new byte[ivLength];
memStream.Read(iv, 0, ivLength);
aesAlg.IV = iv;
cStream = new CryptoStream(memStream, aesAlg.CreateDecryptor(), CryptoStreamMode.Read);
sReader = new StreamReader(cStream, Encoding.ASCII);
The next line of code throws error: "Length of the data to decrypt is invalid"
decodedValue = sReader.ReadToEnd(); //Throws error:"Length of the data to decrypt is invalid"
Does anyone have any idea as to what can be the reason behind this?
Any kind of help or guidance will be greatly appreciated.
Thank you in advance.
Regards,
Abhishek
Here is an example of something that I currently use when Decrypting a value
I hope that this will help you in regards to seeing what you have done incorrectly in your existing code
static string Decrypt()
{
byte[] keyBytes = Convert.FromBase64String("U6XksFkhWV4.......eo3fRg=="");
byte[] iv = Convert.FromBase64String("KLnP....wA=="");
byte[] cipherTextBytes = Convert.FromBase64String("Put the EncryptedText here");
var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, IV = iv, KeySize = 128, Key = keyBytes, Padding = PaddingMode.Zeros};
using (var decryptor = symmetricKey.CreateDecryptor())
using (var ms = new MemoryStream(cipherTextBytes))
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) {
var plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cs.Read(plainTextBytes, 0, plainTextBytes.Length);
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
I need to decrypt a string using Rijndael and those values:
key size - 192
block size - 128
key - cmdAj45F37I5ud2134FDg2fF
When I'm using the code below I get an error : string size illigle, can anyone help me?
public static string DecryptRijndael(string value, string encryptionKey)
{
var key = Encoding.UTF8.GetBytes(encryptionKey); //must be 16 chars
var rijndael = new RijndaelManaged
{
BlockSize = 128,
IV = key,
KeySize = 192,
Key = key
};
var buffer = Convert.FromBase64String(value);
var transform = rijndael.CreateDecryptor();
string decrypted;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
decrypted = Encoding.UTF8.GetString(ms.ToArray());
cs.Close();
}
ms.Close();
}
return decrypted;
}
One (big) problem is in using UTF8.GetBytes() to get the byte[] from string. It is hard to control the number of bytes and it is not very safe.
Use Rfc2898DeriveBytes.GetBytes() instead. And then you can specify the desired length.
But of course you have to do that while encrypting as well.
And I agrre with Luke's remarks about the IV
Can you see the comment in your code that says the key "must be 16 chars"? Your key looks more like 24 characters to me!
In this case you're re-using the key as the IV -- not recommended best practice anyway -- but the size of the IV must match the block size, which is set to 128 bits/16 bytes.
Having said that, the problem I just described should give you the error "Specified initialization vector (IV) does not match the block size for this algorithm", not "string size illigle", so this might be a red herring.
Error is because of the input being 64 bit encoded.
IV and key is not the same. IV is for salting. Anyway the error you are getting is because the input is 64bit encoded. so do this and the error will go.
var decodedEncryptionKey= Base64Decode(encryptionKey);
var key = Encoding.UTF8.GetBytes(decodedEncryptionKey);
here is the full code:
private string decyptInit(string toBeDecrypted, string key, string initVector)
{
var keyByte = Encoding.Default.GetBytes(key);
var decodedIV = Base64Decode(initVector);
var iv = Encoding.Default.GetBytes(decodedIV);
var rijndael = new RijndaelManaged
{
BlockSize = 128,
IV = iv,
KeySize = 192,
Key = keyByte
};
var buffer = Convert.FromBase64String(toBeDecrypted);
var transform = rijndael.CreateDecryptor();
string decrypted;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
decrypted = Encoding.UTF8.GetString(ms.ToArray());
cs.Close();
}
ms.Close();
}
return decrypted;
} public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}