Esempio n. 1
0
def add_vanity():
    key_manager = keymanager.KeyManager()
    tell = lambda tell: logger.info(tell, terminal=True)
    words = ''
    length = len(sys.argv) - 2
    if length == 0: return
    for i in range(2, len(sys.argv)):
        words += ' '
        words += sys.argv[i]
    try:
        if length == 1:
            tell('Finding vanity, this should only take a few moments.')
        else:
            tell('Finding vanity, this will probably take a really long time.')
        try:
            vanity = vanityonionr.find_multiprocess(words)
        except ValueError:
            logger.warn('Vanity words must be valid english bip39',
                        terminal=True)
        else:
            b32_pub = unpaddedbase32.b32encode(vanity[0])
            tell('Found vanity address:\n' +
                 niceware.bytes_to_passphrase(vanity[0]))
            tell('Base32 Public key: %s' % (b32_pub.decode(), ))
            key_manager.addKey(b32_pub, unpaddedbase32.b32encode(vanity[1]))
    except KeyboardInterrupt:
        pass
Esempio n. 2
0
def add_ID():
    """Command to create a new user ID key pair."""
    key_manager = keymanager.KeyManager()
    pw = ""
    try:
        sys.argv[2]  # pylint: disable=W0104
        if not sys.argv[2].lower() == 'true':
            raise ValueError
    except (IndexError, ValueError):
        newID = key_manager.addKey()[0]
    else:
        pw = "-".join(niceware.generate_passphrase(32))
        newID, privKey = onionrcrypto.generate_deterministic(pw)
        try:
            key_manager.addKey(pubKey=newID, privKey=privKey)
        except ValueError:
            logger.error(
                'That ID is already available, you can change to it ' +
                'with the change-id command.',
                terminal=True)
            return
    if pw:
        print("Phrase to restore ID:", pw)
    logger.info('Added ID: %s' %
                (bytesconverter.bytes_to_str(newID.replace('=', '')), ),
                terminal=True)
Esempio n. 3
0
def shorten(sess, url):
    """
    Function used to shorten a single long url
    :param sess: mysql session
    :param url: long url to store in db
    :return:
    """
    global manager

    if not validators.url(url):
        return "Invalid Url"

    if manager is None:
        manager = keymanager.KeyManager()
        
    try:
        tiny_url = __add_to_sess(sess, url)
        sess.commit()
        return tiny_url

    except IntegrityError:
        sess.rollback()

    except Exception as E:
        sess.rollback()
    def test_01_create(self):

        km = keymanager.KeyManager( password = self.password,
                                                 drive = self.drive,
                                                 mountpoint = self.mountpoint )
        self.assertEqual( self.password, km.password )
        self.assertEqual( self.drive, km.drive )
        self.assertEqual( self.mountpoint, km.mountpoint )
        self.assertFalse( km.mounted )
Esempio n. 5
0
 def test_remove(self):
     manager = keymanager.KeyManager()
     new_key = manager.addKey()[0]
     priv_key = manager.getPrivkey(new_key)
     self.assertIn(new_key, manager.getPubkeyList())
     with open(filepaths.keys_file, 'r') as keyfile:
         self.assertIn(new_key, keyfile.read())
     manager.removeKey(new_key)
     with open(filepaths.keys_file, 'r') as keyfile:
         self.assertNotIn(new_key, keyfile.read())
 def setUp(self):
     unittest.TestCase.setUp(self)
     self.password = "******"
     self.drive = "/tmp/strongbox.crypto"
     self.mountpoint = "/tmp/strongbox"
     self.backupfile = "/tmp/strongbox.crypto.backup"
     self.new_password = "******"
     self.keymanager = keymanager.KeyManager( password = self.password,
                                              drive = self.drive,
                                              mountpoint = self.mountpoint )
