我遵循了一些示例,當(dāng)嘗試實(shí)現(xiàn)AES/GCM/NoPadding此處引用時(shí): https: //www.strongauth.com/samplecode/GCM.java我無(wú)法加密任何包含特殊字符(即?)的文本。最終它在 doFinal 內(nèi)部失敗了, javax.crypto.ShortBufferException: Output buffer must be (at least) 30 bytes long 但看來(lái)我一定做錯(cuò)了什么。我缺少什么?簡(jiǎn)單的概念驗(yàn)證: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())]; } }}
1 回答

qq_花開(kāi)花謝_0
TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
你的問(wèn)題是這一行:
byte[] opbytes = new byte[cipher.getOutputSize(PLAINTEXT.length())];
UTF-8 runes 中字符串的長(zhǎng)度并不總是與底層字節(jié)數(shù)組的長(zhǎng)度相同。input
您應(yīng)該使用此處的長(zhǎng)度,而不是PLAINTEXT
.
添加回答
舉報(bào)
0/150
提交
取消