2
我目前正在編寫一個Java程序,它將接受來自PHP的字符串,並根據需要對它們進行加密或解密。加密機制是AES-256,我使用BouncyCastle API來完成它。爲了確保來回傳輸數據的問題更少,我使用Base64對字符串進行編碼。我遇到的問題是,隨機地,我無法解密一個字符串 - 一些字符串可以解密,其他人不能。我在這裏找到了一篇很棒的文章,我認爲可以提供幫助here.BouncyCastle涉及PHP和Base64的「解密最後一塊不完整」問題
但是我真的不知道它是如何適合我的情況的(我不是一個加密專家)。這是我目前的代碼。謝謝你的幫助。
class AES {
private final BlockCipher AESCipher = new AESEngine();
private PaddedBufferedBlockCipher pbbc;
private KeyParameter key;
AES()
{
init();
}
private void init()
{
try
{
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
SecretKey sk = kg.generateKey();
key=new KeyParameter(sk.getEncoded());
pbbc=new PaddedBufferedBlockCipher(AESCipher, new PKCS7Padding());
}
catch (Exception e)
{
//Take care of later
}
}
private byte[] processing(byte[] input, boolean encrypt)
throws DataLengthException, InvalidCipherTextException {
pbbc.init(encrypt, key);
byte[] output = new byte[pbbc.getOutputSize(input.length)];
int bytesWrittenOut = pbbc.processBytes(
input, 0, input.length, output, 0);
pbbc.doFinal(output, bytesWrittenOut);
return output;
}
private byte[] _encrypt(byte[] input)
throws DataLengthException, InvalidCipherTextException {
return processing(input, true);
}
private byte[] _decrypt(byte[] input)
throws DataLengthException, InvalidCipherTextException {
return processing(input, false);
}
public String Encrypt(String input)
{
try
{
byte[] ba = input.getBytes("UTF-8");
byte[] encr = _encrypt(ba);
byte[] encryptedByteValue = new Base64().encode(encr);
String encryptedValue = new String(encryptedByteValue);
return encryptedValue;//+" and decrypted is "+Decrypt(encryptedValue);
}
catch (Exception e)
{
return "ENCRYPT_ERROR "+e.getMessage();
}
}
public String Decrypt(String input)
{
try
{
byte[] decodedValue = new Base64().decode(input.getBytes());
byte[] retr = _decrypt(decodedValue);
return new String(retr, "UTF-8").replaceAll("\\u0000", "");
}
catch (Exception e)
{
return "DECRYPT_ERROR "+e.getMessage();
}
}
剛剛受到+謝謝你離開這裏:) – jorgeu