Пример #1
0
def generate_keys(press_count, text_area, nick_textbox, other_nick_textbox, password_textbox):
	NICK = nick_textbox.get()
	OTHER_NICK = other_nick_textbox.get()
	password = password_textbox.get()

	print "nick: " + NICK
	print "other nick: " + OTHER_NICK
	print "password: "******"make sure nick, other nick and password entries are filled out!\n\n")
		text_area.config(fg="red",state=tk.DISABLED)

	else: 
		global newaxo
		newaxo = Axolotl(NICK, dbname=OTHER_NICK+'.db', dbpassphrase=password)
		newaxo.printKeys()
		identity_key = "identity key: " + binascii.b2a_base64(newaxo.state['DHIs'])
		fingerprint = hashlib.sha224(newaxo.state['DHIs']).hexdigest().upper() #getting fingerprint
		fprint = ''
		for i in range(0, len(fingerprint), 4):
		    fprint += fingerprint[i:i+2] + ':'

		fingerprint = "fingerprint:" + fprint[:-1] + "\n"
		rachet_key="rachet_key: " + binascii.b2a_base64(newaxo.state['DHRs'])
		handshake_key = "handshake key: " + binascii.b2a_base64(newaxo.handshakePKey)
		text_area.config(state=tk.NORMAL)
		text_area.insert(tk.END, identity_key+fingerprint+rachet_key+handshake_key)
		text_area.config(fg="black",state=tk.DISABLED)
Пример #2
0
def decrypt(data, msgtype, servername, args):
    global decrypted
    hostmask, chanmsg = string.split(args, "PRIVMSG ", 1)
    channelname, message = string.split(chanmsg, " :", 1)
    if re.match(r'^\[\d{2}:\d{2}:\d{2}]\s', message):
        timestamp = message[:11]
        message = message[11:]
    else:
        timestamp = ''
    if channelname[0] == "#":
        username = channelname
    else:
        username, rest = string.split(hostmask, "!", 1)
        username = username[1:]
    buf = weechat.current_buffer()
    nick = weechat.buffer_get_string(buf, 'localvar_nick')
    if os.path.exists(weechat_dir + '/' + username + '.db'):
        a = Axolotl(nick,
                    dbname=weechat_dir + '/' + username + '.db',
                    dbpassphrase=getPasswd(username))
        a.loadState(nick, username)
        decrypted = a.decrypt(a2b_base64(message))
        a.saveState()
        del a
        if decrypted == "":
            return args
        decrypted = ''.join(c for c in decrypted if ord(c) > 31 or ord(c) == 9
                            or ord(c) == 2 or ord(c) == 3 or ord(c) == 15)
        return hostmask + "PRIVMSG " + channelname + " :" + chr(
            3) + "04" + weechat.config_get_plugin("message_indicator") + chr(
                15) + timestamp + decrypted
    else:
        return args
Пример #3
0
def decrypt(data, msgtype, servername, args):
  global decrypted
  hostmask, chanmsg = string.split(args, "PRIVMSG ", 1)
  channelname, message = string.split(chanmsg, " :", 1)
  if re.match(r'^\[\d{2}:\d{2}:\d{2}]\s', message):
    timestamp = message[:11]
    message = message[11:]
  else:
    timestamp = ''
  if channelname[0] == "#":
    username=channelname
  else:
    username, rest = string.split(hostmask, "!", 1)
    username = username[1:]
  nick = channelname.strip()
  if os.path.exists(weechat_dir + '/' + username + '.db'):
    a = Axolotl(nick, dbname=weechat_dir+'/'+username+'.db', dbpassphrase=getPasswd(username))
    a.loadState(nick, username)
    decrypted = a.decrypt(a2b_base64(message))
    a.saveState()
    del a
    if decrypted == "":
      return args
    decrypted = ''.join(c for c in decrypted if ord(c) > 31 or ord(c) == 9 or ord(c) == 2 or ord(c) == 3 or ord(c) == 15)
    return hostmask + "PRIVMSG " + channelname + " :" + chr(3) + "04" + weechat.config_get_plugin("message_indicator") + chr(15) + timestamp + decrypted
  else:
    return args
Пример #4
0
def create_axolotl(nym, directory):
    # workaround to suppress prints by pyaxo
    sys.stdout = open(os.devnull, 'w')
    try:
        axolotl = Axolotl(name=nym.fingerprint,
                          dbname=os.path.join(directory,
                                              nym.fingerprint + '.db'),
                          dbpassphrase=nym.passphrase)
    except SystemExit:
        sys.stdout = sys.__stdout__
        raise errors.IncorrectPassphraseError()
    else:
        sys.stdout = sys.__stdout__
        return axolotl
Пример #5
0
    def test_passphrase(self, passphrase_0, passphrase_1):
        a = Axolotl('Angie', dbpassphrase=passphrase_0)
        b = Axolotl('Barb', dbpassphrase=None)

        a.initState(other_name=b.name,
                    other_identityKey=b.state['DHIs'],
                    other_handshakeKey=b.handshakePKey,
                    other_ratchetKey=b.state['DHRs'],
                    verify=False)
        a.saveState()

        if passphrase_0 == passphrase_1:
            a = Axolotl('Angie', dbpassphrase=passphrase_1)
            assert isinstance(a.db, sqlite3.Connection)
        else:
            with pytest.raises(SystemExit):
                a = Axolotl('Angie', dbpassphrase=passphrase_1)
Пример #6
0
#!/usr/bin/env python

"""
This program will encrypt or decrypt a file
"""

import sys

from pyaxo import Axolotl

your_name = raw_input("What is your name? ").strip()

# specify dbname with kwarg - default dbname is axolotl.db db passphrase
# will be prompted for - it can be specified here with dbpassprase kwarg

a = Axolotl(your_name, dbname=your_name + ".db")

other_name = None
try:
    if sys.argv[1] == "-e":
        other_name = raw_input(
            "What is the name of the party \
            that you want to encrypt the file to? "
        ).strip()
        a.loadState(your_name, other_name)
        a.encrypt_file(sys.argv[2])
        print "The encrypted file is: " + sys.argv[2] + ".asc"
    else:
        other_name = raw_input(
            "What is the name of the party that \
            you want to decrypt the file from? "
Пример #7
0
def axolotl_c():
    return Axolotl('Charlie', dbpassphrase=None)
Пример #8
0
    def test_individual_dbs(self, exchange):
        # create two instance classes with encrypted databases
        a = Axolotl('angie', dbname=self.dbs[0], dbpassphrase=self.dbs[0])
        b = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1])

        # initialize the states
        a.initState(other_name=b.name,
                    other_identityKey=b.state['DHIs'],
                    other_handshakeKey=b.handshakePKey,
                    other_ratchetKey=b.state['DHRs'],
                    verify=False)
        b.initState(other_name=a.name,
                    other_identityKey=a.state['DHIs'],
                    other_handshakeKey=a.handshakePKey,
                    other_ratchetKey=a.state['DHRs'],
                    verify=False)

        # save the states
        a.saveState()
        b.saveState()

        # reload the databases
        a = Axolotl('angie', dbname=self.dbs[0], dbpassphrase=self.dbs[0])
        b = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1])

        # load their states
        a.loadState(a.name, b.name)
        b.loadState(b.name, a.name)

        # send some messages back and forth
        exchange(a, b)
