0

BouncyCastle API for Java を使用した Rijndael 暗号化の実装に問題があります。

OutputLengthException実行すると次のようになりcipher.doFinal(inputTextBytes, intOutOff);ます:

org.bouncycastle.crypto.OutputLengthException: 出力バッファが短すぎます

メソッドを実行するためにその整数を生成する方法を完全には理解していませんdoFinal()

これが私が試したことです:

public class RijndaelAndRFC2899Implementation {

    final static String WORD = "763059";
    final static String PASSWORD = "515t3ma5m15B4d35";
    final static byte[] SALT = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
    final static int KEY_SIZE = 256;
    final static int BLOCK_SIZE = 128;
    final static int ITERATIONS = 1000;

    public static void main(String[] args) throws Exception {
        BufferedBlockCipher cipher = getCipher(PASSWORD, true);
        byte[] inputText = WORD.getBytes("UTF-8");
        byte asd[] = new byte[cipher.getOutputSize(inputText.length)];
        int l = cipher.processBytes(inputText, 0, inputText.length, asd, 0);
        int n = cipher.doFinal(inputText, l); //<---HERE PRODUCES OutputLengthException
    }

    private static BufferedBlockCipher getCipher(String password, boolean encrypt) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes("UTF-8"));
        byte[] newPassword = md.digest();

        PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator();
        generator.init(newPassword, SALT, ITERATIONS);

        ParametersWithIV iv = ((ParametersWithIV) generator.generateDerivedParameters(KEY_SIZE, BLOCK_SIZE));

        RijndaelEngine engine = new RijndaelEngine();
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));   
        cipher.init(encrypt, iv);

        return cipher;
    }

}

私が間違っていることを理解することで私を助けてくれますか?

4

1 に答える 1

2

への呼び出しにdoFinal()は、処理していた入力ではなく、最初の引数として出力配列が必要です。

public static void main(String[] args) throws Exception {
    BufferedBlockCipher cipher = getCipher(PASSWORD, true);
    byte[] inputText = WORD.getBytes("UTF-8");
    byte asd[] = new byte[cipher.getOutputSize(inputText.length)];
    int l = cipher.processBytes(inputText, 0, inputText.length, asd, 0);
    int n = cipher.doFinal(asd, l); // <--- Change to asd
}

(残りの実装はまだ検証していません!)

于 2019-03-28T16:40:54.547 に答える