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