猿问

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 但看来我一定做错了什么。我缺少什么?

简单的概念验证:

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())];

        }

    }

}


慕姐4208626
浏览 74回答 1
1回答

qq_花开花谢_0

你的问题是这一行:byte[] opbytes = new byte[cipher.getOutputSize(PLAINTEXT.length())];UTF-8 runes 中字符串的长度并不总是与底层字节数组的长度相同。input您应该使用此处的长度,而不是PLAINTEXT.
随时随地看视频慕课网APP

相关分类

Java
我要回答