Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
54 lines (38 sloc) 1.84 KB
#!/usr/bin/python
# Pulled from https://stackoverflow.com/a/44662262
import binascii
import plistlib
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random
from sys import exit
key_bytes = 32 # AES256
def readKey(key_file):
'Reads in 32 bytes of data from specified file'
with open(key_file, 'r') as key_data:
return key_data.read(key_bytes)
def encryptText(key, plaintext, output_file):
if not output_file.endswith('.plist'):
print 'Output file extension must end with .plist'
exit(1)
else:
assert len(key) == key_bytes # Make sure the length of the key is equal to key_bytes.
init_vector = Random.new().read(AES.block_size) # Random 16 bit initialization vector.
init_vector = int(binascii.hexlify(init_vector), 16) # Convert to integer
ctr = Counter.new(AES.block_size * 8, initial_value=init_vector)
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
plistlib.writePlist({'init_vector': init_vector, 'encoded': plistlib.Data(aes.encrypt(plaintext))}, output_file)
def decryptText(key, input_file):
if not input_file.endswith('.plist'):
print 'Input file extension must end with .plist'
exit(1)
else:
assert len(key) == key_bytes # Make sure key is key_bytes
encoded_data = plistlib.readPlist(input_file)
# Need to use the initialization vector from the encoded data to decrypt.
ctr = Counter.new(AES.block_size * 8, initial_value=encoded_data['init_vector'])
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
return aes.decrypt(encoded_data['encoded'].data) # To read data type in plist, dict['key'].data
keyData = readKey('RandomNumbers')
encryptText(key=keyData, plaintext='Hello world', output_file='encoded.plist')
decryptText(key=keyData, input_file='encoded.plist')