Пример #9
0
    def test_shared_db(self):
        # create two instance classes - one which will share its database
        # (note that Dick and Harry's passphrases must match or Harry won't
        # be able to load Dick's saved database)
        shared_pass = '******'
        tom = Axolotl('Tom', dbpassphrase="tom's passphrase")
        dick = Axolotl('Dick', dbpassphrase=shared_pass)

        # initialize Tom and Dick's states
        tom.initState(other_name=dick.name,
                      other_identityKey=dick.state['DHIs'],
                      other_handshakeKey=dick.handshakePKey,
                      other_ratchetKey=dick.state['DHRs'],
                      verify=False)
        dick.initState(other_name=tom.name,
                       other_identityKey=tom.state['DHIs'],
                       other_handshakeKey=tom.handshakePKey,
                       other_ratchetKey=tom.state['DHRs'],
                       verify=False)

        # get the plaintext
        msg = 'plaintext'

        # Tom encrypts it to Dick
        ciphertext = tom.encrypt(msg)

        # save Dick's state prior to decrypting the message
        dick.saveState()

        # Dick decrypts the ciphertext
        assert dick.decrypt(ciphertext) == msg

        # now load Dick's state to Harry
        harry = Axolotl('Harry', dbpassphrase=shared_pass)
        harry.loadState(dick.name, tom.name)

        # Harry decrypts the ciphertext
        assert harry.decrypt(ciphertext) == msg
Пример #10
0
def threaded_axolotl_c():
    return Axolotl('Charlie', dbpassphrase=None, nonthreaded_sql=False)
in their weechat configuration directory.

You should only need to generate and distribute the databases once per
nick pair.

If each party wishes to generate their own database, you can use the
init_conversations.py script in the utilities directory of the Axolotl
distribution.
"""

import sys
import binascii
from pyaxo import Axolotl

# modify this as appropriate (also modify axolotl.worker.py to match)
def getPasswd(username):
    return username + "123"


your_nick = raw_input("Your nick for this conversation? ").strip()
other_nick = raw_input("What is the nick of the other party? ").strip()
a = Axolotl(your_nick, dbname=other_nick + ".db", dbpassphrase=getPasswd(other_nick))
b = Axolotl(other_nick, dbname=your_nick + ".db", dbpassphrase=getPasswd(your_nick))
a.initState(other_nick, b.state["DHIs"], b.handshakePKey, b.state["DHRs"], verify=False)
b.initState(your_nick, a.state["DHIs"], a.handshakePKey, a.state["DHRs"], verify=False)

a.saveState()
b.saveState()
print "The keys for " + your_nick + " -> " + other_nick + " have been saved in: " + other_nick + ".db"
print "The keys for " + other_nick + " -> " + your_nick + " have been saved in: " + your_nick + ".db"
Пример #12
0
"""
This script will generate a pair of databases named after two conversants.
The databases can then be securely distributed to initialize axolotl.

You will need to provide your name and the other party's name. Conversations
are identified by your name and the other person's name. The conversation
should have a unique other person's name.

If you decide not to complete the initialization process, just answer no to the
question about creating a new conversation. Nothing will be saved.

