This question already has answers here:
Encrypting & Decrypting a String in C# [duplicate]
(7 answers)
Closed 6 years ago.
public string EncryptPwd(String strString)
{
int intAscii;
string strEncryPwd = "";
for (int intIndex = 0; intIndex < strString.ToString().Length; intIndex++)
{
intAscii = (int)char.Parse(strString.ToString().Substring(intIndex, 1));
intAscii = intAscii + 5;
strEncryPwd += (char)intAscii;
}
return strEncryPwd;
}
This is my code.Please suggest me it is right way or not.
you can use this code:
Encrypt string with password:
public static string EncryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(Message);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
and Decrypt String with password:
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
// Step 5. Bat dau giai ma chuoi
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
catch (Exception) { Results = DataToDecrypt; }
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
Do you have a way to decrypt that? Here is another answer on SO
private static readonly UTF8Encoding Encoder = new UTF8Encoding();
public static string Encrypt(string unencrypted)
{
if (string.IsNullOrEmpty(unencrypted))
return string.Empty;
try
{
var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));
if (encryptedBytes != null && encryptedBytes.Length > 0)
return HttpServerUtility.UrlTokenEncode(encryptedBytes);
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
public static string Decrypt(string encrypted)
{
if (string.IsNullOrEmpty(encrypted))
return string.Empty;
try
{
var bytes = HttpServerUtility.UrlTokenDecode(encrypted);
if (bytes != null && bytes.Length > 0)
{
var decryptedBytes = MachineKey.Unprotect(bytes);
if(decryptedBytes != null && decryptedBytes.Length > 0)
return Encoder.GetString(decryptedBytes);
}
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
I agree with all the previous answers (especially share pvv) but in case you really did want a Caesar Cipher (Caesar Cipher is a very weak encryption and should not be used in production), and if this is a learning exercise, then here is some code
string strString = "abcdefghijklmnopqrstuvwxyz";
string enc = String.Join("", strString.ToArray().Select(x =>(char)( 'a' + (x-'a'+5)%26)));
Console.WriteLine(enc);
Or using a for loop like you did
string strEncryPwd = "";
for (int index = 0; index < strString.ToString().Length; index++)
{
int plainChar = strString[index];
int encrypted = 'a' + (plainChar - 'a' + 5) % 26;
strEncryPwd += (char)encrypted;
}
Console.WriteLine(strEncryPwd);
Related
I am trying to decrypt that from the database. The Data is encrypted from the SQL Server
reportItems.DisabilityGroup = Cryptography.ASPEncrypter(reportItems.DisabilityGroup, true);
The above code is when I invoke the decryption method. It works for small data but fails for more data. I get the following order
System.Security.Cryptography.CryptographicException: 'Length of the data to decrypt is invalid.'
private static string DoEncrypt(string Message)
{
// Encrypt string
byte[] Results;
var UTF8 = new UTF8Encoding();
using (var HashProvider = new MD5CryptoServiceProvider())
{
var TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(PassPhrase));
//var TDESAlgorithm = new TripleDESCryptoServiceProvider()
//{
// Key = TDESKey,
// Mode = CipherMode.ECB,
// Padding = PaddingMode.PKCS7
//};
using (var TDESAlgorithm = new TripleDESCryptoServiceProvider())
{
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
if (Message == null)
return "";
var DataToEncrypt = UTF8.GetBytes(Message);
try
{
var Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return Convert.ToBase64String(Results);
}
private static string DoDecrypt(string Message)
{
// Decrypt string
byte[] Results;
var UTF8 = new UTF8Encoding();
using (var HashProvider = new MD5CryptoServiceProvider())
{
var TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(PassPhrase));
using (var TDESAlgorithm = new TripleDESCryptoServiceProvider())
{
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
//var DataToDecrypt = Convert.FromBase64String(Message);
var DataToDecrypt = new byte[0];
if (!IsBase64String(Message, out DataToDecrypt))
{
return Message;
}
try
{
var Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return UTF8.GetString(Results);
}
public static bool IsBase64String(string base64String, out byte[] bytes)
{
bytes = null;
if (string.IsNullOrEmpty(base64String) || base64String.Length % 4 != 0
|| base64String.Contains(" ") || base64String.Contains("\t") || base64String.Contains("\r") || base64String.Contains("\n"))
return false;
try
{
bytes = Convert.FromBase64String(base64String);
return true;
}
catch (Exception)
{
// Handle the exception
}
return false;
}
public static string ASPEncrypter(string PriorValue, bool Decrypt)
{
// Public function to encrypt/decrypt string
if (String.IsNullOrWhiteSpace(PriorValue))
return "";
var Result = string.Empty;
if (Decrypt)
Result = DoDecrypt(PriorValue);
else
Result = DoEncrypt(PriorValue);
return Result;
}
return System.Text.ASCIIEncoding.ASCII.GetString(ence); - the name 'ence' does not exist in the current context.
I am trying to decrypt text from a file that I am already encrypt.
public static string Decrypte(string encrypted)
{
var Check = Form1.verify;
string password = Form1.password;
if (Check == password)
{
byte[] textBytes = Convert.FromBase64String(encrypted);
AesCryptoServiceProvider endec = new AesCryptoServiceProvider();
endec.BlockSize = 128;
endec.KeySize = 256;
endec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
endec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
endec.Mode = CipherMode.CBC;
ICryptoTransform icrypt = endec.CreateDecryptor(endec.Key, endec.IV);
byte[] ence = icrypt.TransformFinalBlock(textBytes, 0, textBytes.Length);
icrypt.Dispose();
return Convert.ToString(ence);
}
if (Form1.verify == password)
{
return System.Text.ASCIIEncoding.ASCII.GetString(ence);
}
else if (Form1.verify != password)
{
MessageBox.Show("Use originas key file");
}
return encrypted;
}
I'm going to encrypt my data transferring between my multi platform apps. My question is that which algorithm can be used that work for all these platforms?
That should have these parameters:
Dynamic key and iv.
Supported in C#, Android, Swift, PHP.
Be secure enough.
It will be welcome if anybody give me some samples or links for each platform.
UPDATE:
I tried these classes:
Android:
public class Cryptor {
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
public Cryptor(byte[] key_par,byte[] iv_par)
{
keyspec = new SecretKeySpec(key_par, "AES");
ivspec = new IvParameterSpec(iv_par);
try {
cipher = Cipher.getInstance("AES/CBC/ZeroPadding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public byte[] encrypt(byte[] input) throws Exception
{
if(text == null || text.length() == 0)
throw new Exception("Empty input");
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(input);
} catch (Exception e)
{
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}
public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(code));
} catch (Exception e)
{
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
public static String bytesToHex(byte[] data)
{
if (data==null)
{
return null;
}
int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16)
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
else
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
return str;
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
}
PHP:
class MCrypt
{
protected $in_iv;
protected $in_key;
function __construct($in_key , $in_iv)
{
$this->key = $in_key;
$this->iv = $in_iv;
}
function encrypt($str) {
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return bin2hex($encrypted);
}
function decrypt($code) {
$code = $this->hex2bin($code);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $code);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return utf8_encode(trim($decrypted));
}
protected function hex2bin($hexdata) {
$bindata = '';
for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
}
C#:
class Cryptor
{
private byte[] iv;
private byte[] key;
public Cypher(byte[] key, byte[] iv)
{
this.key = key;
this.iv = iv;
}
public byte[] EncryptRJ128(byte[] input)
{
var encoding = new UTF8Encoding();
byte[] encrypted;
using (var rj = new RijndaelManaged())
{
try
{
rj.Padding = PaddingMode.Zeros;
rj.Mode = CipherMode.CBC;
rj.KeySize = 128;
rj.BlockSize = 128;
rj.Key = key;
rj.IV = iv;
var ms = new MemoryStream();
var cs = new CryptoStream(ms, rj.CreateEncryptor(key, iv), CryptoStreamMode.Write);
var sr = new StreamWriter(cs);
sr.Write(input);
sr.Flush();
cs.FlushFinalBlock();
encrypted = ms.ToArray();
}
finally
{
rj.Clear();
}
}
return encrypted;
}
public String DecryptRJ128(byte[] input)
{
var sRet = "";
var encoding = new UTF8Encoding();
using (var rj = new RijndaelManaged())
{
try
{
rj.Padding = PaddingMode.Zeros;
rj.Mode = CipherMode.CBC;
rj.KeySize = 128;
rj.BlockSize = 128;
rj.Key = key;
rj.IV = iv;
var ms = new MemoryStream(input);
var cs = new CryptoStream(ms, rj.CreateDecryptor(key, iv), CryptoStreamMode.Read);
var sr = new StreamReader(cs);
sRet = sr.ReadLine();
}
finally
{
rj.Clear();
}
}
return sRet;
}
}
TEST:
This is some example that I used to test:
key ={ 106,104,103,97,103,94,115,106,102,96,115,53,53,52,55,53}
iv ={104,49,52,56,114,102,103,49,48,50,52,97,56,51,118,52}
input ={57,102,117,105,65,75,113,105,108,119,113,54,109,73,89,104}
Now trying to encrypt:
Android and PHP output:
170, 29, 170, 139, 14, 192, 81, 232, 41, 237, 25, 19, 130, 237, 15, 198
c# OUTPUT:
59 , 85 , 127 , 29 , 161 , 145 , 23 , 127 , 246 , 100 , 157 , 234 , 128 , 65
I have following code that works fine when I use a four letter word as input, E.g. “Test”. When the input is not a multiple of 4, it fails E.g. “MyTest”.
Eexception: Invalid length for a Base-64 char array.
QUESTIONS
Is it guaranteed that the encrypted result will be always compatible to a Unicode string (without any loss). If yes I can use UTF encoding instead of Base64? What's the difference between UTF8/UTF16 and Base64 in terms of encoding
How can add padding so that we get correct result (after decryption) even if the input is not a multiple of 4?
MAIN PRGORAM
class Program
{
static void Main(string[] args)
{
string valid128BitString = "AAECAwQFBgcICQoLDA0ODw==";
string inputValue = "MyTest";
string keyValue = valid128BitString;
byte[] byteValForString = Convert.FromBase64String(inputValue);
EncryptResult result = Aes128Utility.EncryptData(byteValForString, keyValue);
EncryptResult encyptedValue = new EncryptResult();
string resultingIV = "4uy34C9sqOC9rbV4GD8jrA==";
if (String.Equals(resultingIV,result.IV))
{
int x = 0;
}
encyptedValue.IV = resultingIV;
encyptedValue.EncryptedMsg = result.EncryptedMsg;
string finalResult = Convert.ToBase64String(Aes128Utility.DecryptData(encyptedValue, keyValue));
Console.WriteLine(finalResult);
if (String.Equals(inputValue, finalResult))
{
Console.WriteLine("Match");
}
else
{
Console.WriteLine("Differ");
}
Console.ReadLine();
}
}
AES Crypto UTILITY
public static class Aes128Utility
{
private static byte[] key;
public static EncryptResult EncryptData(byte[] rawData, string strKey)
{
EncryptResult result = null;
if (key == null)
{
if (!String.IsNullOrEmpty(strKey))
{
key = Convert.FromBase64String((strKey));
result = Encrypt(rawData);
}
}
else
{
result = Encrypt(rawData);
}
return result;
}
public static byte[] DecryptData(EncryptResult encryptResult, string strKey)
{
byte[] origData = null;
if (key == null)
{
if (!String.IsNullOrEmpty(strKey))
{
key = Convert.FromBase64String(strKey);
origData = Decrypt(Convert.FromBase64String(encryptResult.EncryptedMsg), Convert.FromBase64String(encryptResult.IV));
}
}
else
{
origData = Decrypt(Convert.FromBase64String(encryptResult.EncryptedMsg), Convert.FromBase64String(encryptResult.IV));
}
return origData;
}
private static EncryptResult Encrypt(byte[] rawData)
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
aesProvider.Key = key;
aesProvider.Mode = CipherMode.CBC;
aesProvider.Padding = PaddingMode.PKCS7;
aesProvider.IV = Convert.FromBase64String("4uy34C9sqOC9rbV4GD8jrA==");
using (MemoryStream memStream = new MemoryStream())
{
CryptoStream encStream = new CryptoStream(memStream, aesProvider.CreateEncryptor(), CryptoStreamMode.Write);
encStream.Write(rawData, 0, rawData.Length);
encStream.FlushFinalBlock();
EncryptResult encResult = new EncryptResult();
encResult.EncryptedMsg = Convert.ToBase64String(memStream.ToArray());
encResult.IV = Convert.ToBase64String(aesProvider.IV);
return encResult;
}
}
}
private static byte[] Decrypt(byte[] encryptedMsg, byte[] iv)
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
aesProvider.Key = key;
aesProvider.IV = 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(encryptedMsg, 0, encryptedMsg.Length);
decStream.FlushFinalBlock();
return memStream.ToArray();
}
}
}
}
DTO
public class EncryptResult
{
public string EncryptedMsg { get; set; }
public string IV { get; set; }
}
REFERENCES:
How to create byte[] with length 16 using FromBase64String
Getting incorrect decryption value using AesCryptoServiceProvider
If you are encrypting, then encoding Base64 for me doesn't add anything useful, instead it brings the problems you face.
As for the padding, a solution i have seen is to create a new byte[] that is indeed a multiple of 4 and copy the source byte[] to that new byte[].
So, something like this:
if (rawdata.Length % 16 !=0)
{
newSource = new byte[source.Length + 16 - source.Length % 16];
Array.Copy(source, newSource, source.Length);
}
Base64 is a way of representing binary values as text so that you do not conflict with common control codes like \x0A for newline or \0 for a string terminator. It is NOT for turning typed text in to binary.
Here is how you should be passing the text in and getting it back out. You can replace UTF8 with whatever encoding you want, but you will need to make sure the Encoding.Whatever.GetBytes is the same encoding as the Encoding.Whatever.GetString
class Program
{
static void Main(string[] args)
{
string valid128BitString = "AAECAwQFBgcICQoLDA0ODw==";
string inputValue = "MyTest";
string keyValue = valid128BitString;
//Turns our text in to binary data
byte[] byteValForString = Encoding.UTF8.GetBytes(inputValue);
EncryptResult result = Aes128Utility.EncryptData(byteValForString, keyValue);
EncryptResult encyptedValue = new EncryptResult();
//(Snip)
encyptedValue.IV = resultingIV;
encyptedValue.EncryptedMsg = result.EncryptedMsg;
string finalResult = Encoding.UTF8.GetString(Aes128Utility.DecryptData(encyptedValue, keyValue));
Console.WriteLine(finalResult);
if (String.Equals(inputValue, finalResult))
{
Console.WriteLine("Match");
}
else
{
Console.WriteLine("Differ");
}
Console.ReadLine();
}
}
Hello I am trying to encrypt / decrypt a string via Rijaendal.
I simply can't figure out why the decryption blows up. I always end up with an incorrect padding error. One thing that throws me off is the result of my encryption which I return as HEX array. It has a length of 14 bytes. In my decryption function, the same byte array ends up having 16 bytes upon conversion from HEX.
Any help would be appreciated:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace rjandal
{
class Program
{
static void Main(string[] args)
{
string DataForEncrypting = "this is a test";
string key = string.Empty;
string iv = string.Empty;
using (System.Security.Cryptography.RijndaelManaged rmt = new System.Security.Cryptography.RijndaelManaged())
{
rmt.KeySize = 256;
rmt.BlockSize = 128;
rmt.Mode = System.Security.Cryptography.CipherMode.CBC;
rmt.Padding = System.Security.Cryptography.PaddingMode.ISO10126;
rmt.GenerateKey();
rmt.GenerateIV();
key = Convert.ToBase64String(rmt.Key);
iv = Convert.ToBase64String(rmt.IV);
}
string encryptedData = _encrypt(DataForEncrypting, key, iv);
string unencryptedData = _decrypt(key, iv, HexString2Ascii(encryptedData));
Console.WriteLine(unencryptedData);
Console.WriteLine(encryptedData);
Console.ReadKey();
}
private static string _encrypt(string value, string key, string initVector)
{
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(value);
byte[] encBuffer;
using (System.Security.Cryptography.RijndaelManaged rmt = new System.Security.Cryptography.RijndaelManaged())
{
rmt.KeySize = 256;
rmt.BlockSize = 128;
rmt.Mode = System.Security.Cryptography.CipherMode.CBC;
rmt.Padding = System.Security.Cryptography.PaddingMode.ISO10126;
encBuffer = rmt.CreateEncryptor(Convert.FromBase64String(key),
Convert.FromBase64String(initVector)).TransformFinalBlock(buffer, 0, buffer.Length);
}
string encryptValue = ConvertToHex(ASCIIEncoding.ASCII.GetString(encBuffer));
return encryptValue;
}
private static string _decrypt(string key, string initVector, string value)
{
byte[] hexBuffer = ASCIIEncoding.ASCII.GetBytes(value);
byte[] decBuffer;
using (System.Security.Cryptography.RijndaelManaged rmt = new System.Security.Cryptography.RijndaelManaged())
{
rmt.KeySize = 256;
rmt.BlockSize = 128;
rmt.Mode = System.Security.Cryptography.CipherMode.CBC;
rmt.Padding = System.Security.Cryptography.PaddingMode.ISO10126;
decBuffer = rmt.CreateDecryptor(Convert.FromBase64String(key),
Convert.FromBase64String(initVector)).TransformFinalBlock(hexBuffer, 0, hexBuffer.Length);
}
return System.Text.ASCIIEncoding.ASCII.GetString(decBuffer);
}
private static string ConvertToHex(string asciiString)
{
string hex = "";
foreach (char c in asciiString)
{
int tmp = c;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
return hex;
}
private static string HexString2Ascii(string hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= hexString.Length - 2; i += 2)
{
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
return sb.ToString();
}
}
}
You're doing way too much conversion between text and data, basically. Look at this, for example:
string encryptValue = ConvertToHex(ASCIIEncoding.ASCII.GetString(encBuffer));
Once you've got an ASCII string, why would you need to convert that into hex? It's already text! But by then you'll already have lost the data. Unless you really need it in hex (in which case follow Adam's suggestion and change your HexToAscii method to take a byte[] instead of a string) you should just use Convert.ToBase64String:
string encryptValue = Convert.ToBase64String(encBuffer);
Use Convert.FromBase64String at the other end when decrypting. You can then get rid of your hex methods completely.
Oh, and in general I wouldn't use Encoding.ASCII to start with... I'd almost always use Encoding.UTF8 instead. Currently you'll fail to encrypt (correctly) any strings containing non-ASCII characters such as accents.
Here's a rejigged version of your test program, with a few of those changes made. Note that the names "cipher text" and "plain text" are in terms of encryption... they're still binary data rather than text!
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string DataForEncrypting = "this is a test";
string key = string.Empty;
string iv = string.Empty;
using (RijndaelManaged rmt = new RijndaelManaged())
{
rmt.KeySize = 256;
rmt.BlockSize = 128;
rmt.Mode = CipherMode.CBC;
rmt.Padding = PaddingMode.ISO10126;
rmt.GenerateKey();
rmt.GenerateIV();
key = Convert.ToBase64String(rmt.Key);
iv = Convert.ToBase64String(rmt.IV);
}
string encryptedData = _encrypt(DataForEncrypting, key, iv);
string unencryptedData = _decrypt(key, iv, encryptedData);
Console.WriteLine(unencryptedData);
Console.WriteLine(encryptedData);
Console.ReadKey();
}
private static string _encrypt(string value, string key, string initVector)
{
using (RijndaelManaged rmt = new RijndaelManaged())
{
rmt.KeySize = 256;
rmt.BlockSize = 128;
rmt.Mode = CipherMode.CBC;
rmt.Padding = PaddingMode.ISO10126;
byte[] plainText = Encoding.UTF8.GetBytes(value);
byte[] cipherText = rmt.CreateEncryptor(Convert.FromBase64String(key),
Convert.FromBase64String(initVector))
.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherText);
}
}
private static string _decrypt(string key, string initVector, string value)
{
using (RijndaelManaged rmt = new RijndaelManaged())
{
rmt.KeySize = 256;
rmt.BlockSize = 128;
rmt.Mode = CipherMode.CBC;
rmt.Padding = PaddingMode.ISO10126;
byte[] cipherText = Convert.FromBase64String(value);
byte[] plainText = rmt.CreateDecryptor(Convert.FromBase64String(key),
Convert.FromBase64String(initVector))
.TransformFinalBlock(cipherText, 0, cipherText.Length);
return Encoding.UTF8.GetString(plainText);
}
}
}
You shouldn't be using ASCII character encoding as an intermediate step; you should change your functions that go from hex to ASCII (and back again) to go from a byte[] to hex (and back again) instead.
private static string ConvertToHex(byte[] data)
{
string hex = "";
foreach (byte b in data)
{
hex += b.ToString("X2");
}
return hex;
}
private static byte[] HexString2ByteArray(string hexString)
{
byte[] output = new byte[hexString.Length / 2];
for (int i = 0; i <= hexString.Length - 2; i += 2)
{
output[i/2] = Convert.ToByte(hexString.Substring(i, 2), 16);
}
return output;
}
As a side note, is there a reason that you're looking for a hex representation of the array versus something more compact like Base64? You're using Base64 in your example to transfer the key and IV, so I'm just curious about what makes you want to return the encrypted data as hex here.
In any case, here's something that should work for you:
private static string _encrypt(string value, string key, string initVector)
{
byte[] buffer = Encoding.Unicode.GetBytes(value);
byte[] encBuffer;
using (System.Security.Cryptography.RijndaelManaged rmt = new System.Security.Cryptography.RijndaelManaged())
{
rmt.KeySize = 256;
rmt.BlockSize = 128;
rmt.Mode = System.Security.Cryptography.CipherMode.CBC;
rmt.Padding = System.Security.Cryptography.PaddingMode.ISO10126;
encBuffer = rmt.CreateEncryptor(Convert.FromBase64String(key),
Convert.FromBase64String(initVector)).TransformFinalBlock(buffer, 0, buffer.Length);
}
string encryptValue = ConvertToHex(encBuffer);
return encryptValue;
}
private static string _decrypt(string key, string initVector, string value)
{
byte[] hexBuffer = HexString2ByteArray(value);
byte[] decBuffer;
using (System.Security.Cryptography.RijndaelManaged rmt = new System.Security.Cryptography.RijndaelManaged())
{
rmt.KeySize = 256;
rmt.BlockSize = 128;
rmt.Mode = System.Security.Cryptography.CipherMode.CBC;
rmt.Padding = System.Security.Cryptography.PaddingMode.ISO10126;
decBuffer = rmt.CreateDecryptor(Convert.FromBase64String(key),
Convert.FromBase64String(initVector)).TransformFinalBlock(hexBuffer, 0, hexBuffer.Length);
}
return Encoding.Unicode.GetString(decBuffer);
}
You may avoid the issues with Decypting/Encrypting and usign System.Text.Encoding and avoid using Base64 encoding work around, by adding a few methods that completely bypass microsoft's mismatched conversions in the System.Text.Encoding, by allowing you to encrypt the real bytes in memory without any translations.
Since using these I have avoided padding errors caused by System.Text.Encoding methods, without using the Base64 conversions either.
private static Byte[] GetBytes(String SomeString)
{
Char[] SomeChars = SomeString.ToCharArray();
Int32 Size = SomeChars.Length * 2;
List<Byte> TempList = new List<Byte>(Size);
foreach (Char Character in SomeChars)
{
TempList.AddRange(BitConverter.GetBytes(Character));
}
return TempList.ToArray();
}
private static String GetString(Byte[] ByteArray)
{
Int32 Size = ByteArray.Length / 2;
List<Char> TempList = new List<Char>(Size);
for (Int32 i = 0; i < ByteArray.Length; i += 2)
{
TempList.Add(BitConverter.ToChar(ByteArray, i));
}
return new String(TempList.ToArray());
}
And how they are used with encryption
private static String Encrypt(String Test1, Byte[] Key, Byte[] IV)
{
Byte[] Encrypted;
using (AesCryptoServiceProvider AesMan = new AesCryptoServiceProvider())
{
AesMan.Mode = CipherMode.CBC;
AesMan.Padding = PaddingMode.ISO10126;
ICryptoTransform EncThis = AesMan.CreateEncryptor(Key, IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, EncThis, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(Test1);
}
Encrypted = msEncrypt.ToArray();
}
}
};
return GetString(Encrypted);
}
private static String Decrypt(String Data, Byte[] Key, Byte[] IV)
{
String Decrypted;
using (AesCryptoServiceProvider AesMan = new AesCryptoServiceProvider())
{
AesMan.Mode = CipherMode.CBC;
AesMan.Padding = PaddingMode.ISO10126;
ICryptoTransform EncThis = AesMan.CreateDecryptor(Key, IV);
using (MemoryStream msDecrypt = new MemoryStream(GetBytes(Data)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, EncThis, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
Decrypted = srDecrypt.ReadToEnd();
}
}
}
}
return Decrypted;
}