-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
205 lines (169 loc) · 6.68 KB
/
database.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
from peewee import *
import hashlib
import hmac
import datetime
import uuid
from Crypto import Random
from Crypto.Cipher import AES
DB_PATH = 'blog.sqlite' # in normal deployment, should be abs path
db = SqliteDatabase(DB_PATH)
class MyModel(Model):
class Meta:
database = db
class Author(MyModel):
slug = CharField(unique=True)
name = TextField()
description = TextField()
is_editor = BooleanField()
password = BlobField()
salt = BlobField()
def set_password(self, password):
self.salt = Random.new().read(AES.block_size)
self.password = hashlib.scrypt(bytes(password, 'utf-8'), salt=self.salt, n=2**12, r=8, p=8)
if not self.check_password(password):
raise ValueError('failed to trial authenticate')
self.save()
def check_password(self, password):
password = bytes(password, 'utf-8')
test_password = hashlib.scrypt(password, salt=self.salt, n=2**12, r=8, p=8)
return hmac.compare_digest(self.password, test_password)
# AES code from https://stackoverflow.com/a/20868265
def pad(s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)
def encrypt(message, key):
message = pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
def decrypt(ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return plaintext.rstrip(b"\0")
class Article(MyModel):
slug = CharField(unique=True)
title = TextField()
subtitle = TextField(null=True)
date = DateTimeField(default=datetime.datetime.now)
author = ForeignKeyField(Author, backref='articles')
listed = BooleanField(default=True)
version = UUIDField(default=uuid.uuid4)
format = CharField(default='md')
crop_at_paragraph = IntegerField(default=3)
encrypted = BooleanField()
salt = BlobField(null=True)
n_exp = IntegerField(null=True) # n=2**n_exp
r = IntegerField(null=True)
p = IntegerField(null=True)
magic_prefix = BlobField(null=True)
magic_suffix = BlobField(null=True)
content = BlobField()
def decrypt(self, password):
if not self.encrypted:
return self.content
password = bytes(password, 'utf-8')
key = hashlib.scrypt(password, salt=self.salt, n=2**self.n_exp, r=self.r, p=self.p, dklen=32)
plaintext = decrypt(self.content, key)
if plaintext.startswith(self.magic_prefix or b'') and plaintext.endswith(self.magic_suffix or b''):
return plaintext[len(self.magic_prefix) : -len(self.magic_suffix)]
else:
raise ValueError('decryption failed, check key')
def decrypt_in_place(self, password):
plaintext = self.decrypt(password)
self.encrypted = False
self.salt = None
self.n_exp = None
self.r = None
self.p = None
self.magic_prefix = None
self.magic_suffix = None
self.content = plaintext
self.save()
def encrypt_in_place(self, password, salt=None, n_exp=10, r=8, p=1, magic_prefix=b'Article content: \n\n', magic_suffix=b'\n\n=== Article content ends here'):
salt = salt or Random.new().read(64)
key = hashlib.scrypt(bytes(password, 'utf-8'), salt=salt, n=2**n_exp, r=r, p=p, dklen=32)
plaintext = self.content
ciphertext = encrypt(magic_prefix + plaintext + magic_suffix, key)
self.encrypted = True
self.content = ciphertext
self.salt = salt
self.n_exp = n_exp
self.r = r
self.p = p
self.magic_prefix = magic_prefix
self.magic_suffix = magic_suffix
# before saving, confirm that we can decrypt it
# (should never be an issue)
if plaintext != self.decrypt(password):
raise ValueError('Failed to trial decrypt content')
self.save()
class Tag(MyModel):
slug = CharField(unique=True)
class ArticleTag(MyModel):
article = ForeignKeyField(Article, backref='tags')
tag = ForeignKeyField(Tag, backref='articles')
class Meta:
primary_key = CompositeKey('article', 'tag')
class File(MyModel):
uuid = UUIDField(default=uuid.uuid4, unique=True)
filename = CharField()
mimetype = CharField()
hash = CharField(unique=True)
encrypted = BooleanField()
salt = BlobField(null=True)
n_exp = IntegerField(null=True) # n=2**n_exp
r = IntegerField(null=True)
p = IntegerField(null=True)
magic_prefix = BlobField(null=True)
magic_suffix = BlobField(null=True)
content = BlobField()
def set_content(self, content):
self.hash = hashlib.sha3_512(content).hexdigest()
self.encrypted = False
self.salt = None
self.n_exp = None
self.r = None
self.p = None
self.magic_prefix = None
self.magic_suffix = None
self.content = content
def decrypt(self, password):
if not self.encrypted:
return self.content
password = bytes(password, 'utf-8')
key = hashlib.scrypt(password, salt=self.salt, n=2**self.n_exp, r=self.r, p=self.p, dklen=32)
plaintext = decrypt(self.content, key)
if plaintext.startswith(self.magic_prefix or b'') and plaintext.endswith(self.magic_suffix or b''):
return plaintext[len(self.magic_prefix) : -len(self.magic_suffix)]
else:
raise ValueError('decryption failed, check key')
def decrypt_in_place(self, password):
plaintext = self.decrypt(password)
self.encrypted = False
self.salt = None
self.n_exp = None
self.r = None
self.p = None
self.magic_prefix = None
self.magic_suffix = None
self.content = plaintext
def encrypt_in_place(self, password, salt=None, n_exp=10, r=8, p=1, magic_prefix=b'File content: \n\n', magic_suffix=b'\n\n=== File content ends here'):
salt = salt or Random.new().read(64)
key = hashlib.scrypt(bytes(password, 'utf-8'), salt=salt, n=2**n_exp, r=r, p=p, dklen=32)
plaintext = self.content
ciphertext = encrypt(magic_prefix + plaintext + magic_suffix, key)
self.encrypted = True
self.content = ciphertext
self.salt = salt
self.n_exp = n_exp
self.r = r
self.p = p
self.magic_prefix = magic_prefix
self.magic_suffix = magic_suffix
# before saving, confirm that we can decrypt it
# (should never be an issue)
if plaintext != self.decrypt(password):
raise ValueError('Failed to trial decrypt content')
db.connect()
db.create_tables([Author, Article, Tag, ArticleTag, File])
db.close()