Clean up exceptions, mark initialize as synchronized.

This commit is contained in:
Sutra Zhou 2018-04-30 22:33:16 +08:00
parent 2c1892a5e2
commit 1a2d9f2667
2 changed files with 8 additions and 16 deletions

View File

@ -1,9 +1,7 @@
package com.foxinmy.weixin4j.wxa; package com.foxinmy.weixin4j.wxa;
import java.security.AlgorithmParameters; import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.Key; import java.security.Key;
import java.security.NoSuchProviderException;
import java.security.Security; import java.security.Security;
import javax.crypto.Cipher; import javax.crypto.Cipher;
@ -23,12 +21,11 @@ final class AESUtils {
* AES解密 * AES解密
* *
* @param content 密文 * @param content 密文
* @param keyByte key
* @param ivByte 初始向量
* @return 明文 * @return 明文
* @throws InvalidAlgorithmParameterException
* @throws NoSuchProviderException
*/ */
static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) {
throws InvalidAlgorithmParameterException {
initialize(); initialize();
try { try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
@ -42,9 +39,11 @@ final class AESUtils {
} }
} }
private static void initialize() { private static synchronized void initialize() {
if (initialized) if (initialized) {
return; return;
}
Security.addProvider(new BouncyCastleProvider()); Security.addProvider(new BouncyCastleProvider());
initialized = true; initialized = true;
} }

View File

@ -1,7 +1,6 @@
package com.foxinmy.weixin4j.wxa; package com.foxinmy.weixin4j.wxa;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
@ -36,13 +35,7 @@ public class WXBizDataCrypt {
final byte[] aesCipher = Base64.decodeBase64(encryptedData); final byte[] aesCipher = Base64.decodeBase64(encryptedData);
final byte[] aesIV = Base64.decodeBase64(iv); final byte[] aesIV = Base64.decodeBase64(iv);
final byte[] decryptedBytes; final byte[] decryptedBytes = AESUtils.decrypt(aesCipher, aesKey, aesIV);
try {
decryptedBytes = AESUtils.decrypt(aesCipher, aesKey, aesIV);
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
}
final String decryptedText = new String(decryptedBytes, Charset.forName("UTF-8")); final String decryptedText = new String(decryptedBytes, Charset.forName("UTF-8"));
final JSONObject decrypted = JSON.parseObject(decryptedText); final JSONObject decrypted = JSON.parseObject(decryptedText);