AES encrypt C# decrypt Java? - c#

I'm trying to decrypt C# encrypted data in Java without success. I'm using 128 bit key&block size with PKCS7 padding. Here's C# code:
public byte[] Encrypt(byte[] data, byte[] key)
{
using (var ms = new MemoryStream())
{
using (var aes = RijndaelManaged.Create())
{
aes.Key = key;
aes.IV = key;
var stream = new CryptoStream(ms, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write);
stream.Write(data, 0, data.Length);
stream.FlushFinalBlock();
return ms.ToArray();
}
}
}
and this is java code:
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(Files.readAllBytes(Paths.get("D:/Temp/cr.key")), "AES");
return key;
}
public static byte[] decrypt(byte[] encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
IvParameterSpec ivSpec = new IvParameterSpec(key.getEncoded());
c.init(Cipher.DECRYPT_MODE, key, ivSpec);
System.out.println(c.getBlockSize());
c.update(encryptedData);
byte[] decValue = c.doFinal();
return decValue;
}
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] bb = decrypt(Files.readAllBytes(Paths.get("d:\\Temp\\cr~\\OEBPS\\Chapter001.html")));
//decompressFile(bb, new File("D:\\Temp\\enc.html"));
}
Any idea what could be wrong?
THanks
UPDATE
Sorry, how dumb of me, I forgot to write actual error message. Here it is:
Exception in thread "main" javax.crypto.BadPaddingException: pad block
corrupted at
org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown
Source) at javax.crypto.Cipher.doFinal(Cipher.java:1970)
Thanks

You are forgetting that Cipher.update(byte[]): byte[] will return data whenever a full block of ciphertext has been processed.
NOTE: Apparently not an answer to this question, as the exception points to another error. But a bug in the above code none-the-less.

Related

Is it possible to run a PHP function in .NET?

I'm trying to decrypt AES-128 CBC strings in C# but with no success (tried every decrypt method I found on internet for this type of encryption).
The only way I got a result was decrypting those strings in PHP using this code:
<?php
$crypto_data = hex2bin($crypto_data_hex);
$real_data = openssl_decrypt($crypto_data,
'AES-128-CBC',
'23d854ce7364b4f7',
OPENSSL_RAW_DATA,
'23d854ce7364b4f7');
?>
So, is there a way to run this PHP code in .NET (using a PHP.dll library or something similar) ? Or is there a real equivalent method for this operation in .NET C# ?
Thank you
The question seems to boil down to writing C# function that is equivalent to PHP function.
Try this code:
public class Program
{
public static byte[] HexToBytes(string hex)
{
int numberChars = hex.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
{
string plaintext;
AesManaged aes = new AesManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
BlockSize = 128,
Key = key,
IV = iv
};
using (aes)
{
ICryptoTransform decryptor = aes.CreateDecryptor();
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
plaintext = reader.ReadToEnd();
}
}
}
}
return plaintext;
}
public static void Main()
{
string crypto_data_hex = "00965fa56e761b11d37b887f98e6bcc2"; // paste $crypto_data_hex value here
string sKey = "23d854ce7364b4f7";
string sIv = "23d854ce7364b4f7";
byte[] encrypted = HexToBytes(crypto_data_hex);
byte[] key = Encoding.ASCII.GetBytes(sKey);
byte[] iv = Encoding.ASCII.GetBytes(sIv);
string decrypted = Decrypt(encrypted, key, iv);
Console.WriteLine(decrypted);
}
}

Unrecognized unicode result from AES decryption

