示例#1
0
文件: server.py 项目: wmenjoy/sesto
def on_new_file(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    d = get_data_by_id(msg[1])
    if d is None:
        logger.info("not found", msg[1])
        return False
    try:
        sc = scell.scell_seal(msg[2].encode("UTF-8"))
        d = base64.b64decode(sc.decrypt(d[0], msg[3].encode("UTF-8")))
        jj = json.loads(d.decode("UTF-8"))
        new_id, new_pass = new_file(msg[3])
        jj["context"].append({
            "type": "file",
            "name": "New File",
            "desc": "new file",
            "id": new_id,
            "password": new_pass
        })
        update_data_by_id(
            msg[1],
            sc.encrypt(base64.b64encode(json.dumps(jj).encode("UTF-8")),
                       msg[3].encode("UTF-8")))
        ws_response.send_str(
            base64.b64encode(
                session.wrap("NEW_FILE {}".format(new_id).encode(
                    "UTF-8"))).decode("UTF-8"))
        return True
    except Exception:
        logger.info("decription_error")
    return False
示例#2
0
def new_file(context):
    c = dbconn.cursor();
    passwd=generate_pass();
    enc=scell.scell_seal(passwd.encode("UTF-8"));
    c.execute("INSERT INTO data (data) VALUES (?)", [sqlite3.Binary(enc.encrypt(base64.b64encode(b"{ \"type\":\"file\",\"name\": \"File\", \"desc\":\"file\",\"context\": []}"), context.encode('utf8'))), ] );
    dbconn.commit()
    return c.lastrowid, passwd;
示例#3
0
文件: server.py 项目: wmenjoy/sesto
def on_update_message(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    try:
        sc = scell.scell_seal(msg[2].encode("UTF-8"))
        d = sc.encrypt(msg[4].encode("UTF-8"), msg[3].encode("UTF-8"))
        update_data_by_id(msg[1], d)
        return True
    except Exception:
        logger.info("decription_error")
    return False
示例#4
0
def on_update_message(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    try:
        sc = scell.scell_seal(msg[2].encode("UTF-8"))
        d=sc.encrypt(msg[4].encode("UTF-8"), msg[3].encode("UTF-8"));
        update_data_by_id(msg[1], d)
        return True
    except Exception:
        logger.info("decription_error")
    return False
示例#5
0
def on_auth2_message(msg, ws_response, session, comparator):
    try:
        data = base64.b64encode(comparator.proceed_compare(base64.b64decode(msg[2]))).decode("UTF-8");
        sc = scell.scell_seal(get_user_password(msg[1])[0].encode("UTF-8"))
        rr = int.from_bytes((sc.decrypt(get_user_root_id(msg[1]),msg[1].encode("UTF-8"))), byteorder='big');
        if comparator.result() != scomparator.SCOMPARATOR_CODES.NOT_MATCH:
            ws_response.send_str(base64.b64encode(session.wrap(("AUTH2 "+data+" "+str(rr)).encode("UTF-8"))).decode("UTF-8"));
            return True;
    except Exception:
        a=1
    ws_response.send_str(base64.b64encode(session.wrap(b"INVALID_LOGIN")).decode("UTF-8"));
    return False
示例#6
0
文件: server.py 项目: wmenjoy/sesto
def new_file(context):
    c = dbconn.cursor()
    passwd = generate_pass()
    enc = scell.scell_seal(passwd.encode("UTF-8"))
    c.execute("INSERT INTO data (data) VALUES (?)", [
        sqlite3.Binary(
            enc.encrypt(
                base64.b64encode(
                    b"{ \"type\":\"file\",\"name\": \"File\", \"desc\":\"file\",\"context\": []}"
                ), context.encode('utf8'))),
    ])
    dbconn.commit()
    return c.lastrowid, passwd
示例#7
0
def on_get_context_info(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    jj=json.loads(base64.b64decode(msg[2]).decode("UTF-8"));
    res="{\"context\":["
    for ctx in jj["context_info"]:
        sc=scell.scell_seal(ctx["password"].encode("UTF-8"));
        d=json.loads(base64.b64decode(sc.decrypt(get_data_by_id(ctx["id"])[0],msg[1].encode("UTF-8"))).decode("UTF-8"));
        res+="{\"name\":\""+d["name"]+"\",\"desc\":\""+d["desc"]+"\",\"id\":"+str(ctx["id"])+"}"
        if ctx != jj["context_info"][-1]:
            res+=",";
    res+="]}";
    ws_response.send_str(base64.b64encode(session.wrap("GET_CONTEXT {}".format(base64.b64encode(res.encode("UTF-8")).decode("UTF-8")).encode("UTF-8"))).decode("UTF-8"));
    return True;
示例#8
0
def on_get_message(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    d=get_data_by_id(msg[1])
    if d is None:
        logger.info("not found", msg[1])
        return False;
    try:
        sc = scell.scell_seal(msg[2].encode("UTF-8"))
        d=sc.decrypt(d[0], msg[3].encode("UTF-8"));
        ws_response.send_str(base64.b64encode(session.wrap("GET {} {}".format(msg[1], d.decode("UTF-8")).encode("UTF-8"))).decode("UTF-8"));
        return True
    except Exception:
        logger.info("decription_error")
    return False
示例#9
0
文件: server.py 项目: wmenjoy/sesto
def on_get_message(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    d = get_data_by_id(msg[1])
    if d is None:
        logger.info("not found", msg[1])
        return False
    try:
        sc = scell.scell_seal(msg[2].encode("UTF-8"))
        d = sc.decrypt(d[0], msg[3].encode("UTF-8"))
        ws_response.send_str(
            base64.b64encode(
                session.wrap("GET {} {}".format(
                    msg[1],
                    d.decode("UTF-8")).encode("UTF-8"))).decode("UTF-8"))
        return True
    except Exception:
        logger.info("decription_error")
    return False
示例#10
0
文件: server.py 项目: wmenjoy/sesto
def on_auth2_message(msg, ws_response, session, comparator):
    try:
        data = base64.b64encode(
            comparator.proceed_compare(base64.b64decode(
                msg[2]))).decode("UTF-8")
        sc = scell.scell_seal(get_user_password(msg[1])[0].encode("UTF-8"))
        rr = int.from_bytes(
            (sc.decrypt(get_user_root_id(msg[1]), msg[1].encode("UTF-8"))),
            byteorder='big')
        if comparator.result() != scomparator.SCOMPARATOR_CODES.NOT_MATCH:
            ws_response.send_str(
                base64.b64encode(
                    session.wrap(("AUTH2 " + data + " " +
                                  str(rr)).encode("UTF-8"))).decode("UTF-8"))
            return True
    except Exception:
        a = 1
    ws_response.send_str(
        base64.b64encode(session.wrap(b"INVALID_LOGIN")).decode("UTF-8"))
    return False
示例#11
0
def on_new_file(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    d=get_data_by_id(msg[1])    
    if d is None:
        logger.info("not found", msg[1])
        return False;
    try:
        sc = scell.scell_seal(msg[2].encode("UTF-8"))
        d=base64.b64decode(sc.decrypt(d[0], msg[3].encode("UTF-8")));
        jj=json.loads(d.decode("UTF-8"));
        new_id, new_pass=new_file(msg[3]);
        jj["context"].append({"type":"file", "name":"New File","desc":"new file", "id":new_id, "password":new_pass})
        update_data_by_id(msg[1], sc.encrypt(base64.b64encode(json.dumps(jj).encode("UTF-8")), msg[3].encode("UTF-8")))
        ws_response.send_str(base64.b64encode(session.wrap("NEW_FILE {}".format(new_id).encode("UTF-8"))).decode("UTF-8"));
        return True;
    except Exception:
        logger.info("decription_error")
    return False
示例#12
0
def on_del(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    d=get_data_by_id(msg[1])    
    if d is None:
        logger.info("not found", msg[1])
        return False;
    try:
        sc = scell.scell_seal(msg[3].encode("UTF-8"))
        d=base64.b64decode(sc.decrypt(d[0], msg[4].encode("UTF-8")));
        jj=json.loads(d.decode("UTF-8"));
        for a in jj["context"]:
            if a["id"] == int(msg[2]):
                jj["context"].remove(a);
        update_data_by_id(msg[1], sc.encrypt(base64.b64encode(json.dumps(jj).encode("UTF-8")), msg[4].encode("UTF-8")))
        del_by_id(int(msg[2]));
        return True;
    except Exception:
      logger.info("decription_error")
    return False
示例#13
0
文件: server.py 项目: wmenjoy/sesto
def on_del(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    d = get_data_by_id(msg[1])
    if d is None:
        logger.info("not found", msg[1])
        return False
    try:
        sc = scell.scell_seal(msg[3].encode("UTF-8"))
        d = base64.b64decode(sc.decrypt(d[0], msg[4].encode("UTF-8")))
        jj = json.loads(d.decode("UTF-8"))
        for a in jj["context"]:
            if a["id"] == int(msg[2]):
                jj["context"].remove(a)
        update_data_by_id(
            msg[1],
            sc.encrypt(base64.b64encode(json.dumps(jj).encode("UTF-8")),
                       msg[4].encode("UTF-8")))
        del_by_id(int(msg[2]))
        return True
    except Exception:
        logger.info("decription_error")
    return False
示例#14
0
文件: server.py 项目: wmenjoy/sesto
def on_get_context_info(msg, ws_response, session, is_authorized):
    if not is_authorized:
        logger.info("not_authorized")
        return False
    jj = json.loads(base64.b64decode(msg[2]).decode("UTF-8"))
    res = "{\"context\":["
    for ctx in jj["context_info"]:
        sc = scell.scell_seal(ctx["password"].encode("UTF-8"))
        d = json.loads(
            base64.b64decode(
                sc.decrypt(
                    get_data_by_id(ctx["id"])[0],
                    msg[1].encode("UTF-8"))).decode("UTF-8"))
        res += "{\"name\":\"" + d["name"] + "\",\"desc\":\"" + d[
            "desc"] + "\",\"id\":" + str(ctx["id"]) + "}"
        if ctx != jj["context_info"][-1]:
            res += ","
    res += "]}"
    ws_response.send_str(
        base64.b64encode(
            session.wrap("GET_CONTEXT {}".format(
                base64.b64encode(res.encode("UTF-8")).decode("UTF-8")).encode(
                    "UTF-8"))).decode("UTF-8"))
    return True
示例#15
0
 def testSealWithContext(self):
     with self.assertRaises(themis_exception):
         scell.scell_seal("")
     with self.assertRaises(TypeError):
         scell.scell_seal(None)
     with self.assertRaises(TypeError):
         scell.scell_seal(112233)
     enc = scell.scell_seal(self.key)
     with self.assertRaises(themis_exception):
         enc.encrypt("", self.context)
     with self.assertRaises(TypeError):
         enc.encrypt(None, self.context)
     encrypted_message = enc.encrypt(self.message, self.context)
     with self.assertRaises(themis_exception):
         enc.decrypt(b"".join([encrypted_message, b"11"]), self.context)
     with self.assertRaises(themis_exception):
         enc.decrypt(encrypted_message)
     with self.assertRaises(themis_exception):
         enc.decrypt(encrypted_message, None)
     with self.assertRaises(themis_exception):
         enc.decrypt(encrypted_message, b"".join([self.context, b"11"]))
     decrypted_message = enc.decrypt(encrypted_message, self.context)
     self.assertEqual(self.message, decrypted_message)
示例#16
0
 def testSealWithContext(self):
     with self.assertRaises(themis_exception):
         scell.scell_seal("")
     with self.assertRaises(TypeError):
         scell.scell_seal(None)
     with self.assertRaises(TypeError):
         scell.scell_seal(112233)
     enc = scell.scell_seal(self.key)
     with self.assertRaises(themis_exception):
         enc.encrypt("", self.context)
     with self.assertRaises(TypeError):
         enc.encrypt(None, self.context)
     encrypted_message = enc.encrypt(self.message, self.context)
     with self.assertRaises(themis_exception):
         enc.decrypt(b"".join([encrypted_message, b"11"]), self.context)
     with self.assertRaises(themis_exception):
         enc.decrypt(encrypted_message)
     with self.assertRaises(themis_exception):
         enc.decrypt(encrypted_message, None)
     with self.assertRaises(themis_exception):
         enc.decrypt(encrypted_message, b"".join([self.context, b"11"]))
     decrypted_message = enc.decrypt(encrypted_message, self.context)
     self.assertEqual(self.message, decrypted_message)
    else:
        if node.text != None:
            node.text = base64.b64encode(
                enc.encrypt(node.text, context + "/" + node.tag))
            #encrypt leaf data and replace it in file by base64 encoding


def dec_children(node, context):
    if len(node) != 0:
        for i in range(0, len(node)):
            dec_children(node[i], context + "/" + node.tag)
    else:
        if node.text != None:
            node.text = enc.decrypt(base64.b64decode(node.text),
                                    context + "/" + node.tag)
            #decrypt base64 encoded leaf data and replace it by plain value


#encoding file data.xml and save result to encoded_data.xml
tree = ET.parse('data.xml')
root = tree.getroot()
enc = scell.scell_seal(password)
enc_children(root, "")
tree.write("encoded_data.xml")

#decoding file encoded_data.xml and save result to decoded_data.xml
tree2 = ET.parse('encoded_data.xml')
root2 = tree2.getroot()
dec_children(root2, "")
tree2.write("decoded_data.xml")
示例#18
0
文件: add_user.py 项目: wmenjoy/sesto
import sqlite3
import sys
from pythemis import scell
import binascii
import base64

if len(sys.argv) != 3:
    print("Usage: add_user.py <username> <password>");
    exit();

dbconn = sqlite3.connect('sesto.db');
c = dbconn.cursor()

try:
    c = dbconn.cursor()
    # Create table
    c.execute('''CREATE TABLE users (user text, password text, root_id blob)''');
    c.execute('''CREATE TABLE data (id INTEGER PRIMARY KEY AUTOINCREMENT, data blob)''');
    dbconn.commit()
except sqlite3.OperationalError:
    a=1;

c.execute('SELECT user FROM users WHERE user=?', [sys.argv[1]]);
if c.fetchone() is not None:
    print("User with name \"{}\" is always present in db".format(sys.argv[1]))
else:
    enc=scell.scell_seal(sys.argv[2].encode('utf8'))
    c.execute("INSERT INTO data (data) VALUES (?)", [sqlite3.Binary(enc.encrypt(base64.b64encode(b"{ \"type\":\"folder\",\"name\": \"root\", \"desc\":\"root folder\",\"context\": []}"), sys.argv[1].encode('utf8'))), ] );
    c.execute("Insert INTO users (user, password, root_id) VALUES (?, ?, ?)", [sys.argv[1], sys.argv[2], sqlite3.Binary(enc.encrypt(c.lastrowid.to_bytes(4, byteorder='big'), sys.argv[1].encode('utf8'))), ]);
    dbconn.commit()
    print("user \"{}\" added successfully".format(sys.argv[1]));
def enc_children(node, context):
    if len(node)!=0:
        for i in range(0, len(node)):
            enc_children(node[i], context+"/"+node.tag);
    else:
        if node.text!=None:
            node.text=base64.b64encode(enc.encrypt(node.text, context+"/"+node.tag)); #encrypt leaf data and replace it in file by base64 encoding

def dec_children(node, context):
    if len(node)!=0:
        for i in range(0, len(node)):
            dec_children(node[i], context+"/"+node.tag);
    else:
        if node.text!=None:
            node.text=enc.decrypt(base64.b64decode(node.text), context+"/"+node.tag); #decrypt base64 encoded leaf data and replace it by plain value

#encoding file data.xml and save result to encoded_data.xml
tree = ET.parse('data.xml');
root = tree.getroot();
enc=scell.scell_seal(password);
enc_children(root, "");
tree.write("encoded_data.xml");

#decoding file encoded_data.xml and save result to decoded_data.xml
tree2 = ET.parse('encoded_data.xml');
root2 = tree2.getroot();
dec_children(root2, "");
tree2.write("decoded_data.xml");

示例#20
0
import postgresql
from pythemis import scell

#connect to bd
db = postgresql.open('pq://localhost:5432/test')

#load module
db.execute("CREATE EXTENSION IF NOT EXISTS pg_themis")

#scell encrypt by pg_themis
stmt = db.prepare("select pg_themis_scell_encrypt_seal($1::bytea, $2::bytea)")
enc_data = stmt.first(b"data", b"password")
print(enc_data)

#scell decrypt by pythemis
enc = scell.scell_seal(b"password")
data = enc.decrypt(enc_data)
print(data)

#scell encrypt by pythemis
enc_data = enc.encrypt(b"data2")
print(enc_data)

#scell decrypt by pg_themis
stmt = db.prepare("select pg_themis_scell_decrypt_seal($1::bytea, $2::bytea)")
print(stmt.first(enc_data, b"password"))


#smessage encrypt 
stmt = db.prepare("select pg_themis_smessage_encrypt($1::bytea, $2::bytea)")
enc_data = stmt.first(b"data", b"\x55\x45\x43\x32\x00\x00\x00\x2d\x6b\xbb\x79\x79\x03\xfa\xb7\x33\x3a\x4d\x6e\xb7\xc2\x59\xde\x78\x96\xfa\x69\xe6\x63\x86\x91\xc2\x65\xa0\x92\xf6\x5a\x22\x3c\xa9\x8e\xc9\xa7\x35\x42")