I have the following code:
public static string PerformEncryption(string text, string uniqueKey, bool encrypt = false)
{
byte[] textBytes = encrypt ? Encoding.UTF8.GetBytes(text) : Convert.FromBase64String(text);
byte[] resultArray;
var staticKey = Convert.FromBase64String(ConfigReader.SecretKey);
using (TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider())
{
tDes.Mode = CipherMode.ECB;
tDes.Padding = PaddingMode.PKCS7;
tDes.Key = GenerateTripleDesKey(uniqueKey, staticKey);
CTransform = encrypt ? tDes.CreateEncryptor() : tDes.CreateDecryptor();
resultArray = CTransform.TransformFinalBlock(textBytes, 0, textBytes.Length);
tDes.Clear();
}
if (encrypt)
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
return Encoding.UTF8.GetString(resultArray);
}
private static byte[] GenerateTripleDesKey(string uniqueKey, byte[] staticKey)
{
byte[] keyArray;
using (SHA512CryptoServiceProvider hash = new SHA512CryptoServiceProvider())
keyArray = hash.ComputeHash(Encoding.UTF8.GetBytes(string.Format("{0}{1}", uniqueKey, staticKey)));
byte[] trimmedBytes = new byte[24];
Buffer.BlockCopy(keyArray, 0, trimmedBytes, 0, 24);
return trimmedBytes;
}
PerformEncryption is used as a helper method to perform encryption/decryption of a string. A secret key is also supplied for either operation.
It is used in a web API application that is consumed by a mobile app in Android & iOS devices.
Bad Data error is occurring with large portion of the users that are on Android, with a much smaller occurance of this error on iOS. Any tests I have conducted on similar mobile devices do not produce the issue.
Only way I can reproduce error is if I modify the string value in a unit test after its encrypted.
The web API uses Async/Await so I'm not sure if this has something to do with it?
Is there anything I miss with the code above that I have left out or is bad practice?
I don't have access to the raw request being sent to the server so I can't determine if the encrypted value has its content appended with dodgy characters from Android/iOS in the request??
My other thoughts are:
should I switch from using UTF8 getbytes() to ASCII equivalent helper class if that is causing issues with iOS and android environments
Should I just switch to using a diff algorithm completely like AES.
3DES should not be used for new code, instead use AES.
Do not use ECB mode, it is insecure, see ECB mode, scroll down to the Penguin. Instead use CBC mode with a random IV, just prefix the encrypted data with the IV for use in decryption.
PBKDF2 is more secure than a simple hash or even a salted hash. The main difference is iteration in order to take more time to calculate the key,100,000 iterations is common for PBKDF2.
UTF-8 is to be preferred over ASCII which is too limited.
Related
I am trying to encrypt a string passing the same parameters, but each time it produces the same result.
Currently, each time I call Encrypt("testing"), I am getting an output of "pvsLPLnR3fI=". However, I require the output to be different even if the parameters are the same. For example, calling Encrypt("testing") 3 times could produce output of:
pvsLPLnR3fI=
nR3fIasweds=
PHQHasfdevw=
The method I use to encrypt is as follows:
private const string mysecurityKey = "MyTestSampleKey";
public static string Encrypt(string TextToEncrypt)
{
byte[] MyEncryptedArray = UTF8Encoding.UTF8.GetBytes(TextToEncrypt);
MD5CryptoServiceProvider MyMD5CryptoService = new MD5CryptoServiceProvider();
byte[] MysecurityKeyArray = MyMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(mysecurityKey));
MyMD5CryptoService.Clear();
var MyTripleDESCryptoService = new TripleDESCryptoServiceProvider();
MyTripleDESCryptoService.Key = MysecurityKeyArray;
MyTripleDESCryptoService.Mode = CipherMode.ECB;
MyTripleDESCryptoService.Padding = PaddingMode.PKCS7;
var MyCrytpoTransform = MyTripleDESCryptoService.CreateEncryptor();
byte[] MyresultArray = MyCrytpoTransform.TransformFinalBlock(MyEncryptedArray, 0, MyEncryptedArray.Length);
MyTripleDESCryptoService.Clear();
return Convert.ToBase64String(MyresultArray, 0, MyresultArray.Length);
}
You're getting the same result each time because there are no elements of the operation that are changing - you're using the same key and the same plaintext with the same algorithm. This is expected under the ECB mode of operation.
ECB is inherently insecure, so changing the mode to something like GCM (or CBC if you cannot) will both solve your original problem and improve the security immensely.
Be aware that MD5 and TripleDES are both poor choices for new software - consider using AES with a KDF that isn't a message digest, like Argon2 or PBKDF2.
I suggest you review the code examples in this repository for examples of secure, modern encryption.
I'm trying to encrypt and decrypt the string using objective c and C#. both are working fine in native code, but when I was try to decrypt string in c# was encrypted in iOS. I get some error.
This was the code I used in the objective c
- (NSData *)AES256EncryptWithKey:(NSString *)key Data: (NSData *) data
{
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [data length];
NSData *iv = [#"abcdefghijklmnopqrstuvwxyz123456" dataUsingEncoding:NSUTF8StringEncoding];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
[iv bytes] /* initialization vector (optional) */,
[data bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
In want to know how to decrypt in C#, I give blocksize is 256, ivsize to 32 and used "RijndaelManaged()". I'm not using salt & password.
Error: something like "Padding is invalid and cannot be removed."
I tried to set padding too like PKCS7, none, zero but nothing help to decrypt.
can any one help this?
Edit:
My C# code here
public string DecryptString(string encrypted)
{
string result = null;
_encoder = new UTF8Encoding();
if (!string.IsNullOrWhiteSpace(encrypted) && (encrypted.Length >= 32))
{
var messageBytes = Convert.FromBase64String(encrypted);
using (var rm = new RijndaelManaged())
{
rm.BlockSize = _blockSize;
rm.Key = _encoder.GetBytes("mykey_here");
rm.IV = _encoder.GetBytes("abcdefghijklmnopqrstuvwxyz123456"); ;
rm.Padding = PaddingMode.Zeros;
var decryptor = rm.CreateDecryptor(rm.Key, messageBytes.Take(_ivSize).ToArray());
result = _encoder.GetString(Transform(messageBytes.Skip(_ivSize).ToArray(), decryptor));
}
}
return result;
}
protected byte[] Transform(byte[] buffer, ICryptoTransform transform)
{
byte[] result;
using (var stream = new MemoryStream())
using (var cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
result = stream.ToArray();
}
return result;
}
iOS (Common Crypto) explicitly specifies all encryption parameters, the C# code implicitly determines many parameters. These implicit parameters while simplifying usage are problematic when trying to achieve interoperability.
The C# class RijndaelManaged allows explicitly specifying parameter, change your code to use these, in particular BlockSize (128), KeySize (128), Mode (CipherMode.CBC) and Padding (PaddingMode.PKCS7). The defaults for mode and Padding are OK. See RijndaelManaged Documentation
AES and Rijndael are not the same, in particular AES uses only a block size of 128 bits (16 bytes) and Rijndael allows several block sizes. So one needs to specify a block size of 128 bits for Rijndael. Thus the iv is also 128 bits (16 bytes).
Both support encryption keys of 128, 192 and 256 bytes.
You would probably be better off using the AESManaged class than the RijndaelManaged class. See AesManaged Documentation
The C# side expects the data to be Base64 encoded, the iOS side does not show that encoding operation, make sure that is being done on the iOS side.
Since you are using an iv make sure you are using CBC mode on both sides. In Common Crypto CBC mode is the default, make sure CBC mode is being used on the C# side.
Make sure the C# side is using PKCS#7 or PKCS#5 padding, they are equivalent. It appears that PKCS#7 is the default on the C# side so this should be OK.
It is best to use a key of exactly the size specified and not rely on default padding. In Common Crypto the key size is explicitly specified and null padded if the supplied key is to short. The C# looks like it is determining the key size by the supplied key, in this case the key is 10 bytes so the decryption key probably defaults to 128 bits and the key is being internally padded with nulls. On iOS you are explicitly specifying a key size of 256 bits. This is a mis-match that needs to be fixed. Supply a key that is the exact size specified on the iOS side.
Finally there is the iv, the C# code expects the iv to be prepended to the encrypted data but the iOS code is not providing that. The solution is to change the iOS code to prepend the iv to the encrypted code. Change the iv to be 16 bytes, the AES block size.
Finally provide hex dumps of the test data in, data out, iv and key just prior to and after the encryption call if you need more help.
Does .NET's RC2CryptoServiceProvider conform to OpenSSL. I'm using RC2CryptoServiceProvider with CBC but the encrypted value for the same text (using the same key and init vector) is different from what nodejs crypto library's rc2-cbc produces. Node js crypto library conforms to OpenSSL.
Someone had already asked about this discrepancy but no answers yet - Node.JS RC2-CBC Encryption and Decryption ciphers are not matching with C#
Can someone point me to the complete source code RC2CryptoServiceProvider? Is the encrypt/decrypt code a completely managed one available in C# or does it use C++ underneath?
I'm interested in finding the differences as I'm looking for a way to decrypt a .NET application encrypted string in node js.
Below is the C# code and the corresponding node js code. For the same data (HelloWorld), key and iv, the encrypted values produced are different.
public static string Encrypt(string data, string key, string iv)
{
try
{
byte[] ivBytes = Encoding.ASCII.GetBytes(iv);
byte[] keyBytes = Encoding.ASCII.GetBytes(key);
byte[] dataBytes = Encoding.ASCII.GetBytes(data);
RC2 rc = new RC2CryptoServiceProvider();
rc.Mode = CipherMode.CBC;
rc.Key = keyBytes;
rc.IV = ivBytes;
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, rc.CreateEncryptor(), CryptoStreamMode.Write);
stream2.Write(dataBytes, 0, dataBytes.Length);
stream2.Close();
return Convert.ToBase64String(stream.ToArray());
}
catch
{
return string.Empty;
}
}
Below is the node js code.
algo = 'rc2-cbc'
key = '1234567890'
iv = 'someInit'
keyBuffer = new Buffer(key)
ivBuffer = new Buffer(iv)
cipher = crypto.createCipheriv(algo, keyBuffer, ivBuffer)
textBuffer = new Buffer('HelloWorld')
encrypted = cipher.update(textBuffer)
encryptedFinal = cipher.final()
encryptedText = encrypted.toString('base64') + encryptedFinal.toString('base64')
console.log encryptedText
I hit a similar situation. There is existing .NET (core) code using RC2CryptoServiceProvider to decrypt a string. I wanted to replicate this in node.
The .NET code uses keysize 128 (which also appears to be the default) so I assumed the comparable algorithm in node (openssl) would be rc2-128. But this always failed when decrypting.
After some trial and error I discovered that using using the rc2-64 algorithm in node behaves the same as the .NET code using keysize 128. Just don't ask me why!
I'm using this function to Encrypt/Decrypt data using AES because it looked simple and clean (googl'ed code)
public static string Encrypt(string toEncrypt)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes("3a8114db34d5623d4fd1ee0fb0ga7a73"); // 256-AES key
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7; // better lang support
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string toDecrypt)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes("3a8114db34d5623d4fd1ee0fb0ga7a73"); // AES-256 key
byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7; // better lang support
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString(resultArray);
}
I'm trying to encrypt the data "test garbage" and thats what i receive back:
YfhyS3GE/liPCaXR0cMHfQ==
However, I tried the same key/phrase on a lot of online-aes encrypt/decrypt and all of them are returning
U2FsdGVkX184u0/vPgA/B0rxofp5Iuqm7hfn4+QZAhg=
Can anyone actually tell me whats wrong?
"3a8114db34d5623d4fd1ee0fb0ga7a73" is hex encoded 128 bit key not a utf8 encoded 256 bit key.
That said simple and clean doesn't necessarily mean correct. For example, the code your using does use a random IV, but doesn't include it in the wire format, you'll never be able to decrypt what you encrypt.
I have a cut and paste style simple code sample that I try to keep up to date and reviewed that uses authenticated encryption using AES:
Modern Examples of Symmetric Authenticated Encryption of a string. C#
First a few issues with your code. Apparently Google doesn't always return the best code on top.
You are getting a key through the UTF8 encoding, which is silly. This produces a very weak key:
// 256-AES key
byte[] keyArray = UTF8Encoding.UTF8.GetBytes("3a8114db34d5623d4fd1ee0fb0ga7a73");
You are using CBC mode but the IV is not (explicitly) set.
Then you compare to some online-aes encrypt/decrypt services and you see a difference. That's because they probably (hopefully) work different.
The main thing here is that your 2 methods are a match and you can round-trip your data. But a good encryption would use a different way to get Key and IV.
I'm not exactly sure why you see a different (smaller) length encrypted data but that's up to a whole list of settings : Key length, Padding mode etc.
Mysql :
SELECT AES_ENCRYPT('Test','pass')
AES_ENCRYPT() and AES_DECRYPT() enable encryption and decryption of data using the official AES (Advanced Encryption Standard) algorithm, previously known as “Rijndael.” Encoding with a 128-bit key length is used, but you can extend it up to 256 bits by modifying the source. We chose 128 bits because it is much faster and it is secure enough for most purposes.
http://dev.mysql.com/doc/refman/5.5/en/encryption-functions.html#function_aes-encrypt
I was trying to convert that Encrypted string into Decryped Strig in C#.net but i don't get the results as i expect.
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx#Y0
C#
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
In this method I pass ciphertext,Key value which i usedfrom Mysql and
Rijndael.Create().IV for byte[] IV
I use the code but i don't get expected result.
Review the code and comment Idk where made a mistake
What you are doing is following a road of pain. Either decrypt/encrypt on MySQL and use an encrypted connection to the database (if that matters) or encrypt/decrypt on your .NET application, storing the encrypted data in a suitable column.
Mixing AES implementations is prone to mistakes and things can break more easily if you change versions of .NET or MySQL.
Now, to know what exactly is wrong we need to know if the IV is compatible between MySQL and .NET, or else find out what is MySQL's implementation IV and supply that.
And the other potential source of problems is how you have generated the byte arrays (we are not seeing that in your example). You have to consider character encoding issues in generating the arrays if the key is textual.
In the comments of this MySQL docs link there is information about the missing parameters.
After a long hours, I found a solution to this issue.
Couple of FYI's:
MySQL as a default for AES_Encrypt uses 128 bit, with ECB mode, which does not require an IV.
What padding mode they use is not specified, but they do say they pad it. For padding I use PaddingMode.Zeros.
In C#, use AesManaged, not RijndaelManaged since that is not recommended anymore.
If your Key is longer than 128 bits (16 bytes), then use a function below to create the correct key size, since the default MySQL AES algorithm uses 128 bit keys.
Make sure you play around with the correct Encoding and know exactly what type of character encoding you will receive back when translating the bytes to characters.
For more info go here: https://forums.mysql.com/read.php?38,193084,195959#msg-195959
Code:
public static string DecryptAESStringFromBytes(byte[] encryptedText, byte[] key)
{
// Check arguments.
if ((encryptedText == null || encryptedText.Length <= 0) || (key == null || key.Length <= 0))
{
throw new ArgumentNullException("Missing arguments");
}
string decryptedText = null;
// Create an AES object with the specified key and IV.
using (AesManaged aesFactory = new AesManaged())
{
aesFactory.KeySize = 128;
aesFactory.Key = AESCreateKey(key, aesFactory.KeySize / 8);
aesFactory.IV = new byte[16];
aesFactory.BlockSize = 128;
aesFactory.Mode = CipherMode.ECB;
aesFactory.Padding = PaddingMode.Zeros;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesFactory.CreateDecryptor();
// Create the streams used for decryption.
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
{
decryptStream.Write(encryptedText, 0, encryptedText.Length);
}
decryptedText = Encoding.Default.GetString(stream.ToArray());
}
}
return decryptedText.Trim();
}
public static byte[] AESCreateKey(byte[] key, int keyLength)
{
// Create the real key with the given key length.
byte[] realkey = new byte[keyLength];
// XOR each byte of the Key given with the real key until there's nothing left.
// This allows for keys longer than our Key Length and pads short keys to the required length.
for (int i = 0; i < key.Length; i++)
{
realkey[i % keyLength] ^= key[i];
}
return realkey;
}
Here is some working code for achieving the same encryption via C# as MySQL:
public byte[] AESEncrypt(byte[] plaintext, byte[] key) {
/*
* Block Length: 128bit
* Block Mode: ECB
* Data Padding: Padded by bytes which Asc() equal for number of padded bytes (done automagically)
* Key Padding: 0x00 padded to multiple of 16 bytes
* IV: None
*/
RijndaelManaged aes = new RijndaelManaged();
aes.BlockSize = 128;
aes.Mode = CipherMode.ECB;
aes.Key = key;
ICryptoTransform encryptor = aes.CreateEncryptor();
MemoryStream mem = new MemoryStream();
CryptoStream cryptStream = new CryptoStream(mem, encryptor,
CryptoStreamMode.Write);
cryptStream.Write(plaintext, 0, plaintext.Length);
cryptStream.FlushFinalBlock();
byte[] cypher = mem.ToArray();
cryptStream.Close();
cryptStream = null;
encryptor.Dispose();
aes = null;
return cypher;
}
For details see MySQL Bug # 16713
EDIT:
Since the above is relying on officially non-documented information (though it is working) I would recommend to avoid it and use one of the options described in the answer from Vinko Vrsalovic .
If you run SELECT AES_ENCRYPT('Test','pass')
your are sending the pass over the network unencrypted so any one can unencrypted the data.
The AES_ENCRYPT is used to store data so if the database gets hacked your data is safe, not to transmit data.
if you want data encryption over the net work connect to your mysql server using the ssl socket