Lumberjack iOS:如何写加密日志(Block Encryption)

Lumberjack iOS: How to write encrypted logs (Block Encryption)

我正在使用 Lumberjack 作为日志记录平台 (Objective C/Swift) 有没有办法将日志加密写入文件?

如果您可以接受可用的设备加密

在您的应用程序的 plist 中设置苹果文件系统加密并忘记这个问题:)

在此处阅读更多相关信息:
https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html

或更短的摘要(页面底部):
http://www.darthnull.org/2014/10/06/ios-encryption


工作原理:

为您的应用 ID 启用数据保护权利以保护您应用的所有文件:


替代方法:您可以在写入时为文件设置 NSFileProtection 标志。

objC 代码:

NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];
if (![[NSFileManager defaultManager] setAttributes:fileAttributes ofItemAtPath:filePath error:error]) {
    return NO;
}
return YES;

如果您想推出自己的自定义记录器

import CocoaLumberjack
import Security

public class EncryptedLogger: DDAbstractLogger {
    let key: SecKey!
    let blockSize : Int
    let padding : SecPadding
    
    init(key: SecKey!, blockSize : Int = 128, padding: SecPadding = .PKCS1) {
        self.key = key
        self.blockSize = blockSize
        self.padding = padding
    }

    convenience init(keyFilePath: String, blockSize: Int = 128, padding: SecPadding = .PKCS1) {
        //TODO: load key from file
        self.init(key: nil, blockSize: blockSize, padding: padding)
    }
    
    /**
     *  The log message method
     *
     *  @param logMessage the message (model)
     */
    public override func logMessage(logMessage: DDLogMessage!) {
        let plainText = logFormatter != nil ? logFormatter.formatLogMessage(logMessage) : logMessage.message;
        
        let plainTextData = [UInt8](plainText.utf8)
        
        var encryptedData = [UInt8](count: Int(blockSize), repeatedValue: 0)
        var encryptedDataLength = blockSize
        
        let result = SecKeyEncrypt(key, padding, plainTextData, plainTextData.count, &encryptedData, &encryptedDataLength)
        
        //TODO: write the encryptedData to a file or post it to some endpoint
        //...
    }

    @objc
    public override var loggerName: String! {
        get {
            return "\(self.dynamicType)"
        }
    }
}