我在Windows Phone应用程序的C#中进行加密,我需要使用java解密它。 这是我的加密代码
public static String encrypt(String plaintext, KeyParameter keyParam)
{
byte[] ivData = new byte[AES_NIVBITS / 8];
Random r = new Random();
r.NextBytes(ivData);
IBlockCipherPadding padding = new Pkcs7Padding();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), padding);
ICipherParameters param = new ParametersWithIV(keyParam, ivData);
cipher.Reset();
cipher.Init(true, param);
byte[] bytesDec = Encoding.GetEncoding("iso-8859-1").GetBytes(plaintext);
byte[] bytesEnc = null;
int buflen = cipher.GetOutputSize(bytesDec.Length);
System.Diagnostics.Debug.WriteLine("enc length " + buflen);
bytesEnc = new byte[buflen];
int nBytesEnc = cipher.ProcessBytes(bytesDec, 0, bytesDec.Length, bytesEnc, 0);
nBytesEnc += cipher.DoFinal(bytesEnc, nBytesEnc);
if (nBytesEnc != bytesEnc.Length)
{
throw new Exception("Unexpected behaviour : getOutputSize value incorrect");
}
byte[] bytesAll = new byte[ivData.Length + bytesEnc.Length];
Array.Copy(ivData, 0, bytesAll, 0, ivData.Length);
Array.Copy(bytesEnc, 0, bytesAll, ivData.Length, bytesEnc.Length);
byte[] bytesAllb64 = Base64.Encode(bytesAll);
return Encoding.GetEncoding("iso-8859-1").GetString(bytesAllb64, 0, bytesAllb64.Length);
}
这是用于解密的java代码
public static String decodeBase64Aes(String encodedciphertext, KeyParameter keyParam) throws Exception
{
byte[] bytesEnc = Base64.decode(encodedciphertext.getBytes(ISO8859));
int nIvBytes = AES_NIVBITS / 8;
byte[] ivBytes = new byte[nIvBytes];
System.arraycopy(bytesEnc, 0, ivBytes, 0, nIvBytes);
CipherParameters params = new ParametersWithIV(keyParam, ivBytes);
BlockCipherPadding padding = new PKCS7Padding();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
cipher.reset();
cipher.init(false, params);
byte[] bytesDec = null;
int buflen = cipher.getOutputSize(bytesEnc.length - nIvBytes);
byte[] workingBuffer = new byte[buflen];
int len = cipher.processBytes(bytesEnc, nIvBytes, bytesEnc.length - nIvBytes, workingBuffer, 0);
len += cipher.doFinal(workingBuffer, len);
bytesDec = new byte[len];
System.arraycopy(workingBuffer, 0, bytesDec, 0, len);
return new String(bytesDec, ISO8859);
}
当我加密它时工作正常但是当我使用我得到的密钥测试解密时,它会抛出
Exception in thread "main" org.bouncycastle.crypto.DataLengthException: last block incomplete in decryption
我只能更改c#部分。任何帮助将受到高度赞赏???
Key -> 8fe3f8b34e87744c175aae43cc52ee13
'Hello World' -> Nb90n51LqK13LzpalV7qTs7YJqe9m+Ni9uA/U7tU06Y=
异常上线
len += cipher.doFinal(workingBuffer, len);
当我加密" Hello World"来自java使用我在我的服务器上加密方法中的相同密钥
uWMz8ZIPh+3jnGtwxpuyK9Qht7BJV4RQ/Iet9JeTrTk=
编辑------
已更新为工作代码。
答案 0 :(得分:0)
Base 64与原始版本的长度不同,这就是我为什么会遇到这个错误的原因。我已使用正确的代码更新了代码。