I've got a python script with logging. Now I want to encrypt log with AES using pycrypto.
import logging
import base64
from Crypto.Cipher import AES
aes = AES.new(cryptoKey)
logging.basicConfig(filename='example.log',level=logging.DEBUG) # file name, not custom file
logging.info('text')
I want to use base64.b64encode(aes.encrypt('#logging text#'))
before write it to log . What is a most estate way to do it?
There's a bit more to encryption than mere forwarding of data. I would suggest writing your own log formatter and setting it as a root formatter - that way no matter where you log from in your app, even parts not controlled by your code, it will always go through a layer of encryption. So, something like:
Then you can use it wherever you can change the logging formatter, i.e.:
You can of course encrypt levels, timestamps, pretty much anything from the
logging.LogRecord
, and you can output whatever format you prefer. When the time comes to read your logs, you just need to do the reverse - see an example in this answer.UPDATE: As per request, here's how to do the 'reverse' (i.e. decrypt the encrypted logs). First, lets create a few log entries for testing (continuing with the previous):
Provided that the format remained the same (
[%(levelname)s] %(message)s
), this will result in a log like (of course, it will always be different due to the random IV):To create a reader for such a log (file) we need to be aware of the format so we can differentiate encrypted from non-encrypted data. In this case, separating the parts is easy - each log entry is on a new line, the levels are not encrypted and the actual encrypted data is always separated by a whitespace from the actual log level. So, to put all that together we might construct something like:
And then you can use it as a regular generator to decrypt your logs, e.g.:
Or if you've set your log to stream to a file, you can directly decrypt such file as: