본문 바로가기
Spring

데이터 암호화를 위한 JPA Attribute Converter

by jayden-lee 2019. 6. 10.
728x90

User 클래스에서 juminNumber 속성 값을 테이블에 저장할 때 암호화하는 예제입니다.

User Entity 생성

@Entity
@Table(name = "USER")
@DynamicInsert
@DynamicUpdate
@Getter
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "NAME", length = 50, nullable = false)
    private String name;

    @Column(name = "JUMIN_NUMBER", length = 100, nullable = false)
    @Convert(converter = StringCryptoConverter.class)
    private String juminNumber;

    ...

}

StringCryptoConverter 생성

@Convert
public class StringCryptoConverter implements AttributeConverter<String, String> {

    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final byte[] KEY = "lelecoder".getBytes();

    @Override
    public String convertToDatabaseColumn(String attribute) {
        Key key = new SecretKeySpec(KEY, "AES");
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return new String(Base64.getEncoder().encode(cipher.doFinal(attribute.getBytes())));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String convertToEntityAttribute(String dbData) {
        Key key = new SecretKeySpec(KEY, "AES");
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(Base64.getDecoder().decode(dbData)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

참고자료

댓글