Esempio n. 7
0
    def __init__(self,
                 mode='LISTEN',
                 target_ip='127.0.0.1',
                 port=2333,
                 msg_queue=[]):
        # 显示信息队列
        self.msg_queue = msg_queue

        #初始化接收方信息
        if mode == 'LISTEN':
            self.target_config = {"target_ip": '127.0.0.1', "port": 2333}
        else:
            self.fetch_local_config()

        # 初始化模块
        self.crypt = crypto.MsgCrypto.MsgCrypto()
        self.sm4_key = keymanager.KeyManager().get_sm4_key()
        self.km = keymanager.KeyManager()

        # 双方rsa初始化
        self.km.fetch_local_key()
        self.crypt.rsa_my_init(n=self.km.get_rsa_n(),
                               e=self.km.get_rsa_private_key(),
                               d=self.km.get_rsa_public_key())
        self.crypt.rsa_target_init(n=self.km.get_rsa_n(),
                                   e=self.km.get_rsa_private_key(),
                                   d=self.km.get_rsa_public_key())

        # 用keymanager取到的sm4密钥设置crypt模块
        self.crypt.sm4_init(key=self.sm4_key)

        # 监听端口或连接
        self.trans = network.MySocket(msg_queue=self.msg_queue)
        if mode == 'LISTEN':
            self.trans.listen(port)
        elif mode == 'NONE':
            pass
        else:
            self.trans.connect(self.target_config["target_ip"],
                               self.target_config["port"])
            # 协商sm4_key
            self.send_sm4_key(self.sm4_key)
Esempio n. 8
0
def get_keypair():
    key_m = keymanager.KeyManager()
    if os.path.exists(filepaths.keys_file):
        if len(config.get('general.public_key', '')) > 0:
            pubKey = config.get('general.public_key')
        else:
            pubKey = key_m.getPubkeyList()[0]
        privKey = key_m.getPrivkey(pubKey)
    else:
        keys = generate.generate_pub_key()
        pubKey = keys[0]
        privKey = keys[1]
        key_m.addKey(pubKey, privKey)
    return (pubKey, privKey)
Esempio n. 9
0
def add_ID():
    """Command to create a new user ID key pair."""
    key_manager = keymanager.KeyManager()
    try:
        sys.argv[2]  # pylint: disable=W0104
        if not sys.argv[2].lower() == 'true':
            raise ValueError
    except (IndexError, ValueError):
        newID = key_manager.addKey()[0]
    else:
        logger.warn('Deterministic keys require random and long passphrases.',
                    terminal=True)
        logger.warn(
            'If a good passphrase is not used, your key can be easily stolen.',
            terminal=True)
        logger.warn('You should use a series of hard to guess words, ' +
                    'see this for reference: https://www.xkcd.com/936/',
                    terminal=True)
        try:
            pass1 = getpass.getpass(prompt='Enter at least %s characters: ' %
                                    (DETERMINISTIC_REQUIREMENT, ))
            pass2 = getpass.getpass(prompt='Confirm entry: ')
        except KeyboardInterrupt:
            sys.exit(42)
        if onionrcrypto.cryptoutils.safe_compare(pass1, pass2):
            try:
                logger.info(
                    'Generating deterministic key. This can take a while.',
                    terminal=True)
                newID, privKey = onionrcrypto.generate_deterministic(pass1)
            except onionrexceptions.PasswordStrengthError:
                logger.error('Passphrase must use at least %s characters.' %
                             (DETERMINISTIC_REQUIREMENT, ),
                             terminal=True)
                sys.exit(1)
        else:
            logger.error('Passwords do not match.', terminal=True)
            sys.exit(1)
        try:
            key_manager.addKey(pubKey=newID, privKey=privKey)
        except ValueError:
            logger.error(
                'That ID is already available, you can change to it ' +
                'with the change-id command.',
                terminal=True)
            return
    logger.info('Added ID: %s' % (bytesconverter.bytes_to_str(newID), ),
                terminal=True)
