프로젝트/파이널
고객 데이터_비밀번호 암호화하기
케잉
2024. 2. 21. 01:57
aes256 암호화 복호화하는 코드
package com.example.vet.config.aes;
import org.apache.commons.codec.binary.Base64;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.encrypt.BytesEncryptor;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.keygen.KeyGenerators;
@Configuration
public class AES256Config {
private static final String SECRET_KEY = "@@$@$%AFSFFGCXBBCBB";
private static final String SALT = KeyGenerators.string().generateKey();
public String encrypt(String str) {
BytesEncryptor encryptor = Encryptors.standard(SECRET_KEY, SALT);
byte[] encryptedBytes = encryptor.encrypt(str.getBytes());
return Base64.encodeBase64String(encryptedBytes);
}
public String decrypt(String encryptedString) {
BytesEncryptor decryptor = Encryptors.standard(SECRET_KEY, SALT);
byte[] encryptedBytes = Base64.decodeBase64(encryptedString);
byte[] decryptedBytes = decryptor.decrypt(encryptedBytes);
return new String(decryptedBytes);
}
}
SECRET_KEY
: 암호화 및 복호화에 사용되는 키
반드시 안전한 임의의 값으로 설정해야 한다
또한 SALT는 암호화에 사용되는 추가적인 랜덤 값
이 값은 보안성을 높이기 위해 사용
이 코드는 Spring Security의 Encryptors 클래스를 사용하여 AES256를 구현합니다.
암호화된 문자열은 Base64로 인코딩되어 출력됩니다.
gradle에서 사용시 아래 코드 추가
dependencies {
implementation 'commons-codec:commons-codec:1.15'
}