javax.
Crypto. Cipher is instantiated every time, and a large number of instantiations lead to failure of cipher instantiation.
Solution: put the instantiated cipher object in the HashMap, get it from the map each time, and instantiate it when it doesn’t exist. The problem is solved
// If the key is less than 16 bits, then it will be filled. The content of this if is important
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;
}
// Initialize
Security.addProvider(new BouncyCastleProvider());
// convert to JAVA key format
key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
try {
// initialize the cipher to avoid the Cipher not initialized exception when instantiating a lot
if(cipherMap.containsKey("cipher")) {
cipher = cipherMap.get("cipher");
}else {
cipher = Cipher.getInstance(algorithmStr);
//Cipher Initialize
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);
}