1"""fontTools.misc.eexec.py -- Module implementing the eexec and
2charstring encryption algorithm as used by PostScript Type 1 fonts.
3"""
4
5from __future__ import print_function, division, absolute_import
6from fontTools.misc.py23 import *
7
8def _decryptChar(cipher, R):
9	cipher = byteord(cipher)
10	plain = ( (cipher ^ (R>>8)) ) & 0xFF
11	R = ( (cipher + R) * 52845 + 22719 ) & 0xFFFF
12	return bytechr(plain), R
13
14def _encryptChar(plain, R):
15	plain = byteord(plain)
16	cipher = ( (plain ^ (R>>8)) ) & 0xFF
17	R = ( (cipher + R) * 52845 + 22719 ) & 0xFFFF
18	return bytechr(cipher), R
19
20
21def decrypt(cipherstring, R):
22	plainList = []
23	for cipher in cipherstring:
24		plain, R = _decryptChar(cipher, R)
25		plainList.append(plain)
26	plainstring = strjoin(plainList)
27	return plainstring, int(R)
28
29def encrypt(plainstring, R):
30	cipherList = []
31	for plain in plainstring:
32		cipher, R = _encryptChar(plain, R)
33		cipherList.append(cipher)
34	cipherstring = strjoin(cipherList)
35	return cipherstring, int(R)
36
37
38def hexString(s):
39	import binascii
40	return binascii.hexlify(s)
41
42def deHexString(h):
43	import binascii
44	h = strjoin(h.split())
45	return binascii.unhexlify(h)
46
47
48def _test():
49	testStr = "\0\0asdadads asds\265"
50	print(decrypt, decrypt(testStr, 12321))
51	print(encrypt, encrypt(testStr, 12321))
52
53
54if __name__ == "__main__":
55	_test()
56