@Slf4j
@Component
public class KeyEncrypt {
private final static String shaAlg = "SHA-256";
private final static String aesAlg = "AES/CBC/PKCS5Padding";
private final static String key = "MyTestCode-32Character-TestAPIKey";
private final static String iv = key.subString(0, 16);
public String encrypt(String text) {
try {
String shaKey = getShaKey(text);
return getAesKey(shaKey);
} catch (Exception e) {
throw new RuntimeException("암호화 처리중에 에러가 발생했습니다. e = {}", e.getMessage());
}
}
// SHA-256 키 만들기
private String getShaKey(String text) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(shaAlg);
md.update(text.getBytes());
return bytesToHex(md.digest());
}
// AES 키 만들기
private String getAesKey(String text) throws Exception {
Cipher cipher = Cipher.getInstance(aesAlg);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);
byte[] encodedBytes = cipher.doFinal(text.getBytes());
byte[] encrypted = Base64.getEncoder().encode(encodedBytes);
return new String(encrypted).trim();
}
private String bytesToHex(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte b : bytes) {
builder.append(String.format("%02x", b));
}
return builder.toString();
}
}
❗️ SHA 알고리즘은 해싱을 통해 암호화를 하기 때문에 복호화가 불가능 합니다
@Component
public class KeyDecrypt {
private final static String alg = "AES/CBC/PKCS5Padding";
private final static String key = "MyTestCode-32Character-TestAPIKey";
private final static String iv = key.subString(0, 16);
public String decrypt(String clientKey) {
try {
Cipher cipher = Cipher.getInstance(alg);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
byte[] decoedBytes = Base64.getDecoder().decode(clientKey.getBytes());
byte[] decrypted = cipher.doFinal(decoedBytes);
return new String(decrypted).trim();
} catch (Exception e) {
throw new RuntimeException("복호화 처리중에 에러가 발생했습니다. e = {}", e.getMessage());
}
}
}
👉🏻 docs