Esempio n. 10
0
    def __init__(self):
        self._key_manager = keymanager.KeyManager()
        self._mouse_manager = mousemanager.MouseManager()
        self._graph = Graph()
        self._running = True
        self._display_surf = None
        self._width, self._height = 800, 600
        self._size = (self._width, self._height)
        self._bg_color = (255, 255, 255)
        self._state = DRAW_NODES

        self._key_manager.register_callback(pygame.K_e, self._on_key_e_cb)
        self._key_manager.register_callback(pygame.K_n, self._on_key_n_cb)

        # Register mouse callbacks
        self._mouse_manager.register_callback(1, self._on_left_button_cb)
Esempio n. 11
0
def change_ID():
    key_manager = keymanager.KeyManager()
    try:
        key = sys.argv[2]
        key = unpaddedbase32.repad(key.encode()).decode()
    except IndexError:
        logger.warn('Specify pubkey to use', terminal=True)
    else:
        if stringvalidators.validate_pub_key(key):
            key_list = key_manager.getPubkeyList()
            if key in key_list or key.replace('=', '') in key_list:
                config.set('general.public_key', key)
                config.save()
                logger.info('Set active key to: %s' % (key, ), terminal=True)
                logger.info('Restart Onionr if it is running.', terminal=True)
            else:
                logger.warn('That key does not exist', terminal=True)
        else:
            logger.warn('Invalid key %s' % (key, ), terminal=True)
Esempio n. 12
0
    def __init__(self, coreInstance):
        self._core = coreInstance
        self._keyFile = self._core.dataDir + 'keys.txt'
        self.pubKey = None
        self.privKey = None
        self.secrets = secrets
        self.deterministicRequirement = 25  # Min deterministic password/phrase length
        self.HASH_ID_ROUNDS = 2000
        self.keyManager = keymanager.KeyManager(self)

        # Load our own pub/priv Ed25519 keys, gen & save them if they don't exist
        if os.path.exists(self._keyFile):
            if len(config.get('general.public_key', '')) > 0:
                self.pubKey = config.get('general.public_key')
            else:
                self.pubKey = self.keyManager.getPubkeyList()[0]
            self.privKey = self.keyManager.getPrivkey(self.pubKey)
        else:
            keys = self.generatePubKey()
            self.pubKey = keys[0]
            self.privKey = keys[1]
            self.keyManager.addKey(self.pubKey, self.privKey)
        return
Esempio n. 13
0
 def test_change(self):
     new_key = keymanager.KeyManager().addKey()[0]
     self.assertNotEqual(new_key, pub_key)
     self.assertEqual(new_key, keymanager.KeyManager().getPubkeyList()[1])
     stringvalidators.validate_pub_key(new_key)
Esempio n. 14
0
 def test_sane_default(self):
     self.assertGreaterEqual(len(pub_key), 52)
     self.assertLessEqual(len(pub_key), 56)
     self.assertEqual(pub_key, keymanager.KeyManager().getPubkeyList()[0])
     stringvalidators.validate_pub_key(pub_key)
Esempio n. 15
0
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
sys.path.append("src/")
import unittest, uuid

TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
from utils import createdirs
from coredb import keydb
import onionrsetup as setup, keymanager, filepaths
from onionrutils import stringvalidators
createdirs.create_dirs()
setup.setup_config()
pub_key = keymanager.KeyManager().getPubkeyList()[0]


class KeyManagerTest(unittest.TestCase):
    def test_sane_default(self):
        self.assertGreaterEqual(len(pub_key), 52)
        self.assertLessEqual(len(pub_key), 56)
        self.assertEqual(pub_key, keymanager.KeyManager().getPubkeyList()[0])
        stringvalidators.validate_pub_key(pub_key)

    def test_change(self):
        new_key = keymanager.KeyManager().addKey()[0]
        self.assertNotEqual(new_key, pub_key)
        self.assertEqual(new_key, keymanager.KeyManager().getPubkeyList()[1])
        stringvalidators.validate_pub_key(new_key)