[swift] Swift에서의 암호화 개념

암호화는 개인정보를 보호하고 데이터의 안전성을 확보하기 위해 중요한 개념입니다. Swift에서는 암호화를 적용하여 데이터를 안전하게 저장하고 전송할 수 있습니다. 이번 블로그 포스트에서는 Swift에서의 암호화 개념에 대해 알아보도록 하겠습니다.

암호화 종류

Swift에서 사용할 수 있는 주요한 암호화 종류는 다음과 같습니다.

  1. 대칭키 암호화 (Symmetric-key encryption)
  2. 비대칭키 암호화 (Asymmetric-key encryption)
  3. 해시 함수 (Hash function)

대칭키 암호화

대칭키 암호화는 암호화와 복호화에 동일한 키를 사용하는 방식입니다. 이 방식은 암호화 및 복호화 과정에 빠른 속도를 제공하지만, 키의 안전한 공유가 필요합니다. Swift에서는 CommonCrypto 프레임워크를 활용하여 대칭키 암호화를 구현할 수 있습니다.

import CommonCrypto

// 키 생성
let key = "SuperSecretKey123".data(using: .utf8)!

// 암호화
let plaintext = "Hello, World!".data(using: .utf8)!
var ciphertext = Data(count: plaintext.count + kCCBlockSizeAES128)

_ = ciphertext.withUnsafeMutableBytes { ciphertextPtr in
    plaintext.withUnsafeBytes { plaintextPtr in
        key.withUnsafeBytes { keyPtr in
            CCCrypt(
                CCOperation(kCCEncrypt),
                CCAlgorithm(kCCAlgorithmAES),
                CCOptions(kCCOptionPKCS7Padding),
                keyPtr, key.count,
                nil,
                plaintextPtr, plaintext.count,
                ciphertextPtr, ciphertext.count,
                nil
            )
        }
    }
}

// 복호화
var decrypted = Data(count: ciphertext.count)
_ = decrypted.withUnsafeMutableBytes { decryptedPtr in
    ciphertext.withUnsafeBytes { ciphertextPtr in
        key.withUnsafeBytes { keyPtr in
            CCCrypt(
                CCOperation(kCCDecrypt),
                CCAlgorithm(kCCAlgorithmAES),
                CCOptions(kCCOptionPKCS7Padding),
                keyPtr, key.count,
                nil,
                ciphertextPtr, ciphertext.count,
                decryptedPtr, decrypted.count,
                nil
            )
        }
    }
}

let decryptedString = String(data: decrypted, encoding: .utf8)
print(decryptedString) // "Hello, World!"

비대칭키 암호화

비대칭키 암호화는 암호화와 복호화에 각각 다른 키를 사용하는 방식입니다. 이 방식은 보안성이 높으며, 공개 키와 개인 키를 생성하여 사용합니다. Swift에서는 Security 프레임워크의 SecKey 클래스를 활용하여 비대칭키 암호화를 구현할 수 있습니다.

import Security

// 공개 키 및 개인 키 생성
var publicKey, privateKey: SecKey?

let privateKeyAttributes: [CFString: Any] = [
    kSecAttrIsPermanent: true
]

let keyPairAttributes: [CFString: Any] = [
    kSecAttrType: kSecAttrKeyTypeRSA,
    kSecAttrKeySizeInBits: 2048,
    kSecPrivateKeyAttrs: privateKeyAttributes
]

SecKeyGeneratePair(keyPairAttributes as CFDictionary, &publicKey, &privateKey)

// 암호화
let plaintext = "Hello, World!".data(using: .utf8)!

guard let publicKey = publicKey else {
    fatalError("Failed to retrieve public key")
}

let encryptedData = SecKeyCreateEncryptedData(publicKey,
                                              .rsaEncryptionPKCS1,
                                              plaintext as CFData,
                                              nil)!

// 복호화
guard let privateKey = privateKey else {
    fatalError("Failed to retrieve private key")
}

var error: Unmanaged<CFError>?
let decryptedData = SecKeyCreateDecryptedData(privateKey,
                                              .rsaEncryptionPKCS1,
                                              encryptedData as CFData,
                                              &error)!

let decryptedString = String(data: decryptedData as Data, encoding: .utf8)
print(decryptedString) // "Hello, World!"

해시 함수

해시 함수는 임의의 길이의 데이터를 고정된 길이의 데이터로 매핑하는 함수입니다. 이 함수는 단방향 함수이므로, 해시 값으로부터 원본 데이터를 복원할 수 없습니다. Swift에서는 CryptoKit 프레임워크를 활용하여 해시 함수를 구현할 수 있습니다.

import CryptoKit

let data = Data("Hello, World!".utf8)
let digest = SHA256.hash(data: data)
let hexString = digest.compactMap { String(format: "%02x", $0) }.joined()

print(hexString) // "594f8e3ee03b56d8a7c0a3ec5021ea24948d967176548249cb4fa3da982ca9d0"

결론

Swift에서는 대칭키 암호화, 비대칭키 암호화, 해시 함수 등을 활용하여 데이터를 안전하게 처리할 수 있습니다. 이러한 암호화 방식을 적절히 활용하여 개인정보 보호와 데이터의 안전성을 유지하는 것이 중요합니다. 적절한 암호화 기법을 선택하고 구현하는 데 주의를 기울이세요.