-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutilities.py
117 lines (90 loc) · 3.26 KB
/
utilities.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
from __future__ import print_function
import sys
import time
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
import hashlib
import hmac
import os
import datetime
from pytz import timezone, utc
def eprint(*args, **kwargs): # from https://stackoverflow.com/a/14981125
print(*args, file=sys.stderr, **kwargs)
def getTimestamp():
return int(time.time())
def getTimestampMs():
return int(round(time.time() * 1000))
def getTimeString(timezoneStr):
tz = timezone(timezoneStr)
fmt = '%Y-%m-%d %H:%M:%S'
tm = datetime.datetime.now(tz)
return tm.strftime(fmt)
def mergeDicts(x, y): # from https://stackoverflow.com/a/26853961
if x is None and y is None:
return
z = (y if x is None else x).copy()
if x is not None and y is not None:
z.update(y)
return z
def getAttr(obj, key, alt=None):
return obj[key] if isinstance(obj, dict) and key in obj else alt
def filterNone(obj):
if isinstance(obj, dict):
return dict((k, filterNone(v)) for k, v in obj.iteritems() if v is not None)
elif isinstance(obj, list):
return [filterNone(entry) for entry in obj]
else:
return obj
def getNumValidKeys(obj):
return len(filter(lambda x: obj[x] is not None, list(obj.keys())))
def encodeUTF8(s):
if not isinstance(s, str):
s = s.encode("utf-8")
return s
def ceil(n): # from https://stackoverflow.com/a/32559239
res = int(n)
return res if res == n or n < 0 else res+1
def floor(n):
res = int(n)
return res if res == 0 or n >= 0 else res-1
def HmacSha256(key, sign):
return hmac.new(key, sign, hashlib.sha256).digest()
def HKDF(key, length, appInfo=b""): # implements RFC 5869, some parts from https://github.com/MirkoDziadzka/pyhkdf
key = HmacSha256(b"\0"*32, key)
keyStream = b""
keyBlock = b""
blockIndex = 1
while len(keyStream) < length:
keyBlock = hmac.new(key, msg=keyBlock+appInfo+blockIndex.to_bytes(1, byteorder='big'), digestmod=hashlib.sha256).digest()
blockIndex += 1
keyStream += keyBlock
return keyStream[:length]
def AESPad(s):
bs = AES.block_size
return s + (bs - len(s) % bs) * chr(bs - len(s) % bs)
def to_bytes(n, length, endianess='big'):
h = '%x' % n
s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
return s if endianess == 'big' else s[::-1]
def AESUnpad(s):
return s[:-ord(s[len(s)-1:])]
def AESEncrypt(key, plaintext): # like "AESPad"/"AESUnpad" from https://stackoverflow.com/a/21928790
plaintext = AESPad(plaintext)
iv = os.urandom(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(plaintext)
def WhatsAppEncrypt(encKey, macKey, plaintext):
enc = AESEncrypt(encKey, plaintext)
return HmacSha256(macKey, enc) + enc # this may need padding to 64 byte boundary
def AESDecrypt(key, ciphertext): # from https://stackoverflow.com/a/20868265
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return AESUnpad(plaintext)
def customTime(*args):
utc_dt = utc.localize(datetime.datetime.utcnow())
my_tz = timezone("Asia/Kolkata")
converted = utc_dt.astimezone(my_tz)
return converted.timetuple()
def convertToSeconds(tm):
return tm.second + tm.minute*60 + tm.hour*60*60