目前我正在开发一个项目,我们正在构建服务器端和客户端应用程序(移动设备,使用Xamarin)。我们正在加密和解密数据(使用AES ...),以及服务器端的以下实现: Encrypting & Decrypting a String in C#
不幸的是,我们无法在Xamarin项目中使用该实现。所以我们想用Bouncycastle来解密数据。我遇到了以下Bouncycastle的Java实现,并尝试对其进行修改以使其与.NET一起使用。 How to use Bouncy Castle lightweight API with AES and PBE
导致:
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;
}
现在我收到以下错误,因为我正在尝试将Java中的示例调整为AES256:
Additional information: invalid parameter passed to Rijndael init - Org.BouncyCastle.Crypto.Parameters.ParametersWithIV
此时我尝试了很多,错误本身解释了发生了什么。但是我缺乏使用AES256,IV和盐来使用Bouncycastle的经验。我读到您无法使用AesEngine
,因此您必须切换到RijndaelEngine
以获取AES256。
有没有人使用此设置进行实际工作?在Xamarin应用程序中System.Security.Cryptography
无法使用。