JavaのAES / GCM / NoPadding暗号化は特殊文字で失敗します

グレッグ:

私はいくつかの例を踏襲して実装しようとしたときにきたAES/GCM/NoPaddingここで参照:https://www.strongauth.com/samplecode/GCM.java私は特殊文字(つまりが含まれている任意のテキストを暗号化することができませんø)。

最終的にそれはとのdoFinalの内側に失敗したjavax.crypto.ShortBufferException: Output buffer must be (at least) 30 bytes longが、私は何かを間違ってやっている必要がありますように思えます。私は何をしないのですか?

シンプルなPOC:

public class Example {

    private static final String CIPHER_TRANSFORM = "AES/GCM/NoPadding";

    public static void main(String[] args) {

        String key = generateKey("AES", 256, "seed");
        encryptText("text containing a ø character", key, "TOKENTOKENTOKENTOKEN", "AES");
    }

    private static String generateKey(String alg, int size, String seed) {

        try {
            SecureRandom securerandom = SecureRandom.getInstance("SHA1PRNG");
            securerandom.setSeed(seed.getBytes("UTF-8"));
            KeyGenerator kg = KeyGenerator.getInstance(alg);
            kg.init(size, securerandom);
            SecretKey sk = kg.generateKey();
            return new String(Base64.getEncoder().encode(sk.getEncoded()), "UTF-8");
        }
        catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
            System.err.println(ex);
        }
        return null;
    }

    private static String encryptText(String PLAINTEXT, String PLAINTEXTKEY, String TOKEN, String alg) {

        try {
            // Create SecretKey & Cipher
            SecretKeySpec sks = new SecretKeySpec(Base64.getDecoder().decode(PLAINTEXTKEY), alg);
            Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORM);

            // Setup byte arrays
            byte[] input = PLAINTEXT.getBytes("UTF-8");
            byte[] tkb = TOKEN.getBytes("UTF-8");
            byte[] iv = new byte[12];
            System.arraycopy(tkb, 4, iv, 0, 12);
            cipher.init(Cipher.ENCRYPT_MODE, sks, new GCMParameterSpec(128, iv));
            cipher.updateAAD(tkb);
            byte[] opbytes = new byte[cipher.getOutputSize(PLAINTEXT.length())];

            // Perform crypto
            int ctlen = cipher.update(input, 0, input.length, opbytes);
            ctlen += cipher.doFinal(opbytes, ctlen);
            byte[] output = new byte[ctlen];
            System.arraycopy(opbytes, 0, output, 0, ctlen);
            return new String(Base64.getEncoder().encode(output), "UTF-8");

        }
        catch (InvalidAlgorithmParameterException | UnsupportedEncodingException |
            IllegalBlockSizeException | BadPaddingException | InvalidKeyException |
            NoSuchAlgorithmException | NoSuchPaddingException | ShortBufferException ex) {
            System.err.println(ex);
        }
        return null;
    }
}
ルークジョシュア・パーク:

あなたの問題は、この行です:

byte[] opbytes = new byte[cipher.getOutputSize(PLAINTEXT.length())];

UTF-8ルーン文字の文字列の長さが常に根底にあるバイト配列の長さと同じではありません。あなたはの長さ使用する必要がありinput、ここにはありませんPLAINTEXT

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=334046&siteId=1