If you want to reinitialize a conversation, just run the script again.
The old conversation key data will be overwritten in the databases.
"""

import sys
import binascii
from pyaxo import Axolotl

your_name = raw_input('Your name for this conversation? ').strip()
other_name = raw_input('What is the name of the other party? ').strip()
a = Axolotl(your_name,dbname=your_name+'.db')
b = Axolotl(other_name,dbname=other_name+'.db')
a.initState(other_name, b.state['DHIs'], b.handshakePKey, b.state['DHRs'], verify=False)
b.initState(your_name, a.state['DHIs'], a.handshakePKey, a.state['DHRs'], verify=False)

a.saveState()
b.saveState()
print 'The conversation ' + your_name + ' -> ' + other_name + ' has been saved in: ' + your_name + '.db'
print 'The conversation ' + other_name + ' -> ' + your_name + ' has been saved in: ' + other_name + '.db'
Пример #13
0
    while True:
        try:
            PORT = raw_input("TCP port (1 for random choice, 50000 is default): ")
            PORT = int(PORT)
            break
        except ValueError:
            PORT = 50000
            break
    if PORT >= 1025 and PORT <= 65535:
        pass
    elif PORT == 1:
        PORT = 1025 + randint(0, 64510)
        print "PORT is " + str(PORT)

    if mode == "-s":
        a = Axolotl(NICK, dbname=OTHER_NICK + ".db", dbpassphrase=None, nonthreaded_sql=False)
        a.createState(other_name=OTHER_NICK, mkey=hashlib.sha256(mkey).digest(), mode=False)
        print "Your ratchet key is: %s" % b2a(a.state["DHRs"]).strip()
        print "Send this to %s..." % OTHER_NICK

        print "Waiting for " + OTHER_NICK + " to connect..."
        with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((HOST, PORT))
            s.listen(1)
            conn, addr = s.accept()
            chatThread(conn)

    elif mode == "-c":
        rkey = raw_input("Enter %s's ratchet key: " % OTHER_NICK)
        a = Axolotl(NICK, dbname=OTHER_NICK + ".db", dbpassphrase=None, nonthreaded_sql=False)
        a.createState(other_name=OTHER_NICK, mkey=hashlib.sha256(mkey).digest(), mode=True, other_ratchetKey=a2b(rkey))
Пример #14
0
    def test_persist_skipped_mk(
            self, a_identity_keys, a_handshake_keys, a_ratchet_keys,
            b_identity_keys, b_handshake_keys, b_ratchet_keys):
        a = Axolotl('angie', dbname=self.dbs[0], dbpassphrase=self.dbs[0])
        b = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1])

        conv_a = a.init_conversation(
            b.name,
            priv_identity_key=a_identity_keys.priv,
            identity_key=a_identity_keys.pub,
            priv_handshake_key=a_handshake_keys.priv,
            other_identity_key=b_identity_keys.pub,
            other_handshake_key=b_handshake_keys.pub,
            priv_ratchet_key=a_ratchet_keys.priv,
            ratchet_key=a_ratchet_keys.pub,
            other_ratchet_key=b_ratchet_keys.pub)

        conv_b = b.init_conversation(
            a.name,
            priv_identity_key=b_identity_keys.priv,
            identity_key=b_identity_keys.pub,
            priv_handshake_key=b_handshake_keys.priv,
            other_identity_key=a_identity_keys.pub,
            other_handshake_key=a_handshake_keys.pub,
            priv_ratchet_key=b_ratchet_keys.priv,
            ratchet_key=b_ratchet_keys.pub,
            other_ratchet_key=a_ratchet_keys.pub)

        pt = [utils.PLAINTEXT.format(i) for i in range(5)]
        ct = list()

        utils.encrypt(conv_a, 0, pt, ct)
        utils.decrypt(conv_b, 0, pt, ct)
        utils.encrypt(conv_a, 1, pt, ct)
        utils.encrypt(conv_a, 2, pt, ct)
        utils.decrypt(conv_b, 2, pt, ct)
        utils.encrypt(conv_a, 3, pt, ct)
        utils.encrypt(conv_a, 4, pt, ct)
        utils.decrypt(conv_b, 4, pt, ct)

        # make sure there are staged skipped keys
        assert conv_b.staged_hk_mk

        # save the database, copy the staged keys dict and delete the objects
        conv_b.save()
        persisted_hk_mk = deepcopy(conv_b.staged_hk_mk)
        del b, conv_b

        # load the conversation from disk
        B = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1])
        conv_B = B.load_conversation(a.name)

        # assert both dicts have the same content
        assert conv_B.staged_hk_mk.keys() == persisted_hk_mk.keys()
        for mk in conv_B.staged_hk_mk:
            assert conv_B.staged_hk_mk[mk].mk == persisted_hk_mk[mk].mk
            assert conv_B.staged_hk_mk[mk].hk == persisted_hk_mk[mk].hk
            assert (conv_B.staged_hk_mk[mk].timestamp ==
                    persisted_hk_mk[mk].timestamp)

        # decrypt the skipped messages
        utils.decrypt(conv_B, 1, pt, ct)
        utils.decrypt(conv_B, 3, pt, ct)
Пример #15
0
    def test_shared_db(self):
        # create two instance classes - one which will share its database
        # (note that Dick and Harry's passphrases must match or Harry won't
        # be able to load Dick's saved database)
        shared_pass = '******'
        tom = Axolotl('Tom', dbpassphrase="tom's passphrase")
        dick = Axolotl('Dick', dbpassphrase=shared_pass)

        # initialize Tom and Dick's states
        tom.initState(other_name=dick.name,
                      other_identityKey=dick.state['DHIs'],
                      other_handshakeKey=dick.handshakePKey,
                      other_ratchetKey=dick.state['DHRs'],
                      verify=False)
        dick.initState(other_name=tom.name,
                       other_identityKey=tom.state['DHIs'],
                       other_handshakeKey=tom.handshakePKey,
                       other_ratchetKey=tom.state['DHRs'],
                       verify=False)

        # get the plaintext
        msg = 'plaintext'

        # Tom encrypts it to Dick
        ciphertext = tom.encrypt(msg)

        # save Dick's state prior to decrypting the message
        dick.saveState()

        # Dick decrypts the ciphertext
        assert dick.decrypt(ciphertext) == msg

        # now load Dick's state to Harry
        harry = Axolotl('Harry', dbpassphrase=shared_pass)
        harry.loadState(dick.name, tom.name)

        # Harry decrypts the ciphertext
        assert harry.decrypt(ciphertext) == msg
Пример #16
0
#!/usr/bin/env python

"""
A three-toed Axolotl track ;-)
"""

from pyaxo import Axolotl

# create two instance classes
a = Axolotl("Angie")
b = Axolotl("Barb")

# initialize their states
a.initState("Barb", b.state["DHIs"], b.handshakePKey, b.state["DHRs"], verify=False)
b.initState("Angie", a.state["DHIs"], a.handshakePKey, a.state["DHRs"], verify=False)

# tell who is who
if a.mode:
    print "Angie is Alice-like"
    print "Barb is Bob-like"
else:
    print "Angie is Bob-like"
    print "Barb is Alice-like"

# Walk the three-toed Axolotl walk..
msg0 = a.encrypt("Step 1, Toe 1")
msg1 = a.encrypt("Step 1, Toe 2")
msg2 = a.encrypt("Step 1, Toe 3")
print "b decrypt: ", b.decrypt(msg0)
print "b decrypt: ", b.decrypt(msg1)
print "b decrypt: ", b.decrypt(msg2)
Пример #17
0
def threaded_axolotl_a():
    return Axolotl('Angie', dbpassphrase=None, nonthreaded_sql=False)
Пример #18
0
#!/usr/bin/env python

from pyaxo import Axolotl
import sys
import os

# start with a fresh database
try:
    os.remove('./name1.db')
    os.remove('./name2.db')
except OSError:
    pass

# unencrypted databases
a = Axolotl('name1', dbname='name1.db', dbpassphrase=None)
b = Axolotl('name2', dbname='name2.db', dbpassphrase=None)

a.initState('name2',
            b.state['DHIs'],
            b.handshakePKey,
            b.state['DHRs'],
            verify=False)
b.initState('name1',
            a.state['DHIs'],
            a.handshakePKey,
            a.state['DHRs'],
            verify=False)

a.saveState()
b.saveState()
Пример #19
0
#!/usr/bin/env python

import os

from pyaxo import Axolotl


# need clean database for this example to work
try:
    os.remove('./axolotl.db')
except OSError:
    pass

# create two instance classes with unencrypted database
a = Axolotl('Angie', dbpassphrase=None)
b = Axolotl('Barb', dbpassphrase=None)

# initialize their states
a.initState('Barb', b.state['DHIs'], b.handshakePKey, b.state['DHRs'],
            verify=False)
b.initState('Angie', a.state['DHIs'], a.handshakePKey, a.state['DHRs'],
            verify=False)

# tell who is who
if a.mode:
    print 'Angie is Alice-like'
    print 'Barb is Bob-like'
else:
    print 'Angie is Bob-like'
    print 'Barb is Alice-like'
Пример #20
0
                break
            # PORT = raw_input('TCP port (1 for random choice, 50000 is default): ')
            PORT = 50000
            PORT = int(PORT)
            break
        except ValueError:
            PORT = 50000
            break
    if PORT >= 1025 and PORT <= 65535:
        pass
    elif PORT == 1:
        PORT = 1025 + randint(0, 64510)
        print("PORT is " + str(PORT))

    if mode == "-s":
        a = Axolotl(NICK, dbname=OTHER_NICK + ".db")
        a.postKeys()

        obj = ""

        print("Waiting for " + OTHER_NICK + " to connect and be authenticated...")
        smWait = True
        while smWait:
            smRecvUrl = "https://lab3key.herokuapp.com/messages?demail=" + NICK
            smRecvReq = urllib2.Request(smRecvUrl, headers={"content-type": "application/json"})
            smRecvResp = urllib2.urlopen(smRecvReq)
            try:
                responseVal = smRecvResp.read().decode("utf8")
                if responseVal != "none":
                    valstr = str(responseVal)
                    jsonval = json.loads(valstr)
Пример #21
0
    def test_individual_dbs(self, exchange):
        # create two instance classes with encrypted databases
        a = Axolotl('angie', dbname=self.dbs[0], dbpassphrase=self.dbs[0])
        b = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1])

        # initialize the states
        a.initState(other_name=b.name,
                    other_identityKey=b.state['DHIs'],
                    other_handshakeKey=b.handshakePKey,
                    other_ratchetKey=b.state['DHRs'],
                    verify=False)
        b.initState(other_name=a.name,
                    other_identityKey=a.state['DHIs'],
                    other_handshakeKey=a.handshakePKey,
                    other_ratchetKey=a.state['DHRs'],
                    verify=False)

        # save the states
        a.saveState()
        b.saveState()

        # reload the databases
        a = Axolotl('angie', dbname=self.dbs[0], dbpassphrase=self.dbs[0])
        b = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1])

        # load their states
        a.loadState(a.name, b.name)
        b.loadState(b.name, a.name)

        # send some messages back and forth
        exchange(a, b)
Пример #22
0
            PORT = raw_input(
                'TCP port (1 for random choice, 50000 is default): ')
            PORT = int(PORT)
            break
        except ValueError:
            PORT = 50000
            break
    if PORT >= 1025 and PORT <= 65535:
        pass
    elif PORT == 1:
        PORT = 1025 + randint(0, 64510)
        print 'PORT is ' + str(PORT)

    if mode == '-s':
        a = Axolotl(NICK,
                    dbname=OTHER_NICK + '.db',
                    dbpassphrase=None,
                    nonthreaded_sql=False)
        a.createState(other_name=OTHER_NICK,
                      mkey=hashlib.sha256(mkey).digest(),
                      mode=False)
        print 'Your ratchet key is: %s' % b2a(a.state['DHRs']).strip()
        print 'Send this to %s...' % OTHER_NICK

        print 'Waiting for ' + OTHER_NICK + ' to connect...'
        with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((HOST, PORT))
            s.listen(1)
            conn, addr = s.accept()
            chatThread(conn)

    elif mode == '-c':
Пример #23
0
def main():
    global a

    class Chat_Server(threading.Thread):
        def __init__(self):
            print "Chat_Server init"
            threading.Thread.__init__(self)
            self.running = 1
            self.conn = None
            self.addr = None
            self.host = '127.0.0.1'
            self.port = None

        def run(self):
            print "running chat server"
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((self.host, self.port))
            s.listen(1)
            print("waiting for connection from client")
            self.conn, addr = s.accept()
            while self.running == True:
                data = self.conn.recv(1024)

                if data:
                    data = a.decrypt(data)
                    if data == 'exit':
                        self.running = 0
                    else:
                        print "Client Says >> " + data
                else:
                    break
            time.sleep(0)

        def kill(self):
            self.running = 0

    class Chat_Client(threading.Thread):
        def __init__(self):
            print "Chat Client init"
            threading.Thread.__init__(self)
            self.host = None
            self.sock = None
            self.running = 1
            self.port = None

        def run(self):
            print "Chat Client Run"
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((self.host, self.port))
            while self.running == True:

                rcv = self.sock.recv(1024)

                data = '' + rcv
                if data:
                    data = a.decrypt(data)
                    if data == 'exit':
                        self.running = 0
                    else:
                        print "Server Says >> " + data
                else:
                    break
            time.sleep(0)

        def kill(self):
            self.running = 0

    class Text_Input(threading.Thread):
        def __init__(self):
            print "text input init"
            threading.Thread.__init__(self)
            self.running = 1

        def run(self):
            print "text input run "
            while self.running == True:
                text = raw_input('')
                try:
                    text = text.replace('\n', '') + '\n'
                    text = a.encrypt(text)
                    chat_client.sock.sendall(text)
                except:
                    Exception
                try:
                    text = text.replace('\n', '') + '\n'
                    text = a.encrypt(text)
                    chat_server.conn.sendall(text)
                except:
                    Exception
                time.sleep(0.1)

        def kill(self):
            self.running = 0

    try:
        mode = sys.argv[1]
    except:
        exit(1)

    if mode == '-s':
        s = socket.socket()
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
                     1)  # Socket object
        host = '127.0.0.1'  # Get host name
        port = 8000
        myName = raw_input("What is your name: ")
        otherName = raw_input("What is the other name: ")
        masterkey = raw_input("what is your previously decided on master key"
                              )  # Reserve best port.
        a = Axolotl(myName,
                    dbname=otherName + '.db',
                    dbpassphrase=None,
                    nonthreaded_sql=False)
        a.createState(other_name=otherName,
                      mkey=hashlib.sha256(masterkey).digest(),
                      mode=False)
        rkey = b2a(a.state['DHRs']).strip()
        print "Send this ratchet key to your client: ", rkey
        print 'Server started'
        print 'Waiting for cients to connect...'

        s.bind((host, port))  # Bind to the port
        s.listen(3)  # Now wait for client connection.
        c, addr = s.accept()  # Establish connection with client.
        print 'Got connection from', addr
        secret = raw_input("Enter shared secret: ")
        smpr = smp.SMP(secret)
        buffer = c.recv(4096)[4:]

        buffer = smpr.step2(buffer)
        tempBuffer = padBytes(longToBytes(len(buffer) + 4), 4) + buffer
        c.send(tempBuffer)

        buffer = c.recv(4096)[4:]

        buffer = smpr.step4(buffer)
        tempBuffer = padBytes(longToBytes(len(buffer) + 4), 4) + buffer
        c.send(tempBuffer)

        if smpr.match:
            print "match"
        else:
            print "no match"
            s.close()
            sys.exit()

        chat_server = Chat_Server()
        chat_server.port = int(raw_input("Enter port to listen on: "))
        chat_server.start()
        text_input = Text_Input()
        text_input.start()

    elif mode == '-c':
        s = socket.socket()
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
                     1)  # Socket object
        host = '127.0.0.1'  # Get host name
        port = 8000
        # Reserve best port.
        myName = raw_input("What is your name: ")
        otherName = raw_input("What is the other name: ")
        masterkey = raw_input("what is your previously decided on master key"
                              )  # Reserve best port.
        rkey = raw_input(
            "what is the ratchet key you received from your partner:")
        print 'Connect to ', host, port
        s.connect((host, port))
        secret = raw_input("Enter shared secret: ")
        smpr = smp.SMP(secret)

        buffer = smpr.step1()
        #print "buffer = {}\n".format(  buffer )
        tempBuffer = padBytes(longToBytes(len(buffer) + 4), 4) + buffer

        s.send(tempBuffer)

        buffer = s.recv(4096)[4:]
        buffer = smpr.step3(buffer)
        tempBuffer = padBytes(longToBytes(len(buffer) + 4), 4) + buffer
        s.send(tempBuffer)

        buffer = s.recv(4096)[4:]
        smpr.step5(buffer)
        if smpr.match:
            print "match"
        else:
            print "no match"
            s.close()
            sys.exit()
        a = Axolotl(myName,
                    dbname=otherName + '.db',
                    dbpassphrase=None,
                    nonthreaded_sql=False)
        a.createState(other_name=otherName,
                      mkey=hashlib.sha256(masterkey).digest(),
                      mode=True,
                      other_ratchetKey=a2b(rkey))
        chat_client = Chat_Client()
        chat_client.host = raw_input("Enter host to connect to: ")
        chat_client.port = int(raw_input("Enter port to connect to: "))
        chat_client.start()
        text_input = Text_Input()
        text_input.start()
Пример #24
0
def axo(my_name, other_name, dbname, dbpassphrase):
    global a
    a = Axolotl(my_name, dbname=dbname, dbpassphrase=dbpassphrase,
                nonthreaded_sql=False)
    a.loadState(my_name, other_name)
Пример #25
0
#!/usr/bin/env python

import copy
import os
from pyaxo import Axolotl

name1 = 'Angie'
name2 = 'Barb'

a = Axolotl(name1, dbname='name1.db', dbpassphrase=None)
b = Axolotl(name2, dbname='name2.db', dbpassphrase=None)

a.loadState(name1, name2)
b.loadState(name2, name1)

topic = [
    '   My Name', 'Other Name', '        RK', '       HKs', '       HKr',
    '      NHKs', '      NHKr', '       CKs', '       CKr', ' DHIs_priv',
    '      DHIs', '      DHIr', ' DHRs_priv', '      DHRs', '      DHRr',
    '    CONVid', '        Ns', '        Nr', '       PNs', '   ratchet',
    '      mode'
]


def hilite(text, c=False):
    attr = []
    if c:
        attr.append('41')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), text)

Пример #26
0
#!/usr/bin/env python

import os
from pyaxo import Axolotl

# need clean database for this example to work
try:
    os.remove('./axolotl.db')
except OSError:
    pass

# create two instance classes with unencrypted database
a = Axolotl('Angie', dbpassphrase=None)
b = Axolotl('Barb', dbpassphrase=None)

# request a master key
mkey = raw_input('Provide a master key: ')

# initialize their states
a.createState(b.name, mkey, mode=True, other_ratchetKey=b.state['DHRs'])
b.createState(a.name, mkey, mode=False)

# tell who is who
if a.mode:
    print 'Angie is Alice-like'
    print 'Barb is Bob-like'
else:
    print 'Angie is Bob-like'
    print 'Barb is Alice-like'

# send some messages back and forth
Пример #27
0
def axolotl_b():
    return Axolotl('Barb', dbpassphrase=None)
Пример #28
0
#!/usr/bin/env python

from pyaxo import Axolotl
import sys

a = Axolotl('name1', dbname='name1.db', dbpassphrase=None)
a.loadState('name1', 'name2')

if sys.argv[1] == '-e':
    a.encrypt_file(sys.argv[2])
    print 'Encrypted file is ' + sys.argv[2] + '.asc'
else:
    a.decrypt_file(sys.argv[2])

a.saveState()
Пример #29
0
#!/usr/bin/env python

import os

from pyaxo import Axolotl


# start with a fresh database
try:
    os.remove('./alice.db')
    os.remove('./bob.db')
except OSError:
    pass

# unencrypted databases
a = Axolotl('alice', dbname='alice.db', dbpassphrase=None)
b = Axolotl('bob', dbname='bob.db', dbpassphrase=None)

a.initState('bob', b.state['DHIs'], b.handshakePKey,
            b.state['DHRs'], verify=False)
b.initState('alice', a.state['DHIs'], a.handshakePKey,
            a.state['DHRs'], verify=False)

a.saveState()
b.saveState()
Пример #30
0
        print 'Waiting for ' + OTHER_NICK + ' to connect...'
        with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((HOST, PORT))
            s.listen(1)
            conn, addr = s.accept()
            chatThread(conn)

    elif mode == '-c':
        HOST = raw_input('Enter the server: ')
        print 'Connecting to ' + HOST + '...'
        with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((HOST, PORT))
            chatThread(s)

    elif mode == '-g':
         a = Axolotl(NICK, dbname=OTHER_NICK+'.db')
         a.printKeys()

         ans = raw_input('Do you want to create a new Axolotl database? y/N ').strip()
         if ans == 'y':
             identity = raw_input('What is the identity key for the other party? ').strip()
             ratchet = raw_input('What is the ratchet key for the other party? ').strip()
             handshake = raw_input('What is the handshake key for the other party? ').strip()
             a.initState(OTHER_NICK, binascii.a2b_base64(identity), binascii.a2b_base64(handshake),
                         binascii.a2b_base64(ratchet))
             a.saveState()
             print 'The database for ' + NICK + ' -> ' + OTHER_NICK + ' has been saved.'
         else:
             print 'OK, nothing has been saved...'

    else:
Пример #31
0
#!/usr/bin/env python
"""
This program will encrypt or decrypt a file
"""

from pyaxo import Axolotl
import sys

your_name = raw_input('What is your name? ').strip()

# specify dbname with kwarg - default dbname is axolotl.db
# db passphrase will be prompted for - it can be specified here with dbpassprase kwarg
a = Axolotl(your_name, dbname=your_name + '.db')

try:
    if sys.argv[1] == '-e':
        other_name = \
            raw_input("What is the name of the party that you want to encrypt the file to? " ).strip()
        a.loadState(your_name, other_name)
        a.encrypt_file(sys.argv[2])
        print 'The encrypted file is: ' + sys.argv[2] + '.asc'
    else:
        other_name = \
            raw_input("What is the name of the party that you want to decrypt the file from? " ).strip()
        a.loadState(your_name, other_name)
        a.decrypt_file(sys.argv[2])
except IndexError:
    print 'Usage: ' + sys.argv[0] + ' -(e,d) <filename>'
    exit()
except KeyError:
    print 'The conversation ' + your_name + ' -> ' + other_name + \
Пример #32
0
#!/usr/bin/env python

"""
A three-toed Axolotl track ;-)
"""


from pyaxo import Axolotl

# create two instance classes
a = Axolotl('Angie')
b = Axolotl('Barb')

# initialize their states
a.initState('Barb', b.state['DHIs'], b.handshakePKey, b.state['DHRs'], verify=False)
b.initState('Angie', a.state['DHIs'], a.handshakePKey, a.state['DHRs'], verify=False)

# tell who is who
if a.mode:
    print 'Angie is Alice-like'
    print 'Barb is Bob-like'
else:
    print 'Angie is Bob-like'
    print 'Barb is Alice-like'

# Walk the three-toed Axolotl walk..
msg0 = a.encrypt('Step 1, Toe 1')
msg1 = a.encrypt('Step 1, Toe 2')
msg2 = a.encrypt('Step 1, Toe 3')
print 'b decrypt: ', b.decrypt(msg0)
print 'b decrypt: ', b.decrypt(msg1)
Пример #33
0
#!/usr/bin/env python

from pyaxo import Axolotl

argv = ['progname', '-e', 'testfile.md']

a = Axolotl('name1', dbname='name1.db', dbpassphrase=None)
a.loadState('name1', 'name2')

if argv[1] == '-e':
    a.encrypt_file(argv[2])
    print 'Encrypted file is ' + argv[2] + '.asc'
else:
    a.decrypt_file(argv[2])

a.saveState()
Пример #34
0
#!/usr/bin/env python

import os

from pyaxo import Axolotl

name1 = 'Angie'
name2 = 'Barb'

a = Axolotl(name1, dbname='name1.db', dbpassphrase=None)
b = Axolotl(name2, dbname='name2.db', dbpassphrase=None)

a.loadState(name1, name2)
b.loadState(name2, name1)

topic = ['   My Name',
         'Other Name',
         '        RK',
         '       HKs',
         '       HKr',
         '      NHKs',
         '      NHKr',
         '       CKs',
         '       CKr',
         ' DHIs_priv',
         '      DHIs',
         '      DHIr',
         ' DHRs_priv',
         '      DHRs',
         '      DHRr',
         '    CONVid',
Пример #35
0
def threaded_axolotl_b():
    return Axolotl('Barb', dbpassphrase=None, nonthreaded_sql=False)
Пример #36
0
def axo(my_name, other_name, dbname, dbpassphrase):
    a = Axolotl(my_name, dbname=dbname, dbpassphrase=dbpassphrase)
    a.loadState(my_name, other_name)
    yield a
    a.saveState()
Пример #37
0
    except:
        usage()

    NICK = raw_input('Enter your nick: ')
    OTHER_NICK = 'x'
    winlock = threading.Lock()
    transferlock = threading.Lock()
    cryptlock = threading.Lock()
    screen_needs_update = False
    HOST = '127.0.0.1'
    PORT=50000
    mkey = getpass('What is the masterkey (format: NNN-xxxx)? ')

    if mode == '-s':
        axolotl = Axolotl(NICK,
                    dbname=OTHER_NICK+'.db',
                    dbpassphrase=None,
                    nonthreaded_sql=False)
        axolotl.createState(other_name=OTHER_NICK,
                           mkey=hash_(mkey),
                           mode=False)
        tor_process = tor(TOR_SERVER_PORT,
                          TOR_SERVER_CONTROL_PORT,
                          '/tmp/tor.server',
                          '')
        hs, cookie, onion = ephemeralHiddenService()
        print 'Exchanging credentials via tor...'
        if credentialsSend(mkey,
                           cookie,
                           b2a(axolotl.state['DHRs']).strip(),
                           onion):
            pass
Пример #38
0
#!/usr/bin/env python

import os
from pyaxo import Axolotl

# need clean database for this example to work
try:
    os.remove('./axolotl.db')
except OSError:
    pass

# create two instance classes with unencrypted database
a = Axolotl('Angie', dbpassphrase=None)
b = Axolotl('Barb', dbpassphrase=None)

# initialize their states
a.initState('Barb', b.state['DHIs'], b.handshakePKey, b.state['DHRs'], verify=False)
b.initState('Angie', a.state['DHIs'], a.handshakePKey, a.state['DHRs'], verify=False)

# tell who is who
if a.mode:
    print 'Angie is Alice-like'
    print 'Barb is Bob-like'
else:
    print 'Angie is Bob-like'
    print 'Barb is Alice-like'

# send some messages back and forth
msg0 = a.encrypt('message 0')
msg1 = a.encrypt('message 1')
msg2 = b.encrypt('message 2')
Пример #39
0
def encrypt(data, msgtype, servername, args):
    global encrypted
    pre, message = string.split(args, ":", 1)
    prestr = pre.split(" ")
    username = prestr[-2]
    buf = weechat.current_buffer()
    nick = weechat.buffer_get_string(buf, 'localvar_nick')
    if os.path.exists(weechat_dir + '/' + username + '.db'):

        a = Axolotl(nick,
                    dbname=weechat_dir + '/' + username + '.db',
                    dbpassphrase=getPasswd(username))
        a.loadState(nick, username)
        encrypted = a.encrypt(message)
        if encrypted == '':
            return args
        encrypted = b2a_base64(encrypted)
        a.saveState()
        del a
        encrypted = encrypted.replace("\n", "")
        final_msg = pre + ":" + encrypted
        if len(encrypted) > 400:
            # I arrived at this next equation heuristically. If it doesn't work, let me know
            # and I will work on it some more. -DRA
            numsplits = 2 * int(len(encrypted) / 400) + 1
            splitmsg = string.split(message, " ")
            cutpoint = int(len(splitmsg) / numsplits)
            encrypted_list = []
            for i in range(numsplits + 1):
                if min((i + 1) * cutpoint,
                       len(splitmsg)) == (i + 1) * cutpoint:
                    segment = string.join(
                        splitmsg[i * cutpoint:(i + 1) * cutpoint], " ") + "\n"
                    a = Axolotl(nick,
                                dbname=weechat_dir + '/' + username + '.db',
                                dbpassphrase=getPasswd(username))
                    a.loadState(nick, username)
                    encrypted = b2a_base64(a.encrypt(segment))
                    a.saveState()
                    del a
                    valid_segment = True
                else:
                    segment = string.join(splitmsg[i * cutpoint:], " ")
                    if segment.strip() is None or len(segment) == 0:
                        valid_segment = False
                    else:
                        a = Axolotl(nick,
                                    dbname=weechat_dir + '/' + username +
                                    '.db',
                                    dbpassphrase=getPasswd(username))
                        a.loadState(nick, username)
                        encrypted = b2a_base64(a.encrypt(segment))
                        a.saveState()
                        del a
                        valid_segment = True
                encrypted = encrypted.replace("\n", "")
                if valid_segment:
                    encrypted_list += [encrypted]
            final_msg = ''
            for item in encrypted_list:
                final_msg = final_msg + pre + ":" + item + '\n'
        return final_msg
        return encrypted
    else:
        return args
Пример #40
0
#!/usr/bin/env python

import os

from pyaxo import Axolotl


# need clean database for this example to work
try:
    os.remove('./axolotl.db')
except OSError:
    pass

# create two instance classes with database passphrase specified as kwarg
a = Axolotl('Angie', dbpassphrase='123')
b = Axolotl('Barb', dbpassphrase='123')

# initialize their states
a.initState('Barb', b.state['DHIs'], b.handshakePKey, b.state['DHRs'],
            verify=False)
b.initState('Angie', a.state['DHIs'], a.handshakePKey, a.state['DHRs'],
            verify=False)

# tell who is who
if a.mode:
    print 'Angie is Alice-like'
    print 'Barb is Bob-like'
else:
    print 'Angie is Bob-like'
    print 'Barb is Alice-like'
Пример #41
0
    except:
        usage()

    NICK = raw_input('Enter your nick: ')
    OTHER_NICK = 'x'
    winlock = threading.Lock()
    transferlock = threading.Lock()
    cryptlock = threading.Lock()
    screen_needs_update = False
    HOST = '127.0.0.1'
    PORT = 50000
    mkey = getpass('What is the masterkey (format: NNN-xxxx)? ')

    if mode == '-s':
        axolotl = Axolotl(NICK,
                          dbname=OTHER_NICK + '.db',
                          dbpassphrase=None,
                          nonthreaded_sql=False)
        axolotl.createState(other_name=OTHER_NICK,
                            mkey=hash_(mkey),
                            mode=False)
        tor_process = tor(TOR_SERVER_PORT, TOR_SERVER_CONTROL_PORT,
                          '/tmp/tor.server', '')
        hs, cookie, onion = ephemeralHiddenService()
        print 'Exchanging credentials via tor...'
        if credentialsSend(mkey, cookie,
                           b2a(axolotl.state['DHRs']).strip(), onion):
            pass
        else:
            sys.exit(1)
        print 'Credentials sent, waiting for the other party to connect...'
        with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s:
Пример #42
0
def axo(my_name, other_name, dbname, dbpassphrase):
    a = Axolotl(my_name, dbname=dbname, dbpassphrase=dbpassphrase)
    a.loadState(my_name, other_name)
    yield a
    a.saveState()
Пример #43
0
    def test_persist_skipped_mk(
            self, a_identity_keys, a_handshake_keys, a_ratchet_keys,
            b_identity_keys, b_handshake_keys, b_ratchet_keys):
        a = Axolotl('angie', dbname=self.dbs[0], dbpassphrase=self.dbs[0])
        b = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1])

        conv_a = a.init_conversation(
            b.name,
            priv_identity_key=a_identity_keys.priv,
            identity_key=a_identity_keys.pub,
            priv_handshake_key=a_handshake_keys.priv,
            other_identity_key=b_identity_keys.pub,
            other_handshake_key=b_handshake_keys.pub,
            priv_ratchet_key=a_ratchet_keys.priv,
            ratchet_key=a_ratchet_keys.pub,
            other_ratchet_key=b_ratchet_keys.pub)

        conv_b = b.init_conversation(
            a.name,
            priv_identity_key=b_identity_keys.priv,
            identity_key=b_identity_keys.pub,
            priv_handshake_key=b_handshake_keys.priv,
            other_identity_key=a_identity_keys.pub,
            other_handshake_key=a_handshake_keys.pub,
            priv_ratchet_key=b_ratchet_keys.priv,
            ratchet_key=b_ratchet_keys.pub,
            other_ratchet_key=a_ratchet_keys.pub)

        pt = [utils.PLAINTEXT.format(i) for i in range(5)]
        ct = list()

        utils.encrypt(conv_a, 0, pt, ct)
        utils.decrypt(conv_b, 0, pt, ct)
        utils.encrypt(conv_a, 1, pt, ct)
        utils.encrypt(conv_a, 2, pt, ct)
        utils.decrypt(conv_b, 2, pt, ct)
        utils.encrypt(conv_a, 3, pt, ct)
        utils.encrypt(conv_a, 4, pt, ct)
        utils.decrypt(conv_b, 4, pt, ct)

        # make sure there are staged skipped keys
        assert conv_b.staged_hk_mk

        # save the database, copy the staged keys dict and delete the objects
        conv_b.save()
        persisted_hk_mk = deepcopy(conv_b.staged_hk_mk)
        del b, conv_b

        # load the conversation from disk
        B = Axolotl('barb', dbname=self.dbs[1], dbpassphrase=self.dbs[1])
        conv_B = B.load_conversation(a.name)

        # assert both dicts have the same content
        assert conv_B.staged_hk_mk.keys() == persisted_hk_mk.keys()
        for mk in conv_B.staged_hk_mk:
            assert conv_B.staged_hk_mk[mk].mk == persisted_hk_mk[mk].mk
            assert conv_B.staged_hk_mk[mk].hk == persisted_hk_mk[mk].hk
            assert (conv_B.staged_hk_mk[mk].timestamp ==
                    persisted_hk_mk[mk].timestamp)

        # decrypt the skipped messages
        utils.decrypt(conv_B, 1, pt, ct)
        utils.decrypt(conv_B, 3, pt, ct)
Пример #44
0
#!/usr/bin/env python

import binascii
import os
from pyaxo import Axolotl

# need clean database for this example to work
try:
    os.remove('./axolotl.db')
except OSError:
    pass

# create three instance classes - axolotl will prompt for database passphrases
# Note that dick and harry's passphrases must match or harry won't be able to
# load dick's saved database
tom = Axolotl('Tom')
dick = Axolotl('Dick')
harry = Axolotl('Harry')

# initialize Tom and Dick's states
tom.initState('Dick', dick.state['DHIs'], dick.handshakePKey, dick.state['DHRs'], verify=False)
dick.initState('Tom', tom.state['DHIs'], tom.handshakePKey, tom.state['DHRs'], verify=False)

# tell who is who
if tom.mode:
    print 'Tom is Alice-like'
    print 'Dick is Bob-like'
else:
    print 'Tom is Bob-like'
    print 'Dick is Alice-like'
Пример #45
0
    def test_passphrase(self, passphrase_0, passphrase_1):
        a = Axolotl('Angie', dbpassphrase=passphrase_0)
        b = Axolotl('Barb', dbpassphrase=None)

        a.initState(other_name=b.name,
                    other_identityKey=b.state['DHIs'],
                    other_handshakeKey=b.handshakePKey,
                    other_ratchetKey=b.state['DHRs'],
                    verify=False)
        a.saveState()

        if passphrase_0 == passphrase_1:
            a = Axolotl('Angie', dbpassphrase=passphrase_1)
            assert isinstance(a.db, sqlite3.Connection)
        else:
            with pytest.raises(SystemExit):
                a = Axolotl('Angie', dbpassphrase=passphrase_1)
Пример #46
0
#!/usr/bin/env python

from pyaxo import Axolotl
import sys
import os

# start with a fresh database
try:
    os.remove('./name1.db')
    os.remove('./name2.db')
except OSError:
    pass

# unencrypted databases
a = Axolotl('name1', dbname='name1.db', dbpassphrase=None)
b = Axolotl('name2', dbname='name2.db', dbpassphrase=None)

a.initState('name2', b.state['DHIs'], b.handshakePKey, b.state['DHRs'], verify=False)
b.initState('name1', a.state['DHIs'], a.handshakePKey, a.state['DHRs'], verify=False)

a.saveState()
b.saveState()
Пример #47
0
name. Each conversation should have a unique other person's name. Your name can be
the same for each conversation or different for each one or any combination.

If you decide not to complete the initialization process, just answer no to the
question about creating a new conversation. Nothing will be saved.

If you want to reinitialize a conversation, just run the script again.
The old conversation key data will be overwritten in the database.
"""

