- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsqlcrypt.py
More file actions
Latest commit
226 lines (157 loc) · 7.26 KB
/
Copy pathsqlcrypt.py
File metadata and controls
226 lines (157 loc) · 7.26 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
importos
importapsw
fromCrypto.CipherimportAES
fromCrypto.Protocol.KDFimportscrypt
fromCrypto.HashimportHMAC, SHA256
# PASSWORD SALT (16)
HEADER_SIZE=16
# IV (16) | MAC (32) | CIPHERTEXT
BLOCK_HEADER_SIZE=16+32
BLOCK_SIZE=4096+BLOCK_HEADER_SIZE
def_parse_header(file):
file.seek(0)
password_salt=file.read(HEADER_SIZE)
returnpassword_salt
def_decrypt(key: bytes, data: bytes) ->bytearray:
assertlen(key) ==32, "Must decrypt in AES-256"
assertlen(data) ==BLOCK_SIZE
iv=data[:16]
mac=data[16:48]
ciphertext=data[BLOCK_HEADER_SIZE:]
plaintext=AES.new(key, AES.MODE_CBC, iv=iv).decrypt(ciphertext)
ifmac!=HMAC.new(key, msg=plaintext, digestmod=SHA256).digest():
returnb""
assertlen(plaintext) ==BLOCK_SIZE-BLOCK_HEADER_SIZE
returnbytearray(plaintext)
def_encrypt(key: bytes, plaintext: bytes) ->bytearray:
assertlen(key) ==32, "Must encrypt in AES-256"
assertlen(plaintext) ==BLOCK_SIZE-BLOCK_HEADER_SIZE
iv=os.urandom(16)
mac=HMAC.new(key, msg=plaintext, digestmod=SHA256).digest()
ciphertext=AES.new(key, AES.MODE_CBC, iv=iv).encrypt(plaintext)
assertlen(ciphertext) ==BLOCK_SIZE-BLOCK_HEADER_SIZE
assertlen(iv+mac) ==BLOCK_HEADER_SIZE
returnbytearray(iv+mac+ciphertext)
def_derive_password(password: str, salt: bytes) ->bytes:
"""Generate the AES key from the master password."""
returnscrypt(password, salt=salt, key_len=32, N=2**15, r=8, p=1)
defdecrypt_database(password: str, filename: str) ->bytes:
"""For testing purpose only.
Decrypt the encrypt database. To use for testing purpose, to check that the decrypted
database is the same as the not-encrypted one.
"""
withopen(filename, "rb") asfile:
password_salt=_parse_header(file)
key=_derive_password(password, password_salt)
file.seek(HEADER_SIZE)
data=file.read()
plaindata=b""
foriinrange(0, len(data), BLOCK_SIZE):
plaindata+=_decrypt(key, data[i : i+BLOCK_SIZE])
returnplaindata
classEncryptedVFSFile(apsw.VFSFile):
def__init__(self, key: bytes, *args):
"""Encrypt the data when writing on the disk and decrypt when reading.
:param key: AES key used for encryption/decryption
"""
assertlen(key) ==32
self.key=key
super().__init__(*args)
# check that the SQLite page size match with the encryption block size
sector_size=self.xSectorSize()
assertsector_size<=BLOCK_SIZE-BLOCK_HEADER_SIZE
assertnot (BLOCK_SIZE-BLOCK_HEADER_SIZE) %sector_size
defxRead(self, amount: int, offset: int) ->bytes:
assertamount<=BLOCK_SIZE
offset+= (offset// (BLOCK_SIZE-BLOCK_HEADER_SIZE)) *BLOCK_HEADER_SIZE
start_block_offset=offset- (offset%BLOCK_SIZE)
end_offset=offset+amount
end_block_offset=end_offset- (end_offset%-BLOCK_SIZE)
assertnot (end_block_offset-start_block_offset) %BLOCK_SIZE
data=super().xRead(
end_block_offset-start_block_offset, start_block_offset+HEADER_SIZE
)
ifnotdata:
returndata
data=_decrypt(self.key, data)
returndata[offset%BLOCK_SIZE : offset%BLOCK_SIZE+amount]
defxWrite(self, data: bytes, offset: int):
offset+= (offset// (BLOCK_SIZE-BLOCK_HEADER_SIZE)) *BLOCK_HEADER_SIZE
start_block_offset=offset- (offset%BLOCK_SIZE)
assertnotstart_block_offset%BLOCK_SIZE
if (offset+len(data)) > (start_block_offset+BLOCK_SIZE-BLOCK_HEADER_SIZE):
end_data_pos= (
start_block_offset+BLOCK_SIZE-BLOCK_HEADER_SIZE
) -offset
self.xWrite(data[:end_data_pos], start_block_offset+BLOCK_SIZE)
data=data[:end_data_pos]
assertoffset+len(data) <=start_block_offset+BLOCK_SIZE
# the data doesn't fill into blocks
# so we need to read the entire block to add data
blocks_data=super().xRead(BLOCK_SIZE, start_block_offset+HEADER_SIZE)
assertlen(blocks_data) in [0, BLOCK_SIZE]
ifnotlen(blocks_data):
# we add new block at the end of the file
blocks_data=bytearray(os.urandom(BLOCK_SIZE-BLOCK_HEADER_SIZE))
else:
blocks_data=_decrypt(self.key, blocks_data)
blocks_data[offset%BLOCK_SIZE : offset%BLOCK_SIZE+len(data)] =data
blocks_data=_encrypt(self.key, blocks_data)
super().xWrite(blocks_data, start_block_offset+HEADER_SIZE)
defxFileSize(self) ->int:
file_size=super().xFileSize()
returnfile_size-HEADER_SIZE- (file_size//BLOCK_SIZE) -BLOCK_HEADER_SIZE
classEncryptedVFS(apsw.VFS):
def__init__(self, password: str, vfsname: str="encrypted", basevfs: str=""):
self.vfsname=vfsname
self.basevfs=basevfs
self.password=password
# SQLite open and close many time the same file
# so we store the derived keys and the IVs salt
# to not re-generate them each time the file is opened
self.files_key= {}
super().__init__(self.vfsname, self.basevfs)
defxOpen(self, name, flags):
"""Open the file and read the header (store necessary data)."""
filename=nameifisinstance(name, str) elsename.filename()
iffilenamenotinself.files_key:
withopen(filename, "a+b") asfile:
password_salt=_parse_header(file)
ifnotpassword_salt:
# init the header of the file
password_salt=os.urandom(16)
file.seek(0)
file.write(password_salt)
self.files_key[filename] =_derive_password(self.password, password_salt)
returnEncryptedVFSFile(self.files_key[filename], self.basevfs, name, flags)
classConnection(apsw.Connection):
def__init__(self, filename: str, password: str) ->"Connection":
self.password=password
self.encrypted_vfs=EncryptedVFS(password)
super().__init__(filename, vfs=self.encrypted_vfs.vfsname)
defchange_password(self, new_password: str):
new_password_salt=os.urandom(16)
new_key=_derive_password(new_password, new_password_salt)
ifnotself.filename:
# ':memory:' database (so not encrypted)
return
withopen(self.filename, "r+b") asfile:
file.seek(0)
header=file.read(HEADER_SIZE)
old_password_salt=header[:16]
old_key=_derive_password(self.password, old_password_salt)
iflen(header) !=HEADER_SIZE:
self.__init__(self.filename, new_password)
return
file.seek(0)
file.write(new_password_salt)
data=file.read(BLOCK_SIZE)
offset=0
whiledata:
data=_decrypt(old_key, data)
data=_encrypt(new_key, data)
file.seek(-BLOCK_SIZE, 1)
file.write(data)
offset+=BLOCK_SIZE
data=file.read(BLOCK_SIZE)
self.__init__(self.filename, new_password)