JAVAでAES/CBC/NoPaddingを使用して暗号化と復号化を試みています。私は(mcrypt)を使ってJAVAとPHPの両方で暗号化を行い、同じキーとivを使って同じ結果を得ました。しかし、私がJAVAで解読しようとすると、単語は正しく取得されますが、常に余分な文字が付きます。私は他の質問を読んで、パディングを追加する必要があることを発見しました。そこでPadding5を追加しましたが、同じ結果が得られました。とにかく、それはPHPで動作するので、私はそれを必要としません。どんな助けもありがとうございます。私のコードは以下であり、結果はここにある:16である場合、ブロック長にゼロバイトまでと] 2AES CBC復号化に余分な文字が埋められないJAVa
public class RijndaelCrypt {
//private String key = "2a4e2471c77344b3bf1de28ab9aa492a444abc1379c3824e3162664a2c2b811d";
private static String iv = "beadfacebadc0fee";
private static String hashedKey = "6a2dad9f75b87f5bdd365c9de0b9c842";
private static Cipher cipher;
public static String decrypt(String text) throws UnsupportedEncodingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException {
SecretKeySpec keyspec = new SecretKeySpec(hashedKey.getBytes("UTF-8"), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] decodedValue = Base64.decode(text.getBytes("UTF-8"));
byte[] decryptedVal = cipher.doFinal(decodedValue);
return new String(decryptedVal);
}
public static String encryptNew(String data) throws Exception {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes("UTF-8");
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(hashedKey.getBytes("UTF-8"), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return DatatypeConverter.printBase64Binary(encrypted);
}
public static void main (String [] args) throws Exception
{
Security.addProvider(new BouncyCastleProvider());
String data = "Hello";
System.out.println("New Decrypted: " + RijndaelCrypt.decrypt(RijndaelCrypt.encryptNew(data)));
System.out.println("New Encryption: " + RijndaelCrypt.encryptNew(data));
}
}
PHPでは、パディングを指定しなくても余分なバイトが自動的に削除されると言っていますか?ブロックサイズで割り切れるデータを暗号化する場合にのみ、パディングを必要としないので、余分なバイトを何とか取り除く必要があります。 – Kayaman
私はPHPでPaddingを使用しておらず、余分なバイトを削除せずに動作します。PHPとJAVAの両方の暗号化結果は同じです –
本当にno paddingオプションを使用している場合はうまくいきません。どのバイトが「余分」なのかを知るためにはパディングが必要です。実際には実際に知ることなくPHPでパディングを使用している可能性が高くなります。 – Kayaman