解決辦法:將已經實例化的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);
}
