I have a MySQL database which is configured to receive a data with polish characters (f. ex ą, ę, ó, ł, ń etc.).
Now I want to send data with these Polish characters to a db using AES_ENCRYPT(), and then get them from there using AES_DECRYPT().
My problem is that I receive a byte[] array in C# which has X elements where X is length of text I receive. And every single array element has an ASCII code of an character it represents. I could easily convert it to text using Encoding Class, but I won't get Polish characters in output text.
F. ex.:
I send AES_ENCRYPT('ąąą', '123') to db.
I get AES_DECRYPT('sql command','123') and I get byte[] which has 3 elements, everyone with '97' value which represents 'aaa' - NOT 'ąąą'.
How to use AES_DECRYPT/ENCRYPT in a way which allows me to send/get polish characters to my DB?!
Or how to get string output from aes_decrypt() instead byte[]?
convert using encoding might help you.
select convert(aes_decrypt(aes_encrypt('ąąą', 'abcdefg'), 'abcdefg') using UTF8);
Why don't you just implement encryption/decryption in code instead of in queries?
private static Byte[] Encrypt(String toEncrypt, Byte[] Key, Byte[] IV)
{
CryptoStream streamCrypto = null;
MemoryStream streamMemory = null;
RijndaelManaged aes = null;
StreamWriter streamWriter = null;
try
{
aes = new RijndaelManaged();
aes.Key = Key;
aes.IV = IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
streamMemory = new MemoryStream();
streamCrypto = new CryptoStream(streamMemory, encryptor, CryptoStreamMode.Write);
streamWriter = new StreamWriter(streamCrypto);
streamWriter.Write(toEncrypt);
}
finally
{
if (streamWriter != null)
streamWriter.Close();
if (streamCrypto != null)
streamCrypto.Close();
if (streamMemory != null)
streamMemory.Close();
if (aes != null)
aes.Clear();
}
return streamMemory.ToArray();
}
public static String Decrypt(Byte[] toDecrypt, Byte[] Key, Byte[] IV)
{
CryptoStream streamCrypto = null;
MemoryStream streamMemory = null;
RijndaelManaged aes = null;
StreamReader streamReader = null;
String output = null;
try
{
aes = new RijndaelManaged();
aes.Key = Key;
aes.IV = IV;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
streamMemory = new MemoryStream(toDecrypt);
streamCrypto = new CryptoStream(streamMemory, decryptor, CryptoStreamMode.Read);
streamReader = new StreamReader(streamCrypto);
output = streamReader.ReadToEnd();
}
finally
{
if (streamReader != null)
streamReader.Close();
if (streamCrypto != null)
streamCrypto.Close();
if (streamMemory != null)
streamMemory.Close();
if (aes != null)
aes.Clear();
}
return output;
}
In your code, you encrypt your string and then you send encrypted data to the database:
Byte[] encrypted = Encrypt(yourString, Key, IV);
When you pull out data from the database, you just get back your string using:
String decrypted = Decrypt(dbData, Key, IV);
If you don't like this way, just use your queries like so:
INSERT INTO mysecrets (mysecret1, mysecret2) VALUES (AES_ENCRYPT(secret1, YOUR_ENCRYPTION_KEY), AES_ENCRYPT(secret2, YOUR_ENCRYPTION_KEY))
SELECT AES_DECRYPT(mysecret1, YOUR_ENCRYPTION_KEY) AS secret1, AES_DECRYPT(mysecret1, YOUR_ENCRYPTION_KEY) AS secret2 FROM mysecrets
Your MySQL data is in characters, while encryption works on bytes. You need to convert your characters to bytes before encrypting them, and also convert the decrypted bytes back to characters. That means you need to explicitly specify the character encoding to be used at both ends so they match. The current standard is UTF-8, so you should specify that at each end. If UTF-8 does not work, then try some Microsoft specific character encoding at both ends.
Related
I have a problem when performing a decryption in TRIPLEDES that a provider sends me in HEX: EF69FF79BBD7E8E4EF69FF79BBD7E8E4 with the following key "0123456789ABCDEFFEDCBA9876543210", applying the following method:
public IActionResult GetTokenTemp1()
{
TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
tDESalg.Key = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes("0123456789ABCDEFFEDCBA9876543210"));
byte[] cipherBytes = Convert.FromBase64String("EF69FF79BBD7E8E4EF69FF79BBD7E8E4");
string finalDecrypt = _3desTest.DecryptTextFromMemory(cipherBytes, tDESalg.Key, tDESalg.IV);
return Ok(finalDecrypt);
}
public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream(Data);
TripleDESCryptoServiceProvider de = new TripleDESCryptoServiceProvider();
var descritor = de.CreateDecryptor(Key, IV);
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream(msDecrypt,
descritor,
CryptoStreamMode.Read);
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[Data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
string es = new UTF8Encoding().GetString(fromEncrypt);
//Convert the buffer into a string and return it.
return new UTF8Encoding().GetString(fromEncrypt);
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
When I leave the default padding or any other to zero or none, I get the following error "adding is invalid and cannot be removed.",
but when I leave the padding at zero or none tripleDescryptorService.Padding = PaddingMode.None I get a format:
padding.none
I don't know what to do very well, when I do it on this page:
https://neapay.com/online-tools/des-calculator.html?data=EF69FF79BBD7E8E4EF69FF79BBD7E8E4&key=0123456789ABCDEFFEDCBA9876543210&algo=3DES&decr=true
I get the desired result.
I'm already desperate, I'm not very expert in encryption.
Thank you so much
The website uses neither a padding nor an IV. Therefore in the code the padding must be disabled and the ECB mode must be applied.
Furthermore the website expects a hex encoded key and ciphertext and returns the decrypted data also hex encoded, which therefore must not be UTF-8 decoded in the code:
public static byte[] DecryptTextFromMemory(byte[] encryptedData, byte[] key)
{
using (TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider())
{
tripleDES.Key = key;
tripleDES.Padding = PaddingMode.None;
tripleDES.Mode = CipherMode.ECB;
byte[] decryptedData = new byte[encryptedData.Length];
using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
{
ICryptoTransform decryptor = tripleDES.CreateDecryptor(tripleDES.Key, null);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
csDecrypt.Read(decryptedData, 0, decryptedData.Length);
}
}
return decryptedData;
}
}
For the hex encoding and decoding you can use arbitrary methods, e.g. from here.
With this the code:
byte[] data = HexStringToByteArray("EF69FF79BBD7E8E4EF69FF79BBD7E8E4");
byte[] key = HexStringToByteArray("0123456789ABCDEFFEDCBA9876543210");
Console.WriteLine(ByteArrayToHexString(DecryptTextFromMemory(data, key)));
returns the result of the website:
00000000003331720000000000333172
Please note: Your last change is not useful because it applies conversions and algorithms that are not consistent with the website.
I came across to this old C# code and I was wondering if with .NET Framework 4.5 is there something more elegant and compact to do the same thing: encrypt a text avoiding '=' chars in the result.
Thanks.
EDIT: in addition where the number 40 comes from and why longer text does not need to be processed?
public static string BuildAutoLoginUrl(string username)
{
// build a plain text string as username#AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
if (username.Length < 40)
{
//cycle to avoid '=' character at the end of the encrypted string
int len = username.Length;
do
{
if (len == username.Length)
{
username += "#";
}
username += "A";
len++;
} while (len < 41);
}
return #"http://www.domain.com/Account/AutoLogin?key=" + EncryptStringAES(username, sharedKey);
}
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize/8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize/8);
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
Thanks.
The equal sign is there because that's part of it being a Base64 encoded string. It's Base64 encoded, because the encryption process results in a byte-array where not all of the items representable as readable text. I suppose you could try to encode as something other than Base64, but using Base32 or something is only going to make the resulting string far longer, and perhaps too long for the URL.
I've solved using the "Catto" user answer for this StackOverflow question: Encrypt and decrypt a string
I am facing with problem when decrypting data with usage of TripleDESCryptoServiceProvider. The problem is that decrypted value contains beside of original value some additional, strange characters at the end
Per instance if I provide "rastko" to be encrypted, I will get later with decryption something like this "rastko⥊㮶". For other values it could be different number of 'dummy' characters or in some cases I will get exact value.
Then, I saw that for all encrypted data byte array size is divisible by 8. It looks like any provided data is rounded on value that is divisible by 8. Only in case when original encoded value is divisible by 8, decryption will retrieve appropriate value.
Here are methods that I am using :
public static byte[] EncryptPassword(string password, out byte[] cryptoKey, out byte[] cryptoIV)
{
try
{
UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
byte[] unicodePassword = unicodeEncoding.GetBytes(password);
byte[] encryptedPassword;
using (TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider())
{
tripleDes.Key = GetCryptoKey();
tripleDes.Mode = CipherMode.CBC;
tripleDes.Padding = PaddingMode.PKCS7;
cryptoKey = tripleDes.Key;
cryptoIV = tripleDes.IV;
using (MemoryStream memoryStream = new MemoryStream())
{
ICryptoTransform cryptoTransform = tripleDes.CreateEncryptor();
using (
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(unicodePassword, 0, unicodePassword.Length);
////cryptoStream.FlushFinalBlock();
}
encryptedPassword = memoryStream.ToArray();
}
}
return encryptedPassword;
}
catch (Exception ex)
{
throw new Exception("Password encryption failed !", ex);
}
}
public static string DecryptPassword(byte[] encryptedPassword, byte[] cryptoKey, byte[] cryptoIV)
{
try
{
UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
string readablePassword;
using (TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider())
{
tripleDes.Key = cryptoKey;
tripleDes.IV = cryptoIV;
tripleDes.Mode = CipherMode.CBC;
tripleDes.Padding = PaddingMode.PKCS7;
// Create a new MemoryStream using the passed
// array of encrypted data.
using (MemoryStream memoryStream = new MemoryStream(encryptedPassword))
{
// Create crypto transform that defines the basic operations of cryptographic transformations.
ICryptoTransform cryptoTransform = tripleDes.CreateDecryptor();
// Create a CryptoStream using the MemoryStream and the passed key and initialization vector (IV).
using (CryptoStream decryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
decryptoStream.Write(encryptedPassword, 0, encryptedPassword.Length);
///decryptoStream.FlushFinalBlock();
}
byte[] decryptedPassword = memoryStream.ToArray();
//Convert the buffer into a string and return it.
readablePassword = unicodeEncoding.GetString(decryptedPassword, 0, decryptedPassword.Length);
}
}
return readablePassword;
}
catch (Exception ex)
{
throw new Exception("Password decryption failed !", ex);
}
}
private static byte[] GetCryptoKey()
{
UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
string plainKey = "rastkoisajev2310982josipasenera153";
byte[] encodedKey = unicodeEncoding.GetBytes(plainKey);
// Prepares 192 bit key
byte[] preparedKey = new byte[24];
Array.Copy(encodedKey, preparedKey, 24);
return preparedKey;
}
Here is sample test invocation :
private static void CryptoTest()
{
string password = "rastko";
byte[] cryptoKey;
byte[] cryptoIV;
byte[] encryptedPassword = Crypto.EncryptPassword(password, out cryptoKey, out cryptoIV);
string decryptedPAssword = Crypto.DecryptPassword(encryptedPassword, cryptoKey, cryptoIV);
}
I have not good experience with security. What I see is that IV vector is 8byte size and as I found it is related to BlockSize, that is 8times greater then IV size. TripleDESCryptoServiceProvider for IV vector is using 8byte value. I can not change this.
Could you please tell me what I have to do or did I wrote something wrongly ?
DES is a 64 bit block cypher. Any text that does not divide cleanly into 64 bit (=8 byte) blocks needs to be padded to make up a whole number of blocks. You need to set padding for encryption and decryption. If you have control of both ends then use PKCS#5 padding to encrypt and decrypt. If you only have control over the decryption end, then ask the encrypting end what padding they are using and expect that.
Note that encrypting a password is normally not the way to go. Use PBKDF2 instead. Don't confuse passwords and keys!
Try to make sure that your CryptoStreams get closed or flushed:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.flushfinalblock.aspx
If you don't then the padding/unpadding will likely not be performed, and you get trash instead.
After detail investigation I have found the solution for my problem.
I have changed a little bit decryption logic.
Instead of this part in DecryptPassword method :
// Create a CryptoStream using the MemoryStream and the passed key and initialization vector (IV).
using (CryptoStream decryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
decryptoStream.Write(encryptedPassword, 0, encryptedPassword.Length);
///decryptoStream.FlushFinalBlock();
}
byte[] decryptedPassword = memoryStream.ToArray();
//Convert the buffer into a string and return it.
readablePassword = unicodeEncoding.GetString(decryptedPassword, 0, decryptedPassword.Length);
}
I am now using the Read logic from CryptoStream and then I am just removing nullable characters. It is like this now :
// Create a CryptoStream using the MemoryStream and the passed key and initialization vector (IV).
using (CryptoStream decryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read))
{
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[encryptedPassword.Length];
decryptoStream.Read(fromEncrypt, 0, fromEncrypt.Length);
//Convert the buffer into a string and return it.
readablePassword = unicodeEncoding.GetString(fromEncrypt);
readablePassword = readablePassword.Replace("\0", string.Empty);
}
This works perfectly for me ! Thank you all for your time.
I have an app that is using query string to pass some values around pages. I found few examples on how to encrypt values in query string, but the problem is that my KEYS tell more about query string then the values which are all integers converted to string.
Is there a way to encrypt the whole query string in ASP.NET including keys and key values?
Something like:
Default.aspx?value1=40&value2=30&value3=20
to
Default.aspx?56sdf78fgh90sdf4564k34klog5646l
Thanks!
There is one issue that many of the references above overlook, and that is just prior to returning the encrypted string, URL Encode (see below right before the string is returned). I am using IIS 7.5, and it will automatically "Decode" the string for you, so the decryption "should" be OK. Both the Encrypt and Decrypt code is shown below.
public string EncryptQueryString(string inputText, string key, string salt)
{
byte[] plainText = Encoding.UTF8.GetBytes(inputText);
using (RijndaelManaged rijndaelCipher = new RijndaelManaged())
{
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(salt));
using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
string base64 = Convert.ToBase64String(memoryStream.ToArray());
// Generate a string that won't get screwed up when passed as a query string.
string urlEncoded = HttpUtility.UrlEncode(base64);
return urlEncoded;
}
}
}
}
}
public string DecryptQueryString(string inputText, string key, string salt)
{
byte[] encryptedData = Convert.FromBase64String(inputText);
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(salt));
using (RijndaelManaged rijndaelCipher = new RijndaelManaged())
{
using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
byte[] plainText = new byte[encryptedData.Length];
cryptoStream.Read(plainText, 0, plainText.Length);
string utf8 = Encoding.UTF8.GetString(plainText);
return utf8;
}
}
}
}
}
There are many examples on web.
some of them:
How can I encrypt a querystring in asp.net?
how to pass encrypted query string in asp.net
http://www.codeproject.com/Articles/33350/Encrypting-Query-Strings
http://www.keyvan.ms/how-to-encrypt-query-string-parameters-in-asp-net
http://forums.asp.net/t/989552.aspx/1
Now you say that you do like to encrypt the keys also, actually what you have to do is to encrypt them all url line, and then you just read the RawUrl what after the ? and decrypt it.
Scenario: One symmetric key, each user has his own IV, the documents are stored in a NVARCHAR(MAX) field. When I try to to decrypt the file, I get:
The input data is not a complete block.
// Create symmetric key
public static byte[] CreateKey()
{
AesCryptoServiceProvider aesCrypto = (AesCryptoServiceProvider)AesCryptoServiceProvider.Create();
byte[] key = aesCrypto.Key;
return key;
}
//Get key (stored in a database)
public static Byte[] GetAppKey()
{
return db.Encryptors.Where(x => x.EncryptorID == 1).Single().EncryptionKey.ToArray();
}
// Get application IV (stored in database)
public static Byte[] GetAppIV()
{
return db.Encryptors.Where(x => x.EncryptorID == 1).Single().IV.ToArray();
}
// Encrypt document (this will be stored in a VARBINARY(MAX) field
public static byte[] EncryptBinaryToBytes(Binary document, byte[] iv)
{
byte[] key = GetAppKey();
byte[] encrypted;
using (AesCryptoServiceProvider aesCsp = new AesCryptoServiceProvider())
{
aesCsp.Key = key;
aesCsp.IV = iv;
ICryptoTransform encryptor = aesCsp.CreateEncryptor(aesCsp.Key, aesCsp.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(document);
}
encrypted = msEncrypt.ToArray();
}
}
}
// return the encrypted document
return encrypted;
}
// Decrypt document
public static byte[] DecryptBytesToBytes(byte[] document, byte[] iv)
{
byte[] key = GetAppKey();
using (AesCryptoServiceProvider aesCsp = new AesCryptoServiceProvider())
{
aesCsp.Key = key;
aesCsp.IV = iv;
ICryptoTransform decryptor = aesCsp.CreateDecryptor(aesCsp.Key, aesCsp.IV);
using (MemoryStream msDecrypt = new MemoryStream())
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
{
using (StreamWriter swDecrypt = new StreamWriter(csDecrypt))
{
swDecrypt.Write(document);
}
byte[] decrypted = msDecrypt.ToArray();
// return the unencrypted document
return decrypted;
}
}
}
}
Thanks in advance.
To store the document
byte[] fileByte = fluUploadFile.FileBytes;
Binary document = new Binary(fileByte);
byte[] appIv = AES.GetAppIV();
byte[] encryptedDocument = AES.EncryptBinaryToBytes(document, appIv);
byte[] decryptedDocument = AES.DecryptBytesToBytes(encryptedDocument, appIv);
Document d = new Document()
{
OriginalName = originalName,
DocSize = fileSize,
BinaryDocument = encryptedDocument,
UploadedName = uploadedFileName,
MimeType = MIMEType,
DocExtension = extension
};
db.Documents.InsertOnSubmit(d);
db.SubmitChanges();
It's really important that you change the data type of the database field to VARBINARY(MAX), that way you avoid issues with character encodings and byte combinations that cannot be interpreted as legal characters.
Also, I think the problem is that you are not closing the streams before calling ToArray() method on the MemoryStream in both encrypt and decrypt routines. It's very important to call Close() in the CryptoStream so that FlushFinalBlock() is called and the encryption process writes the final block to the stream.
Try moving the call to MemoryStream.ToArray() to the outer using block, that is, outside the using block of CryptoStream, so that Dispose() is called on the CryptoStream and call MemoryStream.Close() before that.
Another problem with your code is that you are wrapping the CryptoStream with a StreamWriter, which writes the text representation of the object you pass into the Write method. You should instead write directly to the CryptoStream to avoid any byte to string conversions.