私は現在、PHPからの文字列を受け入れ、必要に応じてそれらを暗号化または復号化するプログラムをJavaで作成しています。暗号化のメカニズムはAES-256であり、私はBouncyCastleAPIを使用して暗号化を行っています。データをやり取りする際の問題を少なくするために、Base64を使用して文字列をエンコードしています。私が経験している問題は、ランダムに文字列を復号化できないことです。一部の文字列は正常に復号化できますが、他の文字列は復号化できません。私はここで役立つと思ったstackoverflowで素晴らしい記事を見つけました。
しかし、それが自分の状況にどのように適合するかは実際にはわかりませんでした(私は暗号化の専門家ではありません)。これが私の現在のコードです。ご協力いただきありがとうございます。
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();
}
}