import sys
import binascii
from pyaxo import Axolotl

your_name = raw_input('Your name for this conversation? ').strip()
a = Axolotl(your_name)
a.printKeys()

ans = raw_input('Do you want to create a new conversation? y/N ').strip()
if ans == 'y':
    other_name = raw_input('What is the name of the other party? ').strip()
    identity = raw_input(
        'What is the identity key for the other party? ').strip()
    handshake = raw_input(
        'What is the handshake key for the other party? ').strip()
    ratchet = raw_input(
        'What is the ratchet key for the other party? ').strip()
    a.initState(other_name, binascii.a2b_base64(identity),
                binascii.a2b_base64(handshake), binascii.a2b_base64(ratchet))
    a.saveState()
    print 'The conversation ' + your_name + ' -> ' + other_name + ' has been saved.'
Пример #48
0
should have a unique other person's name.

If you decide not to complete the initialization process, just answer no to the
question about creating a new conversation. Nothing will be saved.

If you want to reinitialize a conversation, just run the script again.
The old conversation key data will be overwritten in the databases.
"""

import sys
import binascii
from pyaxo import Axolotl

your_name = raw_input('Your name for this conversation? ').strip()
other_name = raw_input('What is the name of the other party? ').strip()
a = Axolotl(your_name, dbname=your_name + '.db')
b = Axolotl(other_name, dbname=other_name + '.db')
a.initState(other_name,
            b.state['DHIs'],
            b.handshakePKey,
            b.state['DHRs'],
            verify=False)
b.initState(your_name,
            a.state['DHIs'],
            a.handshakePKey,
            a.state['DHRs'],
            verify=False)

a.saveState()
b.saveState()
print 'The conversation ' + your_name + ' -> ' + other_name + ' has been saved in: ' + your_name + '.db'
Пример #49
0
def encrypt(data, msgtype, servername, args):
  global encrypted
  pre, message = string.split(args, ":", 1)
  prestr=pre.split(" ")
  username=prestr[-2]
  buf = weechat.current_buffer()
  nick = weechat.buffer_get_string(buf, 'localvar_nick')
  if os.path.exists(weechat_dir + '/' + username + '.db'):

    a = Axolotl(nick, dbname=weechat_dir+'/'+username+'.db', dbpassphrase=getPasswd(username))
    a.loadState(nick, username)
    encrypted = a.encrypt(message)
    if encrypted == '':
        return args
    encrypted = b2a_base64(encrypted)
    a.saveState()
    del a
    encrypted = encrypted.replace("\n","")
    final_msg = pre + ":" +encrypted
    if len(encrypted) > 400:
      # I arrived at this next equation heuristically. If it doesn't work, let me know
      # and I will work on it some more. -DRA
      numsplits = 2*int(len(encrypted)/400) + 1
      splitmsg=string.split(message," ")
      cutpoint=int(len(splitmsg)/numsplits)
      encrypted_list = []
      for i in range(numsplits+1):
        if min((i+1)*cutpoint, len(splitmsg)) == (i+1)*cutpoint:
          segment = string.join(splitmsg[i*cutpoint:(i+1)*cutpoint]," ") + "\n"
          a = Axolotl(nick, dbname=weechat_dir+'/'+username+'.db', dbpassphrase=getPasswd(username))
          a.loadState(nick, username)
          encrypted = b2a_base64(a.encrypt(segment))
          a.saveState()
          del a
          valid_segment = True
        else:
          segment = string.join(splitmsg[i*cutpoint:]," ")
          if segment.strip() is None or len(segment) == 0:
            valid_segment = False
          else:
            a = Axolotl(nick, dbname=weechat_dir+'/'+username+'.db', dbpassphrase=getPasswd(username))
            a.loadState(nick, username)
            encrypted = b2a_base64(a.encrypt(segment))
            a.saveState()
            del a
            valid_segment = True
        encrypted = encrypted.replace("\n","")
        if valid_segment:
          encrypted_list += [encrypted]
      final_msg = ''
      for item in encrypted_list:
        final_msg = final_msg + pre + ":" + item + '\n'
    return final_msg
    return encrypted
  else:
    return args
Пример #50
0
def axolotl_a():
    return Axolotl('Angie', dbpassphrase=None)
Пример #51
0
name. Each conversation should have a unique other person's name. Your name can be
the same for each conversation or different for each one or any combination.

If you decide not to complete the initialization process, just answer no to the
question about creating a new conversation. Nothing will be saved.

If you want to reinitialize a conversation, just run the script again.
The old conversation key data will be overwritten in the database.
"""

import sys
import binascii
from pyaxo import Axolotl

your_name = raw_input('Your name for this conversation? ').strip()
a = Axolotl(your_name)
a.printKeys()

ans = raw_input('Do you want to create a new conversation? y/N ').strip()
if ans == 'y':
    other_name = raw_input('What is the name of the other party? ').strip()
    identity = raw_input('What is the identity key for the other party? ').strip()
    handshake = raw_input('What is the handshake key for the other party? ').strip()
    ratchet = raw_input('What is the ratchet key for the other party? ').strip()
    a.initState(other_name, binascii.a2b_base64(identity), binascii.a2b_base64(handshake),
                binascii.a2b_base64(ratchet))
    a.saveState()
    print 'The conversation ' + your_name + ' -> ' + other_name + ' has been saved.'
else:
    print 'OK, nothing has been saved...'
Пример #52
0
def main():
    global lock, screen_needs_update, NICK, OTHER_NICK
    mode = None
    try:
        mode = sys.argv[1]
    except:
        usage()

    NICK = raw_input("Enter your nick: ")
    OTHER_NICK = raw_input("Enter the nick of the other party: ")
    lock = threading.Lock()
    screen_needs_update = False
    host = ""
    port = 50000
    while True:
        try:
            if mode == "-g":
                port = 50000  # dummy assignment
                break
            port = raw_input("TCP port (1 for random choice, 50000 is default): ")
            port = int(port)
            break
        except ValueError:
            break

    if 1025 <= port <= 65535:
        pass
    elif port == 1:
        port = 1025 + randint(0, 64510)
        print("PORT is " + str(port))

    if mode == "-s":
        print("Waiting for " + OTHER_NICK + " to connect...")
        with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((host, port))
            s.listen(1)
            conn, addr = s.accept()
            chat_thread(conn)

    elif mode == "-c":
        host = raw_input("Enter the server: ")
        print("Connecting to " + host + "...")
        with socketcontext(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((host, port))
            chat_thread(s)

    elif mode == "-g":
        a = Axolotl(NICK, dbname=OTHER_NICK + ".db")
        a.printKeys()

        ans = raw_input("Do you want to create a new Axolotl database? y/N ").strip()
        if ans == "y":
            identity = raw_input("What is the identity key for the other party? ").strip()
            ratchet = raw_input("What is the ratchet key for the other party? ").strip()
            handshake = raw_input("What is the handshake key for the other party? ").strip()
            a.initState(
                OTHER_NICK, binascii.a2b_base64(identity), binascii.a2b_base64(handshake), binascii.a2b_base64(ratchet)
            )
            a.saveState()
            print("The database for " + NICK + " -> " + OTHER_NICK + " has been saved.")
        else:
            print("OK, nothing has been saved...")

    else:
        usage()