Currently I am working on an project where we are building an server side and client side application (mobile device, using Xamarin). We are encrypting and decrypting the data (using AES...), with the exact following implementation for the server-side: Encrypting & Decrypting a String in C#
Unforunately we cannot use that implementation within our Xamarin project. So we would like to use Bouncycastle to decrypt the data. I came across the following Java implementation of Bouncycastle, and tried to modify it in order to get it to work with .NET. How to use Bouncy Castle lightweight API with AES and PBE
Resulting in:
private byte[] decryptWithLWCrypto(string cipherText, String password, int iterationCount)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
var salt = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipher = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
Pkcs12ParametersGenerator pGen = new Pkcs12ParametersGenerator(new Sha256Digest());
byte[] pkcs12PasswordBytes = Convert.FromBase64String(password);//PbeParametersGenerator
pGen.Init(pkcs12PasswordBytes, salt, iterationCount);
CbcBlockCipher aesCBC = new CbcBlockCipher(new RijndaelEngine(256));//was AesEngine
ParametersWithIV aesCBCParams = new ParametersWithIV(pGen.GenerateDerivedParameters(256, 128), ivStringBytes);
aesCBC.Init(false, aesCBCParams);
PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(aesCBC,
new Pkcs7Padding());
byte[] plainTemp = new byte[aesCipher.GetOutputSize(cipher.Length)];
int offset = aesCipher.ProcessBytes(cipher, 0, cipher.Length, plainTemp, 0);
int last = aesCipher.DoFinal(plainTemp, offset);
byte[] plain = new byte[offset + last];
System.Array.Copy(plainTemp, 0, plain, 0, plain.Length);
return plain;
}
Now I get the following error, because I am trying to adapt the sample from Java to AES256:
Additional information: invalid parameter passed to Rijndael init - Org.BouncyCastle.Crypto.Parameters.ParametersWithIV
At this point I tried a lot, the error itself explains what is going on. But I lack the experience with Bouncycastle to get it to work using AES256, IV and salt. I read that you can't use AesEngine
, so you have to switch to RijndaelEngine
for AES256.
Does anyone have an working implementation using this setup? Within the Xamarin app System.Security.Cryptography
cannot be used.