본문 바로가기
개발/java,spring,springboot

jpa Converter를 이용한 암복호화

by 개발자종혁 2021. 3. 30.
728x90

1. converter/ model 설정

1. EncryptConverter.java

....
import org.springframework.util.StringUtils;
import javax.persistence.AttributeConverter;

public abstract class EncryptConverter implements AttributeConverter<String, String> {
    private final String encryptKey; // 암호화 컬럼
    private final boolean oneWayEncrypt; // 단방향 암호화 여부


    public EncryptConverter(String encryptKey) {
        this(encryptKey, false);
    }

    public EncryptConverter(String encryptKey, boolean oneWayEncrypt) {
        this.encryptKey = encryptKey;
        this.oneWayEncrypt = oneWayEncrypt;
    }

    @Override
    public String convertToDatabaseColumn(String data) {
        if (StringUtils.isEmpty(data)) { return null; }
        return EncryptModule.encrypt(encryptKey, data);
    }

    @Override
    public String convertToEntityAttribute(String dbData) {
        if (StringUtils.isEmpty(dbData)) { return null; }
        return oneWayEncrypt ? dbData : EncryptModule.decrypt(encryptKey, dbData);
    }
}

2. AccountNoEncryptConverter.java ( converter abstract class 구현)


public class AccountNoEncryptConverter extends EncryptConverter {
    public AccountNoEncryptConverter() {
        super("account_no");
    }
}

3. EncryptModule.java ( 암호화 모듈 - 원하는대로 제작)


@Component
public class EncryptModule {

    public static String encrypt(String key, String value) {

        // key, value를 이용해 암호화
        ....
        return result;
    }

    public static String decrypt(String key, String value) {
        String result = null;
        // key, value를 이용해 복호화
        ....
        return result;
    }
}

4. TestEntity.java - converter 적용(@Convert를 이용해 적용)

import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.GeneratedValue;

@Entity
@Table(name = "TEST_ENTITY")
public class TestEntity{
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name="ID", length = 50)
    private String id;

    @Convert(converter = AccountNoEncryptConverter.class)
    @Column(name = "ACCOUNT_NO")
    private String accountNo;

}

입력시 테스트 결과

DB 입력 결과

728x90

댓글