This question already has an answer here:
Decrypt/Decrypt Arabic string
(1 answer)
Closed 7 years ago.
How to Encrypt/Decrypt Arabic string in C# using these methods ????
Wheni try to decrypt any arabic string its return "????" question marks.. How can use Encoding UTF8 through this code ??
Any help please ..
thanks in advance
public static string Encrypt(string pDataToEncrypt)
{
ASCIIEncoding textConverter = new ASCIIEncoding();
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] toEncrypt;
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
toEncrypt = textConverter.GetBytes(pDataToEncrypt);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
return Convert.ToBase64String(msEncrypt.GetBuffer(), 0, (int)msEncrypt.Length);
}
public static string Decrypt(string pDataToDecrypt)
{
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] fromEncrypt;
//Encoding asciiEncoding = Encoding.ASCII;
fromEncrypt = Convert.FromBase64String(pDataToDecrypt);
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);
MemoryStream msDecrypt = new MemoryStream(fromEncrypt, 0, fromEncrypt.Length);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(csDecrypt);
return sr.ReadToEnd();
}
Using UTF-8 your code should be like this:
public static string Encrypt(string pDataToEncrypt)
{
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor,CryptoStreamMode.Write);
byte[] toEncrypt = Encoding.UTF8.GetBytes(pDataToEncrypt);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
return Convert.ToBase64String(msEncrypt.GetBuffer(), 0, (int)msEncrypt.Length);
}
public static string Decrypt(string pDataToDecrypt)
{
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] fromEncrypt = Convert.FromBase64String(pDataToDecrypt);
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);
MemoryStream msDecrypt = new MemoryStream(fromEncrypt, 0, fromEncrypt.Length);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[fromEncrypt.Length];
int decryptedByteCount = csDecrypt.Read(plainTextBytes, 0, plainTextBytes.Length);
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
Related
In ms SQL server, I have a field text with data look like below:
"!"$$$$$$!#$$$$!!!!! !!!!!!!!!!!!!! "!! ! " !" ! !" !!!! ! !!"!".
I belive that from a plain text string, they using a Rijndael algorithm to encrypted this string. from encrypted string, it was transform to string above.
Can anyone recognize what the algorithm to decrypt from string above to the encrypted string of Rijndael algorithm?
thanks
Hi me drona please find the below code. It will useful from you.
public static class Encrypt
{
// This size of the IV (in bytes) must = (keysize / 8). Default keysize is 256, so the IV must be
// 32 bytes long. Using a 16 character string here gives us 32 bytes when converted to a byte array.
private const string initVector = "pemgail9uzpgzl88";
// This constant is used to determine the keysize of the encryption algorithm
private const int keysize = 256;
//Encrypt
public static string EncryptString(string plainText, string passPhrase)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
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();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
//Decrypt
public static string DecryptString(string cipherText, string passPhrase)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
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);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
enter code here
How to encrypt/decrypt arabic text in C#
public static string Encrypt(string pDataToEncrypt)
{
ASCIIEncoding textConverter = new ASCIIEncoding();
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] toEncrypt;
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
toEncrypt = textConverter.GetBytes(pDataToEncrypt);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
return Convert.ToBase64String(msEncrypt.GetBuffer(), 0, (int)msEncrypt.Length);
}
public static string Decrypt(string pDataToDecrypt)
{
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] fromEncrypt;
//Encoding asciiEncoding = Encoding.ASCII;
fromEncrypt = Convert.FromBase64String(pDataToDecrypt);
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);
MemoryStream msDecrypt = new MemoryStream(fromEncrypt, 0, fromEncrypt.Length);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(csDecrypt);
return sr.ReadToEnd();
}
when i try to encrypt its return "????" question marks
thanks in advance
Use
UnicodeEncoding()
instead of
ASCIIEncoding()
At the moment, I'm working on a project that involves encryption. Therefore, I have a class, which worked fine in .NET 4.0, but now that I changed it so it would work in .NET 2.0, it fails to encrypt almost any string... I don't know why, but it fails every time and throws a CryptographicException. Decrypting works fine as far as I can tell, and everything else too.
Anyway, here's the code:
public class Encryption
{
static readonly string PasswordHash = "P##Sw0rd";
static readonly string SaltKey = "S#LT&KEY";
static readonly string VIKey = "#1B2c3D4e5F6g7H8";
public static string Encrypt(string plainText, string passwordHash)
{
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
byte[] keyBytes = new Rfc2898DeriveBytes(passwordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.None;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
byte[] cipherTextBytes;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
cryptoStream.Close();
}
memoryStream.Close();
}
return Convert.ToBase64String(cipherTextBytes);
}
public static string Decrypt(string encryptedText, string passwordHash)
{
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
byte[] keyBytes = new Rfc2898DeriveBytes(passwordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.None;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
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);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
}
}
The error message is (translated from German):
CryptographicException: Length of the data to encrypt is invalid. at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)
Encryption.Encrypt("Client connected!", "elit3Nase") does not work
"Client connected!" is not long enough to fully fill a block (16 bytes) and you are not using padding:
symmetricKey.Padding = PaddingMode.None;
Change to symmetricKey.Padding = PaddingMode.PKCS7; to ensure padding is applied.
I have error from CryptoStream:
Padding is invalid and cannot be removed.
Code
public MemoryStream EncrypteBytes(Stream inputStream, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Padding = PaddingMode.PKCS7;
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
var buffer = new byte[1024];
var read = inputStream.Read(buffer, 0, buffer.Length);
while (read > 0)
{
cryptoStream.Write(buffer, 0, read);
read = inputStream.Read(buffer, 0, buffer.Length);
}
cryptoStream.FlushFinalBlock();
memoryStream.Position = 0;
return memoryStream;
}
// Example usage: DecryptBytes(encryptedBytes, "SensitivePhrase", "SodiumChloride");
public byte[] DecrypteBytes(MemoryStream memoryStream, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Padding = PaddingMode.PKCS7;
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] plainBytes = new byte[memoryStream.Length];
int DecryptedCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
return plainBytes;
}
Use PaddingMode.Zeros to fix problem , Following code:
public byte[] EncryptFile(Stream input, string password, string salt)
{
// Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
// 1.The block size is set to 128 bits
// 2.You are not using CFB mode, or if you are the feedback size is also 128 bits
var algorithm = new RijndaelManaged { KeySize = 256, BlockSize = 128 };
var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(salt));
algorithm.Key = key.GetBytes(algorithm.KeySize / 8);
algorithm.IV = key.GetBytes(algorithm.BlockSize / 8);
algorithm.Padding = PaddingMode.Zeros;
using (Stream cryptoStream = new MemoryStream())
using (var encryptedStream = new CryptoStream(cryptoStream, algorithm.CreateEncryptor(), CryptoStreamMode.Write))
{
CopyStream(input, encryptedStream);
return ReadToEnd(cryptoStream);
}
}
public byte[] DecryptFile(Stream input, Stream output, string password, string salt)
{
// Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
// 1.The block size is set to 128 bits
// 2.You are not using CFB mode, or if you are the feedback size is also 128 bits
var algorithm = new RijndaelManaged { KeySize = 256, BlockSize = 128 };
var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(salt));
algorithm.Key = key.GetBytes(algorithm.KeySize / 8);
algorithm.IV = key.GetBytes(algorithm.BlockSize / 8);
algorithm.Padding = PaddingMode.Zeros;
try
{
using (var decryptedStream = new CryptoStream(output, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
{
CopyStream(input, decryptedStream);
return ReadToEnd(output);
}
}
catch (CryptographicException ex)
{
throw new InvalidDataException("Please supply a correct password");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I hop help you.
Please check your pass phrase - it should be same in both methods EncrypteBytes and DecrypteBytes. If both are not same, then it will generate the error.
My problem was I was taking the encryped output in bytes and converting it to a string. The string back to byte array (for decrypting) was not the same. I was using UTF8Encoding, then I tried ASCIIEnconding. Neither worked.
Convert.FromBase64String/ToBase64String worked fine, got rid of the padding issues and actually decrypted the data.
It's work
using (FileStream fs = new FileStream( absolute, FileMode.Open )) {
// create a CryptoStream in read mode
using (CryptoStream cryptoStream = new CryptoStream( fs, decryptor, CryptoStreamMode.Read )) {
int readLength = ( int )fs.Length;
byte[] buffer = new byte[readLength];
cryptoStream.Read( buffer, 0, readLength );
using (MemoryStream ms = new MemoryStream( buffer )) {
BinaryFormatter bf = new BinaryFormatter( );
settings = ( SettingsJson )bf.Deserialize( ms );// Deserialize SettingsJson array
}
}
fs.Close( );
}
Only part of the string is getting decrypted, i think it has to do with my encoding.
Here is what happens:
string s = "The brown fox jumped over the green frog";
string k = "urieurut";
string enc = EncryptString(s, k);
string dec = DecryptString(enc, k);
The RESULT is this: The brown fox juϼ㴘裴혽Ή⪻ㆉr th≸ g⟤een frog
public static string EncryptString(string stringToEncrypt, string encryptionKey)
{
string encrypted = String.Empty;
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(encryptionKey);
RijndaelManaged RMCrypto = new RijndaelManaged();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
byte[] encryptedString = UE.GetBytes(stringToEncrypt);
cs.Write(encryptedString, 0, encryptedString.Length);
cs.FlushFinalBlock();
cs.Close();
encrypted = UE.GetString(ms.ToArray());
return encrypted;
}
public static string DecryptString(string stringToDecrypt, string encryptionKey)
{
string decrypted = String.Empty;
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(encryptionKey);
byte[] data = UE.GetBytes(stringToDecrypt);
RijndaelManaged RMCrypto = new RijndaelManaged();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
cs.Close();
decrypted = UE.GetString(ms.ToArray());
return decrypted;
}
Here you go:
string s = "The brown fox jumped over the green frog";
string k = "urieurut";
byte[] enc = EncryptString(s, k);
string dec = DecryptString(enc, k);
You can't attempt to interpret an encrypted bunch of bytes as a Unicode string. Keep them as bytes. The decrypted version can be converted back to string.
Also note the disposing of disposable objects below. You could wind up with some resources being held too long or leak if you don't release them properly with using() or Dispose().
public static byte[] EncryptString(string stringToEncrypt, string encryptionKey)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(encryptionKey);
using (RijndaelManaged RMCrypto = new RijndaelManaged())
using (MemoryStream ms = new MemoryStream())
using (ICryptoTransform encryptor = RMCrypto.CreateEncryptor(key, key))
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
byte[] encryptedString = UE.GetBytes(stringToEncrypt);
cs.Write(encryptedString, 0, encryptedString.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
public static string DecryptString(byte[] stringToDecrypt, string encryptionKey)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(encryptionKey);
using (RijndaelManaged RMCrypto = new RijndaelManaged())
using (MemoryStream ms = new MemoryStream())
using (ICryptoTransform decryptor = RMCrypto.CreateDecryptor(key, key))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
cs.Write(stringToDecrypt, 0, stringToDecrypt.Length);
cs.FlushFinalBlock();
return UE.GetString(ms.ToArray());
}
}
I solved my issue by using base64 string for the encryption - i may look at other options but i only needed these methods for a small amount of data, here is the final code:
public static string EncryptString(string stringToEncrypt, string encryptionKey)
{
string encrypted = String.Empty;
byte[] key = Encoding.Unicode.GetBytes(encryptionKey);
RijndaelManaged RMCrypto = new RijndaelManaged();
RMCrypto.Padding = PaddingMode.PKCS7;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
byte[] encryptedString = Encoding.ASCII.GetBytes(stringToEncrypt);
cs.Write(encryptedString, 0, encryptedString.Length);
cs.FlushFinalBlock();
cs.Close();
//encrypted = Encoding.ASCII.GetString(ms.ToArray());
return Convert.ToBase64String(ms.ToArray());
}
public static string DecryptString(string stringToDecrypt, string encryptionKey)
{
string decrypted = String.Empty;
byte[] key = Encoding.Unicode.GetBytes(encryptionKey);
byte[] data = Convert.FromBase64String(stringToDecrypt);
RijndaelManaged RMCrypto = new RijndaelManaged();
RMCrypto.Padding = PaddingMode.PKCS7;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
cs.Close();
decrypted = Encoding.ASCII.GetString(ms.ToArray());
return decrypted;
}
Not sure about your specific code chunk, but Jeff Atwood did a nice little library that I've used before:
http://www.codeproject.com/KB/security/SimpleEncryption.aspx
It's worth a look as it simplifies the process of encrypting things a lot, I actually had to port to C# as there wasn't a port available when I saw it. However there is now a C# port (in the comments section).