[swift] Swift에서 키체인을 사용하여 데이터 손상 여부 검사하기

앱 개발 중에 데이터의 손상 여부를 검사해야 할 때가 있습니다. 이러한 경우 키체인(Keychain)을 사용하여 데이터의 무결성을 검증할 수 있습니다. 키체인은 암호화된 형태로 데이터를 안전하게 저장하는 용도로 사용되며, iOS, macOS 등 다양한 플랫폼에서 지원됩니다.

키체인 API 사용하기

Swift에서 키체인을 사용하기 위해서는 Security 프레임워크를 import 해야 합니다.

import Security

키체인에 데이터를 저장하는 방법은 다양하지만, 여기서는 kSecClassGenericPassword 타입을 사용하겠습니다. 먼저, 데이터를 키체인에 저장하는 함수를 작성해보겠습니다.

func saveDataToKeychain(data: Data, service: String, account: String) {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: service,
        kSecAttrAccount as String: account,
        kSecValueData as String: data
    ]
    
    let status = SecItemAdd(query as CFDictionary, nil)
    if status != errSecSuccess {
        print("Failed to save data to keychain. Status: \(status)")
    }
}

위의 함수는 dataserviceaccount 정보와 함께 키체인에 저장합니다. 저장에 실패한 경우 에러 메시지를 출력합니다.

데이터를 키체인에서 검색하는 함수를 작성해보겠습니다.

func fetchDataFromKeychain(service: String, account: String) -> Data? {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: service,
        kSecAttrAccount as String: account,
        kSecMatchLimit as String: kSecMatchLimitOne,
        kSecReturnData as String: true
    ]
    
    var result: CFTypeRef?
    let status = SecItemCopyMatching(query as CFDictionary, &result)
    if status == errSecSuccess {
        return result as? Data
    } else {
        print("Failed to fetch data from keychain. Status: \(status)")
        return nil
    }
}

위의 함수는 serviceaccount 정보에 해당하는 데이터를 키체인에서 검색하여 반환합니다. 검색에 실패한 경우 에러 메시지를 출력하고 nil을 반환합니다.

데이터의 손상 여부를 검사하는 함수를 작성해보겠습니다. 이 함수는 이전에 저장된 데이터와 현재 데이터를 비교하여 무결성을 검증합니다.

func checkDataIntegrity(data: Data, service: String, account: String) -> Bool {
    if let storedData = fetchDataFromKeychain(service: service, account: account) {
        return data == storedData
    }
    return false
}

위의 함수는 data와 키체인에서 검색한 이전 데이터를 비교하여 무결성 여부를 판단합니다. 데이터의 무결성이 유지되었다면 true를 반환하고, 그렇지 않다면 false를 반환합니다.

예제 사용법

let data = "Hello, World!".data(using: .utf8)!
let service = "com.example.app"
let account = "user"

saveDataToKeychain(data: data, service: service, account: account)

let isDataIntegrityVerified = checkDataIntegrity(data: data, service: service, account: account)
if isDataIntegrityVerified {
    print("Data integrity verified.")
} else {
    print("Data has been tampered with.")
}

위의 예제에서는 “Hello, World!”라는 문자열을 data로 변환하고, 이를 saveDataToKeychain 함수를 사용하여 키체인에 저장합니다. 그런 다음 checkDataIntegrity 함수를 사용하여 저장된 데이터의 무결성을 검사합니다.

결론

Swift에서 키체인을 사용하여 데이터의 손상 여부를 검사하는 방법을 살펴보았습니다. 키체인은 데이터를 안전하게 저장하고 검증하는 용도로 사용할 수 있으며, 앱의 보안 강화에 도움을 줄 수 있습니다. 추가적인 기능을 구현하려면 Apple의 Keychain Services 문서를 참조하시기 바랍니다.