smartproc-be/src/main/java/com/iconplus/smartproc/util/EncryptDecryptUtils.java
2023-05-28 17:36:28 +07:00

53 lines
2.4 KiB
Java

package com.iconplus.smartproc.util;
import com.iconplus.smartproc.exception.TechnicalException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.util.Base64;
public class EncryptDecryptUtils {
private static final Logger log = LogManager.getLogger(EncryptDecryptUtils.class);
private EncryptDecryptUtils() {
}
public static String decrypt(String data, String base64PrivateKey) {
return decryptChipper(Base64.getDecoder().decode(data.getBytes()), RSAUtil.getPrivateKey(base64PrivateKey));
}
private static String decryptChipper(byte[] data, PrivateKey privateKey) {
var result = "";
try {
var cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(2, privateKey);
result = new String(cipher.doFinal(data));
} catch (NoSuchAlgorithmException var3) {
log.error("NoSuchAlgorithmException : {}", var3.getMessage());
throw new TechnicalException(Constants.ERR_CODE_80000, Constants.N0_SUCH_ALGORITHM_EXCEPTION + var3.getMessage());
} catch (NoSuchPaddingException var4) {
log.error("NoSuchPaddingException : {}", var4.getMessage());
throw new TechnicalException(Constants.ERR_CODE_80000, Constants.N0_SUCH_PADDING_EXCEPTION + var4.getMessage());
} catch (InvalidKeyException var5) {
log.error("InvalidKeyException : {}", var5.getMessage());
throw new TechnicalException(Constants.ERR_CODE_80000, Constants.INVALID_KEY_EXCEPTION + var5.getMessage());
} catch (IllegalBlockSizeException var6) {
log.error("IllegalBlockSizeException : {}", var6.getMessage());
throw new TechnicalException(Constants.ERR_CODE_80000, Constants.ILEGAL_BLOCK_SIZE_EXCEPTION + var6.getMessage());
} catch (BadPaddingException var7) {
log.error("BadPaddingException : {}", var7.getMessage());
throw new TechnicalException(Constants.ERR_CODE_80000, Constants.BAD_PADDING_EXCEPTION + var7.getMessage());
}
return result;
}
}