aes并发加密Cipher not initialized 异常
解决办法:将已经实例化的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); }