I try to build simple AES encryption helper to encrypt/decrypt some strings
Fist, I have an issue with Padding mode wherein decryption it only accepts if Zero otherwise an error about padding occurs!
The second issue is when I try to encrypt simple string "Hello World," it got encrypted, and I have the base64 string, but when trying to decrypt, there's no error, but a weird unknown character is shown! like 㡲啁䎰廾ử靱힩㡲啁䎰廾ử靱힩
My code:
private static int keySizes = 256;
private static int blockSize = 128;
private static PaddingMode pMode = PaddingMode.Zeros;
private static CipherMode cMode = CipherMode.ECB;
private static byte[] key = GenEncryptionKey();
private const string passphrase = #"StartYourMorningWithASmile";
private static byte[] GenEncryptionKey()
{
HashAlgorithm hash = MD5.Create();
return hash.ComputeHash(Encoding.Unicode.GetBytes(passphrase));
}
private static AesManaged CreateCryptor()
{
AesManaged cryptor = new AesManaged();
cryptor.KeySize = keySizes;
cryptor.BlockSize = blockSize;
cryptor.Padding = pMode;
cryptor.Key = key;
cryptor.Mode = cMode;
cryptor.GenerateIV();
return cryptor;
}
public static string EncryptParams(string reqVal)
{
string cipherText = "";
if (string.IsNullOrEmpty(reqVal) || reqVal.Length < 1)
throw new ArgumentNullException();
byte[] plainBytes = Encoding.Unicode.GetBytes(reqVal);
using (var cryptor = CreateCryptor())
{
ICryptoTransform encryptor = cryptor.CreateEncryptor();
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(plainBytes, 0, plainBytes.Length);
}
byte[] cipherBytes = ms.ToArray();
cipherText = Convert.ToBase64String(cipherBytes);
}
cryptor.Clear();
}
return cipherText;
}
public static string DecryptParams(string resVal)
{
var data = Convert.FromBase64String(resVal);
byte[] cipherBytes = new byte[data.Length];
string plainText = "";
using (var crypto = CreateCryptor())
{
ICryptoTransform Dec = crypto.CreateDecryptor();
using (MemoryStream ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, Dec, CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
plainText = Encoding.Unicode.GetString(ms.ToArray());
}
}
crypto.Clear();
}
return plainText;
}
UPDATE 1:
Please set also the IV yourself to achieve successful decryption, as #maarten-bodewes pointed out. I missed that part and the decryption somehow worked (?) with your existing code, but you always should provide the same key and IV to a symmetric encryption algorithm to have it work both ways.
ORIGINAL ANSWER:
Your decryption fails (produces incorrect results) because you implemented the decryption part incorrectly (by using CryptoStreamMode.Write instead of CryptoStreamMode.Read) and besides feeding the decryption stream all zero bytes
At the point of execution of
cs.Write(cipherBytes, 0, cipherBytes.Length);
the variable cipherBytes is all zero. The real encrypted buffer is in the data variable which you only use to set the length of cipherBytes
So change your decryption method to this.
BONUS: After correcting the decryption part, you can specify the padding as you wish! I tested with PKCS7 and it is ok.
public static string DecryptParams(string resVal)
{
var cipherBytes = Convert.FromBase64String(resVal);
string plainText = "";
using (var crypto = CreateCryptor())
{
ICryptoTransform Dec = crypto.CreateDecryptor();
using (MemoryStream ms = new MemoryStream(cipherBytes))
{
using (var cs = new CryptoStream(ms, Dec, CryptoStreamMode.Read))
{
byte[] decryptBlock = new byte[4096];
MemoryStream decryptStream = new MemoryStream();
int readBytes;
while ((readBytes = cs.Read(decryptBlock, 0, 4096)) > 0)
{
decryptStream.Write(decryptBlock, 0, readBytes);
}
plainText = Encoding.Unicode.GetString(decryptStream.ToArray());
}
}
crypto.Clear();
}
return plainText;
}
Hope this helps.
Thanks to Oguz
Below is my description method after edit
public static string DecryptParams(string resVal)
{
var data = Convert.FromBase64String(resVal);
byte[] cipherBytes = new byte[data.Length];
string plainText = "";
using (var crypto = CreateCryptor())
{
ICryptoTransform Dec = crypto.CreateDecryptor();
using (MemoryStream ms = new MemoryStream(data))
{
using (var cs = new CryptoStream(ms, Dec, CryptoStreamMode.Read))
{
cs.Read(cipherBytes, 0, cipherBytes.Length);
plainText = Encoding.Unicode.GetString(cipherBytes.ToArray());
}
}
crypto.Clear();
}
return plainText;
}
one more thing about the return result after the decryption I got the original string plus \0\0\0\0 so I use myString.TrimEnd('\0') to solve that.

AESManaged File Encryption and Decryption and prepending initiaization vector

