forked from Gig-o-Matic/GO2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cryptoutil.py
87 lines (57 loc) · 1.92 KB
/
cryptoutil.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
"""
crypto utils for Gig-o-Matic 2
Aaron Oppenheimer
4 March 2016
"""
from google.appengine.ext import ndb
from requestmodel import *
import webapp2_extras.appengine.auth.models
import webapp2
import crypto_db
import member
from Crypto.Cipher import AES
import binascii
# Utilities for encrypting stuff
def encrypt_string(the_string):
key = crypto_db.get_cryptokey()
encobj = AES.new(key, AES.MODE_ECB)
# pad out the string to a multiple of 16
x = 16-(len(the_string) % 16)
if x < 16:
the_string_pad = '{: <{}}'.format(the_string,len(the_string)+x)
else:
the_string_pad = the_string
ciphertext = encobj.encrypt(the_string_pad)
# Resulting ciphertext in hex
return ciphertext.encode('hex')
def decrypt_string(the_string):
key = crypto_db.get_cryptokey()
ciphertext = binascii.unhexlify(the_string)
decobj = AES.new(key, AES.MODE_ECB)
plaintext = decobj.decrypt(ciphertext)
# Resulting plaintext
return plaintext
# handler function for crypto key admin
class AdminPage(BaseHandler):
""" Page for cryptokey administration """
@user_required
def get(self):
if member.member_is_superuser(self.user):
self._make_page(the_user=self.user)
else:
return self.redirect('/')
def _make_page(self,the_user):
template_args = {
'current' : crypto_db.get_cryptokey()
}
self.render_template('crypto_admin.html', template_args)
@user_required
def post(self):
the_cryptokey=self.request.get('cryptokey_content','')
# pad out the string to 32 characters
the_cryptokey = '{:_<32}'.format(the_cryptokey)
crypto_db.set_cryptokey(the_cryptokey)
# testing
str1=encrypt_string('boom!!!')
str2=decrypt_string(str1)
self.redirect(self.uri_for('crypto_admin'))