aes並發加密Cipher not initialized 異常


javax. crypto.Cipher 每次都要實例化,大量的實例化導致 Cipher 實例化失敗。
解決辦法:將已經實例化的Cipher對象,放在hashmap中,每次實例化的時候從MAP 獲取,不存在的時候再進行實例化,問題解決
        // 如果密鑰不足16位,那么就補足.  這個if 中的內容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 轉化成JAVA的密鑰格式
        key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        try {
            // 初始化cipher 避免大量實例化時候發生Cipher not initialized 異常
            if(cipherMap.containsKey("cipher")) {
                cipher = cipherMap.get("cipher");
            }else {
                cipher = Cipher.getInstance(algorithmStr);
                //Cipher初始化
                cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv.getBytes("utf-8")));
                cipherMap.put("cipher", cipher);
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(),e);
        } catch (NoSuchPaddingException e) {
            log.error(e.getMessage(),e);
        } catch (InvalidKeyException e) {
            log.error(e.getMessage(),e);
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage(),e);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(),e);
        }

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM