Onionr/src/safedb/__init__.py

73 lines
2.3 KiB
Python
Raw Normal View History

2021-01-02 01:29:14 +00:00
"""Onionr - Private P2P Communication.
Create required Onionr directories
"""
from typing import Union
import dbm
2020-12-31 03:25:05 +00:00
from .securestring import generate_key_file, protect_string, unprotect_string
2021-01-02 01:29:14 +00:00
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
2020-12-31 03:25:05 +00:00
2021-01-02 01:29:14 +00:00
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
class DBProtectionOpeningModeError(Exception):
pass
class SafeDB:
2020-12-31 03:25:05 +00:00
"""Wrapper around dbm to optionally encrypt db values."""
def get(self, key: Union[str, bytes, bytearray]) -> bytes:
if self.protected:
return self.db_conn[key]
return unprotect_string(self.db_conn[key])
2020-12-31 03:25:05 +00:00
def put(
self,
key: Union[str, bytes, bytearray], value: Union[bytes, bytearray]):
2020-12-31 03:25:05 +00:00
if self.protected:
self.db_conn[key] = protect_string(value)
else:
self.db_conn[key] = value
2020-12-31 03:25:05 +00:00
def close(self):
self.db_conn.close()
2021-01-17 00:40:04 +00:00
def __init__(self, db_path: str, protected=False):
self.db_path = db_path
2020-12-31 03:25:05 +00:00
self.db_conn = dbm.open(db_path, "c")
try:
existing_protected_mode = self.db_conn['enc']
if protected and existing_protected_mode != b'1':
raise DBProtectionOpeningModeError(
2020-12-31 03:25:05 +00:00
"Cannot open unencrypted database with protected=True")
elif not protected and existing_protected_mode != b'0':
raise DBProtectionOpeningModeError(
2020-12-31 03:25:05 +00:00
"Cannot open encrypted database in protected=False")
except KeyError:
if protected:
self.db_conn['enc'] = b'1'
else:
self.db_conn['enc'] = b'0'
try:
generate_key_file()
except FileExistsError:
pass
self.protected = protected