유니 코드

[Android] local.properties에 민감한 정보 안전하게 보관하기 본문

오늘의 공부는?!/Android

[Android] local.properties에 민감한 정보 안전하게 보관하기

꼬물쥰 2022. 7. 12. 18:44

안드로이드 프로젝트를 진행하다보면 민감한 정보가 소스코드에 포함되는 경우가 있다

예를 들어 메일을 보낼 때 필요한 메일계정정보를 소스 코드에 그대로 포함하면 보안상의 문제가 있다

API key값도 마찬가지이다. 만약 코드에 상수값으로 선언해두었다면 Github 등에 노출될 위험이 있기 때문에

.gitignore 파일을 통해 민감한 정보가 노출되지 않도록 보관해야 한다

 

이 글에서는 local.properties 파일을 사용해 정보를 안전하게 보관하는 방법을 설명하겠다

 

local.properties에 정보 추가

local.properties 파일은 기본적으로 .gitignore 파일에 추가되어 있어서 git을 통해 추적되지 않는다

local.properties 파일에 숨기고 싶은 정보를 추가해준다

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file should *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
sdk.dir=C\:\\AndroidSDK

# GMailSender에서 사용하는 발신자 메일 계정
gmail.address = "메일주소"
gmail.passwd = "비밀번호"

 

build.gradle(app) 설정

local.properties 파일에 추가한 정보를 사용하기 위해서는 접근할 수 있도록 gradle파일에서 설정해줘야한다

local.properties 파일을 properties에 로드해주고 buildConfigField를 통해 BuildConfig에 추가해주고 프로젝트를 빌드한다

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

android {
		...
    defaultConfig {
    		...
        buildConfigField "String", "GMAIL_ADDRESS", properties["gmail.address"]
        buildConfigField "String", "GMAIL_PASSWD", properties["gmail.passwd"]
    }
}

 

BuildConfig에서 값 꺼내오기

프로젝트를 빌드하면 BuildConfig가 생성되고 아래와 같은 코드가 추가된다

/**
 * Automatically generated file. DO NOT MODIFY
 */
public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.example.project";
  public static final String BUILD_TYPE = "debug";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "1.0";

  // Field from default config.
  public static final String GMAIL_ADDRESS = "메일주소";
  // Field from default config.
  public static final String GMAIL_PASSWD = "비밀번호";
}

 

여기까지 완료하면 코드에서 BuildConfig를 통해 접근하면 된다

//변경 전
val fromEmail = "example@gmail.com"
val password = "1234567890"

//변경 후
val fromEmail = BuildConfig.GMAIL_ADDRESS
val password = BuildConfig.GMAIL_PASSWD

 

 

참고

https://yerintil.tistory.com/63

https://leveloper.tistory.com/212

Comments