[swift] Swift으로 디렉토리 생성 후 파일을 암호화하기

Swift는 다양한 운영 체제에서 파일 시스템에 액세스할 수 있는 기능을 제공합니다. 디렉토리를 생성하고 파일을 암호화하는 방법을 알아보겠습니다.

디렉토리 생성하기

디렉토리를 생성하려면 FileManager 클래스를 사용합니다. 아래의 코드는 FileManager를 사용하여 새로운 디렉토리를 생성하는 방법을 보여줍니다.

import Foundation

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let newDirectoryURL = documentsURL.appendingPathComponent("MyNewDirectory")

do {
    try fileManager.createDirectory(at: newDirectoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
    print(error)
}

파일 암호화하기

파일을 암호화하려면 Data를 사용하여 파일 내용을 읽은 후, 해당 데이터를 암호화합니다.

아래의 예제는 파일을 암호화하는 방법을 보여줍니다.

import Foundation

func encryptFile(at filePath: String, key: Data) {
    do {
        var data = try Data(contentsOf: URL(fileURLWithPath: filePath))
        // TODO: Use the key to encrypt the data
        // ...
        
        // Write the encrypted data back to the file
        try data.write(to: URL(fileURLWithPath: filePath), options: .completeFileProtection)
    } catch {
        print(error)
    }
}

위 코드에서 key는 암호화에 사용될 키로 대체되어야 합니다.

위의 코드를 활용하여 Swift에서 디렉토리를 생성하고 파일을 암호화하는 방법을 학습할 수 있습니다.