Onionr/onionr/keymanager.py

78 lines
2.7 KiB
Python
Raw Normal View History

2018-12-09 17:29:39 +00:00
'''
Onionr - Private P2P Communication
2018-12-09 17:29:39 +00:00
Load, save, and delete the user's public key pairs (does not handle peer keys)
'''
'''
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
'''
from onionrutils import bytesconverter
2019-07-19 19:49:56 +00:00
from onionrcrypto import generate
2019-08-05 23:09:04 +00:00
import os
2019-07-19 19:49:56 +00:00
import filepaths
2019-09-09 08:52:40 +00:00
2018-12-09 17:29:39 +00:00
class KeyManager:
2019-07-19 19:49:56 +00:00
def __init__(self):
self.keyFile = filepaths.keys_file
2018-12-09 17:29:39 +00:00
def addKey(self, pubKey=None, privKey=None):
2019-07-27 20:29:15 +00:00
'''Add a new key pair, either specified or none to generate a new pair automatically'''
2018-12-09 17:29:39 +00:00
if type(pubKey) is type(None) and type(privKey) is type(None):
2019-07-19 19:49:56 +00:00
pubKey, privKey = generate.generate_pub_key()
pubKey = bytesconverter.bytes_to_str(pubKey)
privKey = bytesconverter.bytes_to_str(privKey)
2018-12-09 17:29:39 +00:00
try:
if pubKey in self.getPubkeyList():
raise ValueError('Pubkey already in list: %s' % (pubKey,))
except FileNotFoundError:
pass
2019-08-05 23:09:04 +00:00
2018-12-09 17:29:39 +00:00
with open(self.keyFile, "a") as keyFile:
keyFile.write(pubKey + ',' + privKey + '\n')
return (pubKey, privKey)
def removeKey(self, pubKey):
'''Remove a key pair by pubkey'''
keyList = self.getPubkeyList()
keyData = ''
try:
keyList.remove(pubKey)
except ValueError:
return False
else:
keyData = ','.join(keyList)
with open(self.keyFile, "w") as keyFile:
keyFile.write(keyData)
def getPubkeyList(self):
'''Return a list of the user's keys'''
keyList = []
2019-07-27 20:29:15 +00:00
try:
with open(self.keyFile, "r") as keyFile:
keyData = keyFile.read()
except FileNotFoundError:
keyData = ''
2018-12-09 17:29:39 +00:00
keyData = keyData.split('\n')
for pair in keyData:
if len(pair) > 0: keyList.append(pair.split(',')[0])
return keyList
def getPrivkey(self, pubKey):
privKey = None
with open(self.keyFile, "r") as keyFile:
keyData = keyFile.read()
for pair in keyData.split('\n'):
2019-09-09 08:52:40 +00:00
if pubKey in pair or pubKey.replace('=', '') in pair:
2018-12-09 17:29:39 +00:00
privKey = pair.split(',')[1]
2019-07-19 19:49:56 +00:00
return privKey