Ilan Levy Ilan Levy - 2 months ago 24
iOS Question

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

I'm using Lumberjack as logging platform (Objective C/Swift)
Is there any way to write the logs to file as encrypted?


  • If yes, then any example would be useful

  • Also, how to read the encrypted logs afterwards

  • Are there different type of encryption for intensive logging? I heard about Block Encryption


Answer

if you want to roll your own custom logger

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)"
        }
    }
}