I am trying to encrypt/decrypt bytes - I have done a lot of reading about the Key and IV for the AES algorithm using the AESManaged class in System.Security.Cryptography. I read James Johnson's answer to the following question http://www.techques.com/question/1-7025135/My-Length-of-the-data-to-decrypt-is-invalid-error where he suggests that you use a random IV in the encryption routine and prepend the IV to the encrypted message. The decrypt function strips off the random IV from the beginning of the encrypted message to initialize the decryption class and then decrypts the rest of the bytes. I have attempted to do this in the following code. But I keep getting the "Length of the data to decrypt is invalid." error message when I attempt the decrypt after the encryption. Could someone possibly shed some light on what might be wrong.
USAGE: (streamToEncrypt/streamToDecrypt are System.IO.Stream)
using (var cryptoHelper = new AESHelper())
{
var encryptedBytes = cryptoHelper.Encrypt(AESHelper.StreamToByteArray(streamToEncrypt));
}
using (var cryptoHelper = new AESHelper())
{
var decryptedBytes = cryptoHelper.Decrypt(AESHelper.StreamToByteArray(streamToDecrypt));
}
public class AESHelper : IDisposable
{
public AesManaged AESManaged;
internal ICryptoTransform Encryptor { get; set; }
internal ICryptoTransform Decryptor { get; set; }
private const string KEY = "2428GD19569F9B2C2341839416C8E87G";
private static readonly byte[] Salt = Encoding.ASCII.GetBytes("?pt1$8f]l4g80");
private const Int32 ITERATIONS = 1042;
internal AESHelper()
{
AESManaged = new AesManaged();
AESManaged.BlockSize = AESManaged.LegalBlockSizes[0].MaxSize;
AESManaged.KeySize = AESManaged.LegalKeySizes[0].MaxSize;
AESManaged.Mode= CipherMode.CBC;
}
public void KeyGenerator()
{
var key = new Rfc2898DeriveBytes(KEY, Salt, ITERATIONS);
AESManaged.Key = key.GetBytes(AESManaged.KeySize / 8);
}
public byte[] Encrypt(byte[] input)
{
KeyGenerator();
var ms = new MemoryStream();
//Random IV
Encryptor = AESManaged.CreateEncryptor(AESManaged.Key, AESManaged.IV);
//Add the IV to the beginning of the memory stream
ms.Write(BitConverter.GetBytes(AESManaged.IV.Length), 0, sizeof(int));
ms.Write(AESManaged.IV, 0, AESManaged.IV.Length);
var cs = new CryptoStream(ms,
Encryptor, CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();
return ms.ToArray();
}
public byte[] Decrypt(byte[] input)
{
KeyGenerator();
// Get the initialization vector from the encrypted stream
var ms = new MemoryStream(input);
AESManaged.IV = ReadByteArray(ms);
Decryptor = AESManaged.CreateDecryptor(AESManaged.Key, AESManaged.IV);
var cs = new CryptoStream(ms,
Decryptor, CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();//Error occurs here
return ms.ToArray();
}
internal static byte[] ReadByteArray(Stream s)
{
var rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
var buffer = new byte[16];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
internal static byte[] StreamToByteArray(Stream inputStream)
{
if (!inputStream.CanRead)
{
throw new ArgumentException();
}
// This is optional
if (inputStream.CanSeek)
{
inputStream.Seek(0, SeekOrigin.Begin);
}
var output = new byte[inputStream.Length];
var bytesRead = inputStream.Read(output, 0, output.Length);
Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
return output;
}
public void Dispose()
{
if (AESManaged != null)
((IDisposable) AESManaged).Dispose();
}}
Many Thanks in advance
Probably you have solved this already but I'll just put my answer for others who faces similar issue.
Error occurs due to the additional information present in the input array. In public byte[] Encrypt(byte[] input) method you are writing IV length and IV before the ciphered data is written. Lines:
ms.Write(BitConverter.GetBytes(AESManaged.IV.Length), 0, sizeof(int));
ms.Write(AESManaged.IV, 0, AESManaged.IV.Length);
In public byte[] Decrypt(byte[] input) method you are reading this information and using read IV as initialization vector for AES algorithm. All fine. Then you are constructing CryptoStream with CryptoStreamMode.Write and passing MemoryStream object ms which gets decrypted data. However the passed input array contains not only the encrypted message but also the IV that you wrote during the encryption process. That is why it fails to decrypt.
What you need to do to overcome this is either extract only cipher data from the input array and pass it to: cs.Write(cipherData, 0, cipherData.Length); or change mode into CryptoStreamMode.Read and use cs.Read(outputBuff, 0, outputBuff.Length);.
Also don't use the same MemoryStream object to read and write to because you'll have some garbage in it after CryptoStream will write in it.

Getting incorrect decryption value using AesCryptoServiceProvider

I have following code that uses AesCryptoServiceProvider for encrypting and decrypting. The iv and key used are same for both encryption and decryption. Still the decrypted value differ from the source string.
What need to be corrected to get the original value after decrypt?
This code is working when inputValue = valid128BitString. But when the inputString = “Test” I am getting the following exception Padding is invalid and cannot be removed.. How can we correct it?
UPDATED QUESTION
The following will do the trick based on #jbtule answer.
encyptedValue.IV = result.IV;
The IV value from encryption result changes. Suppose encryption is done in a separate process, how can we know the IV for decryption? Is there a way to make it constant or known?
Answer: Your other option is pass a IV in to Encrypt and assign it before you begin your crypto transform, instead of letting aesProvider generate a random one for you. – #Scott Chamberlain
aesProvider.IV = Convert.FromBase64String("4uy34C9sqOC9rbV4GD8jrA==");
Update: Refer How to apply padding for Base64. We can use UTF8 for encoding the source input and result output. The key and IV may remain in Base64.
Using Base64 for source input will cause issues with some values, for example, "MyTest" where length of string is not a multiple of 4
Relevant points:
To decrypt data that was encrypted using one of the SymmetricAlgorithm classes, you must set the Key property and IV property to the same values that were used for encryption.
SymmetricAlgorithm.IV Property: Information from the previous block is mixed into the process of encrypting the next block. Thus, the output of two identical plain text blocks is different. Because this technique uses the previous block to encrypt the next block, an initialization vector is needed to encrypt the first block of data. (As per SymmetricAlgorithm.IV Property MSDN article)
The valid Key sizes are: 128, 192, 256 bits (as per How many characters to create a byte array for my AES method?)
Main Program
class Program
{
static void Main(string[] args)
{
string valid128BitString = "AAECAwQFBgcICQoLDA0ODw==";
string inputValue = valid128BitString;
string keyValue = valid128BitString;
string iv = valid128BitString;
byte[] byteValForString = Convert.FromBase64String(inputValue);
EncryptResult result = Aes128Utility.EncryptData(byteValForString, keyValue);
EncryptResult encyptedValue = new EncryptResult();
encyptedValue.IV = iv;
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 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;
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 Class
public class EncryptResult
{
public string EncryptedMsg { get; set; }
public string IV { get; set; }
}
References
How many characters to create a byte array for my AES method?
Specified key is not a valid size for this algorithm
Encryption with AES-256 and the Initialization Vector
Invalid length for a Base-64 char array
What's the difference between UTF8/UTF16 and Base64 in terms of encoding
It is easy to make implementation mistakes with cryptographic primitives, people do it all the time, it's best to use a high level library if you can.
I have a snippet that I try to keep reviewed and up to date, that works pretty close to what you're doing. It also does authentication on the cipher text, which I would recommend if there is anyway an adversary could send chosen ciphertext to your decryption implementation, there are a lot of side channel attacks related to modifying the ciphertext.
However, the problem you're having does not have any thing to do with padding, if your ciphertext doesn't matchup to your key and iv, and you didn't authenticate your iv and ciphertext, you'll typically get a padding error (if this is bubbled up a client it's called a padding oracle). You need to change your main statement to:
string valid128BitString = "AAECAwQFBgcICQoLDA0ODw==";
string inputValue = "Test";
string keyValue = valid128BitString;
byte[] byteValForString = Encoding.UTF8.GetBytes(inputValue);
EncryptResult result = Aes128Utility.EncryptData(byteValForString, keyValue);
EncryptResult encyptedValue = new EncryptResult();
encyptedValue.IV = result.IV; //<--Very Important
encyptedValue.EncryptedMsg = result.EncryptedMsg;
string finalResult =Encoding.UTF8.GetString(Aes128Utility.DecryptData(encyptedValue, keyValue));
So you use the same IV to decrypt as you did to encrypt.

Encryption between Android and C#

I am using the following C# source code to encrypt plain text using AES (ECB 256):
public static string Encode(string PlainText)
{
byte[] Key = ASCIIEncoding.UTF8.GetBytes("12345678901234567890123456789012");
string encrypted = null;
RijndaelManaged rj = new RijndaelManaged();
rj.BlockSize = 256;
rj.KeySize = 256;
rj.Key = Key;
rj.GenerateIV();
byte[] IV = rj.IV;
rj.Mode = CipherMode.ECB;
rj.Padding = PaddingMode.Zeros;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(PlainText);
sw.Close();
sw.Dispose();
}
cs.Close();
cs.Dispose();
}
byte[] encryptArray = ms.ToArray();
encrypted = (Convert.ToBase64String(encryptArray));
ms.Close();
ms.Dispose();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
rj.Clear();
}
return encrypted;
}
And I need decrypt/encrypt data through same algorithm, but I don't know how.
Here my Java Class (not working):
public static String encrypt(byte[] key, String cleartext, boolean base64) throws Exception
{
byte[] rawKey = key;
byte[] result = encrypt(rawKey, cleartext.getBytes());
// Base 64
if (base64)
return toBase64(result);
// Hex
return toHex(result);
}
public static String decrypt(byte[] key, String encrypted)
throws Exception
{
byte[] rawKey = key;
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
Java call:
encrypt("12345678901234567890123456789012".getBytes(), "Example Message", true);
I dont know how I can select the block size or the PaddingMode.Zeros in Java.
¿Any idea?
Thanks in advance
Yes, the problem is the limit of 128 bits block size in AES (see 'Strong Versus Unlimited Strength Cryptography').
Finally, I've used GNU Crypto and it works!. I've imported all source code and I've deleted the code that I'm not using.
If somebody wants the cleaned source code he only have to ask me.
Thanks for the help.
You should also consider Bouncy Castle, it's available for both C# and Java
http://www.bouncycastle.org
Reading over this article, it seems you might need to use a version of Java that allows unlimited strength cryptography so that you can use large key sizes (AES-192 and AES-256). They intentionally limit the key lengths that can be used by default due to import-control restrictions imposed by some countries. See the 'Strong Versus Unlimited Strength Cryptography' section for more information.

Categories

Resources