Skip to content

Instantly share code, notes, and snippets.

@NSEGeorge
Created April 20, 2020 14:03
Show Gist options
  • Save NSEGeorge/be40e61c8e559fd3949c54b4c6f058ce to your computer and use it in GitHub Desktop.
Save NSEGeorge/be40e61c8e559fd3949c54b4c6f058ce to your computer and use it in GitHub Desktop.
public struct MLEncoderTool {
// The first argument is the file name
// The second argument is key
private let arguments: [String]
private let cryptor: MLCryptor
public init(
arguments: [String] = CommandLine.arguments,
cryptor: MLCryptor = MLCryptor.cryptoKit
) {
self.arguments = arguments
self.cryptor = cryptor
}
public func run() throws {
if arguments.count == 1 {
throw Error.missingAllArguments
}
if arguments.count == 2 {
throw Error.missingKey
}
try encryptFile()
}
func encryptFile() throws {
let fileName = arguments[1]
let key = arguments[2]
let currentPath = FileManager.default.currentDirectoryPath
let fullPath = currentPath + "/" + fileName
guard let data = FileManager.default.contents(atPath: fullPath) else {
throw Error.noFile
}
guard let encryptedData = try cryptor.encrypt(data: data, withPassword: key) else {
throw Error.undefinedError
}
let destinationPath = currentPath + "/" + fileName + ".enc"
let destinationURL = URL(fileURLWithPath: destinationPath)
try encryptedData.write(to: destinationURL)
print("The file was encrypted successfully.")
}
func decryptFile() throws {
let fileName = arguments[1]
let key = arguments[2]
let currentPath = FileManager.default.currentDirectoryPath
let fullPath = currentPath + "/" + fileName
guard let data = FileManager.default.contents(atPath: fullPath) else {
throw Error.noFile
}
guard let encryptedData = try cryptor.decrypt(data: data, withPassword: key) else {
throw Error.undefinedError
}
let destinationPath = currentPath + "/" + (fileName as NSString).deletingPathExtension
let destionationURL = URL(fileURLWithPath: destinationPath)
try encryptedData.write(to: destionationURL)
print("The file was decrypted successfully.")
}
}
public extension MLEncoderTool {
enum Error: Swift.Error {
case missingAllArguments
case missingKey
case noFile
case undefinedError
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment