亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java AES/GCM/NoPadding 加密因特殊字符而失敗

Java AES/GCM/NoPadding 加密因特殊字符而失敗

慕姐4208626 2024-01-25 10:46:19
我遵循了一些示例,當嘗試實現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())];        }    }}
查看完整描述

1 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

你的問題是這一行:

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

UTF-8 runes 中字符串的長度并不總是與底層字節數組的長度相同。input您應該使用此處的長度,而不是PLAINTEXT.


查看完整回答
反對 回復 2024-01-25
  • 1 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號