Exemplo n.º 1
0
Arquivo: simple.py Projeto: l-n-s/sjcl
 def test_encrypt_decrypt(self):
     message = b"secret message to encrypt"
     cyphertext = SJCL().encrypt(message, "shared_secret")
     self.assertEqual(
         SJCL().decrypt(cyphertext, "shared_secret"),
         message
     )
Exemplo n.º 2
0
    def _decryptV1(self):
        from sjcl import SJCL
        from json import loads as json_decode

        password = self.__preparePassKey()
        cipher_text = json_decode(self._data['data'])
        if self._debug: print("Text:\t{}\n".format(cipher_text))

        text = SJCL().decrypt(cipher_text, password)

        if len(text):
            if self._debug: print("Decoded Text:\t{}\n".format(text))
            self._text = self.__decompress(text.decode())

        if 'attachment' in self._data and 'attachmentname' in self._data:
            cipherfile = json_decode(self._data['attachment'])
            cipherfilename = json_decode(self._data['attachmentname'])

            if self._debug:
                print("Name:\t{}\nData:\t{}".format(cipherfilename,
                                                    cipherfile))

            attachment = SJCL().decrypt(cipherfile, password)
            attachmentname = SJCL().decrypt(cipherfilename, password)

            self._attachment = self.__decompress(
                attachment.decode('utf-8')).decode('utf-8')
            self._attachment_name = self.__decompress(
                attachmentname.decode('utf-8')).decode('utf-8')
Exemplo n.º 3
0
    def decrypt(self):
        from json import loads as json_decode

        if self._version == 2:
            iv = b64decode(self._data['adata'][0][0])
            salt = b64decode(self._data['adata'][0][1])
            key = self.__deriveKey(salt)

            # Get compression type from received paste
            self._compression = self._data['adata'][0][7]

            cipher = self.__initializeCipher(key, iv, self._data['adata'])
            # Cut the cipher text into message and tag
            cipher_text_tag = b64decode(self._data['ct'])
            cipher_text = cipher_text_tag[:-CIPHER_TAG_BYTES]
            cipher_tag = cipher_text_tag[-CIPHER_TAG_BYTES:]
            cipher_message = json_decode(
                self.__decompress(
                    cipher.decrypt_and_verify(cipher_text,
                                              cipher_tag)).decode())

            self._text = cipher_message['paste'].encode()
            if 'attachment' in cipher_message and 'attachment_name' in cipher_message:
                self._attachment = cipher_message['attachment']
                self._attachment_name = cipher_message['attachment_name']
        else:
            from hashlib import sha256
            from sjcl import SJCL

            if self._password:
                digest = sha256(self._password.encode("UTF-8")).hexdigest()
                password = b64encode(self._key) + digest.encode("UTF-8")
            else:
                password = b64encode(self._key)

            cipher_text = json_decode(self._data['data'])

            if self._debug: print("Text:\t{}\n".format(data))

            text = SJCL().decrypt(cipher_text, password)

            if len(text):
                self._text = self.__decompress(text.decode())

            if 'attachment' in self._data and 'attachmentname' in self._data:
                cipherfile = json_decode(self._data['attachment'])
                cipherfilename = json_decode(self._data['attachmentname'])

                if self._debug:
                    print("Name:\t{}\nData:\t{}".format(
                        cipherfilename, cipherfile))

                attachment = SJCL().decrypt(cipherfile, password)
                attachmentname = SJCL().decrypt(cipherfilename, password)

                self._attachment = self.__decompress(
                    attachment.decode('utf-8')).decode('utf-8')
                self._attachment_name = self.__decompress(
                    attachmentname.decode('utf-8')).decode('utf-8')
Exemplo n.º 4
0
    def encrypt(self, salt, plainText):
        """
        (String, String) -> String
        Encrypt a text
        """

        ciphred = SJCL().encrypt(plainText.encode('utf-8'), salt)
        ciphred['ct'] = base64.b64encode(ciphred.get('ct')).decode('utf-8')
        ciphred['salt'] = base64.b64encode(ciphred.get('salt')).decode('utf-8')
        ciphred['iv'] = base64.b64encode(ciphred.get('iv')).decode('utf-8')

        return base64.b64encode(bytes(json.dumps(ciphred), 'utf-8')).decode()
Exemplo n.º 5
0
async def getFile(wsurl, key, ssl=False):
    part = 0
    finished = False
    randomFile = ''.join(
        random.choice(string.ascii_letters + string.digits)
        for x in range(16)) + ".tmp"
    with open(randomFile, "wb") as f:
        async with websockets.connect(wsurl, ssl=ssl, max_size=5000000) as ws:
            while finished is False:
                req = await ws.send('{"part":' + str(part) + '}')

                result = await ws.recv()
                partInfo, partContent = result.split('XXMOJOXX')
                pc = json.loads(partContent[1:-1].replace('\\', ''))
                partInfo = json.loads(partInfo)
                print("Downloaded part " + str(part + 1) + "/" +
                      str(partInfo['total']))
                fileContent = SJCL().decrypt(pc, key)
                f.write(base64.b64decode(fileContent))
                if part == partInfo['total'] - 1:
                    finished = True
                    print("Download finished")
                    shutil.move(randomFile, partInfo['name'])
                else:
                    part += 1
Exemplo n.º 6
0
    def encrypt(self, formatter, burnafterreading, discussion, expiration):

        from hashlib import sha256
        from sjcl import SJCL

        self._data = {
            'expire': expiration,
            'formatter': formatter,
            'burnafterreading': int(burnafterreading),
            'opendiscussion': int(discussion)
        }

        if self._password:
            digest = sha256(self._password.encode("UTF-8")).hexdigest()
            password = b64encode(self._key) + digest.encode("UTF-8")
        else:
            password = b64encode(self._key)

        # Encrypting text
        cipher = SJCL().encrypt(self.__compress(self._text.encode('utf-8')),
                                password,
                                mode='gcm')
        for k in ['salt', 'iv', 'ct']:
            cipher[k] = cipher[k].decode()

        self._data['data'] = self.json_encode(cipher)
Exemplo n.º 7
0
def encrypt(text):
    key = base64.urlsafe_b64encode(os.urandom(32))
    # Encrypting text
    encrypted_data = SJCL().encrypt(compress(text.encode('utf-8')),
                                    key,
                                    mode='gcm')
    return encrypted_data, key
Exemplo n.º 8
0
 def decrypt(self, token, key, type='AES'):
     if type == 'AES':
         data = SJCL.decrypt(self, token, key)
         return data.decode()
     else:
         jwe = JsonWebEncryption()
         data = jwe.deserialize_compact(token, key)
         return data['payload'].decode()
Exemplo n.º 9
0
 def decrypt(self, salt, ciphredText):
     """
     (String, String) -> String
     Decrypt a text
     """
     ciphred = json.loads(
         base64.b64decode(ciphredText.encode('utf-8')).decode('utf-8'))
     ciphred['ct'] = base64.b64decode(ciphred.get('ct'))
     ciphred['salt'] = base64.b64decode(ciphred.get('salt'))
     ciphred['iv'] = base64.b64decode(ciphred.get('iv'))
     return SJCL().decrypt(ciphred, salt).decode('utf-8')
Exemplo n.º 10
0
def _decrypt(encrypted_data: dict, key: bytes, password: str = None):
    """
    Supplies decrypted text from the payload.
    """
    if password:
        digest = hashlib.sha256(password.encode()).hexdigest()
        passphrase = key + digest.encode()
    else:
        passphrase = key

    data = _decompress(SJCL().decrypt(encrypted_data, passphrase).decode())
    return data
Exemplo n.º 11
0
    def _encryptV1(self):
        from sjcl import SJCL
        from pbincli.utils import json_encode

        self._data = {
            'expire': self._expiration,
            'formatter': self._formatter,
            'burnafterreading': int(self._burnafterreading),
            'opendiscussion': int(self._discussion)
        }

        password = self.__preparePassKey()
        if self._debug: print("Password:\t{}".format(password))

        # Encrypting text
        cipher = SJCL().encrypt(self.__compress(self._text.encode('utf-8')),
                                password,
                                mode='gcm')
        for k in ['salt', 'iv', 'ct']:
            cipher[k] = cipher[k].decode()

        self._data['data'] = json_encode(cipher)

        if self._attachment:
            cipherfile = SJCL().encrypt(self.__compress(
                self._attachment.encode('utf-8')),
                                        password,
                                        mode='gcm')
            for k in ['salt', 'iv', 'ct']:
                cipherfile[k] = cipherfile[k].decode()

            cipherfilename = SJCL().encrypt(self.__compress(
                self._attachment_name.encode('utf-8')),
                                            password,
                                            mode='gcm')
            for k in ['salt', 'iv', 'ct']:
                cipherfilename[k] = cipherfilename[k].decode()

            self._data['attachment'] = json_encode(cipherfile)
            self._data['attachmentname'] = json_encode(cipherfilename)
Exemplo n.º 12
0
def upload(listoffiles):
    for lit in listoffiles:
        l = lit.split('/')
        l.pop()
        fil = str()
        for i in l:
            fil = fil + i + "/"
        filepath = fil
        md5sum = ""
        files = {}
        try:
            file = open(obsdirpath + lit, 'rb')
            hash = hashlib.md5()
            blocksize = 65536
            for block in iter(lambda: file.read(blocksize), b""):
                hash.update(block)
            md5sum = hash.hexdigest()
            text = file.read()
            b = base64.b64encode(text)
            #b = text
            cyphertext = SJCL().encrypt(b, data['key'])
            for key in cyphertext:
                if type(cyphertext[key]) is bytes:
                    cyphertext[key] = cyphertext[key].decode('ascii')
            temp = tempfile.NamedTemporaryFile("a+")
            temp.name = file.name
            temp.write(json.dumps(cyphertext))
            temp.seek(0)
            file.close()

            files = {'document': temp}
        except IOError:
            print("file {} not found".format(obsdirpath + lit))
            sys.exit()
        print("Reading file {}".format(obsdirpath + lit))

        try:
            r2 = client.post(base_url + 'upload_file/',
                             data={
                                 'filepath': filepath,
                                 'md5sum': md5sum,
                                 'csrfmiddlewaretoken': r.cookies['csrftoken']
                             },
                             files=files)
            if r2.url == base_url:
                print("File upload successful")
            else:
                print("An error occured")
        except () as e:
            print("error posting file: {}".format(e))
Exemplo n.º 13
0
def _encrypt(text: str, password: str = None):
    """
    Supplies encrypted text for the payload.
    """
    key = base64.urlsafe_b64encode(os.urandom(32))

    if password:
        digest = hashlib.sha256(password.encode()).hexdigest()
        passphrase = key + digest.encode()
    else:
        passphrase = key

    # Encrypting text
    encrypted_data = SJCL().encrypt(_compress(text.encode()), passphrase, mode='gcm')
    return encrypted_data, key
Exemplo n.º 14
0
 def test_decrypt(self):
     cyphertext = {
         'ks': 128,
         'cipher': 'aes',
         'mode': 'ccm',
         'v': 1,
         'adata': '',
         'iv': 'fR4fZKbjsZOrzDyjCYdEQw==',
         'salt': '5IiimlH8JvY=',
         'ts': 64,
         'iter': 1000,
         'ct': 'V8BYrUdurq1/Qx/EX8EBliKDKa6XB93dZ6QOFSelw77Q'
     }
     self.assertEqual(SJCL().decrypt(cyphertext, "shared_secret"),
                      b"secret message to encrypt")
Exemplo n.º 15
0
    def encrypt(self, data, type='AES', Key=None, dump=True):
        """
        Encrypt data using RSA , AES

        param: type= type of key used in encryption: 'AES' or 'RSA'
        param: key= use your own key for RSA encryption
        param: dump= dumps the data if neccessary
        """

        if dump == True:
            payload = str(json.dumps(data)).encode()
        else:
            payload = str(data).encode()

        if type == 'RSA':
            key = RSA.generate(2048)
            key = key.exportKey('PEM')
            key = jwk.dumps(key, kty='RSA')

            if Key:
                key = Key

            protected = {'alg': 'RSA-OAEP', 'enc': 'A256GCM'}
            jwe = JsonWebEncryption()
            token = jwe.serialize_compact(protected, payload, key)
            token = token.decode()
        else:
            key = secrets.token_urlsafe(32)
            token = SJCL().encrypt(payload, key, "ccm", 1000, 32)
            token['salt'] = str(token['salt']).replace("b'",
                                                       "").replace("'", "")
            token['ct'] = str(token['ct']).replace("b'", "").replace("'", "")
            token['iv'] = str(token['iv']).replace("b'", "").replace("'", "")
            dic = {}
            dic['iv'] = token['iv']
            dic['v'] = token['v']
            dic['iter'] = token['iter']
            dic['ks'] = token['ks']
            dic['ts'] = token['ts']
            dic['mode'] = token['mode']
            dic['adata'] = token['adata']
            dic['cipher'] = token['cipher']
            dic['salt'] = token['salt']
            dic['ct'] = token['ct']
            token = dic
        return {'token': token, 'key': key}
Exemplo n.º 16
0
 def test_gcm_decrypt(self):
     cyphertext = {
         "iv": "oi51KdYi8av0PysYeCDDiw==",
         "v": 1,
         "iter": 10000,
         "ks": 256,
         "ts": 128,
         "mode": "gcm",
         "adata": "",
         "cipher": "aes",
         "salt": "C4DRJM5AH+A=",
         "ct": "KIINDGEQO63pY2mFIWpOuWgx2RAnfU0rhKU="
     }
     self.assertEqual(
         SJCL().decrypt(cyphertext,
                        "vYHOPyQ7Q6NOfm6zkT44IE2SVv+52arqCOv7cDfMApI="),
         b"test paste")
Exemplo n.º 17
0
def get(sid, passphrase, outformat):
    """Get secret from server

    """
    backend = os.environ.get("YOPASS_BACKEND_URL")
    if backend is None:
        click.echo("YOPASS_BACKEND_URL is not defined, "
                   "run export YOPASS_BACKEND_URL=<your backend> first")
        exit(1)
    try:
        response = requests.get("{:s}/secret/{:s}".format(backend, sid))
    except requests.exceptions.HTTPError as errh:
        click.echo("HTTP Error: {:s}".format(errh))
        exit(1)
    except requests.exceptions.ConnectionError as errc:
        click.echo("Error Connecting: {:s}".format(errc))
        exit(1)
    except requests.exceptions.Timeout as errt:
        click.echo("Timeout: {:s}".format(errt))
        exit(1)
    except requests.exceptions.RequestException as err:
        click.echo("Request Exception: {:s}".format(err))
        exit(1)

    response_dict = json.loads(response.text)
    response_message = response_dict["message"]
    if response_message == "Secret not found":
        click.echo("The requested secret was not found.")
        click.echo(
            "Please check if you have entered the sid (secret id) properly.")
        click.echo("The secret might have expired or got opened previously.")
        exit(1)

    print(response.text)
    cypherdict = json.loads(response_message)
    decrypted_secret = SJCL().decrypt(cypherdict, passphrase)

    if outformat == "json":
        click.echo(json.dumps({"secret": decrypted_secret}))
    else:
        click.echo(decrypted_secret)
Exemplo n.º 18
0
    def encrypt(self, formatter, burnafterreading, discussion, expiration):
        from pbincli.utils import json_encode
        if self._version == 2:
            iv = get_random_bytes(CIPHER_TAG_BYTES)
            salt = get_random_bytes(CIPHER_SALT_BYTES)
            key = self.__deriveKey(salt)

            # prepare encryption authenticated data and message
            adata = [[
                b64encode(iv).decode(),
                b64encode(salt).decode(), CIPHER_ITERATION_COUNT,
                CIPHER_BLOCK_BITS, CIPHER_TAG_BITS, 'aes', 'gcm',
                self._compression
            ], formatter,
                     int(burnafterreading),
                     int(discussion)]
            cipher_message = {'paste': self._text}
            if self._attachment:
                cipher_message['attachment'] = self._attachment
                cipher_message['attachment_name'] = self._attachment_name

            cipher = self.__initializeCipher(key, iv, adata)
            ciphertext, tag = cipher.encrypt_and_digest(
                self.__compress(json_encode(cipher_message)))

            self._data = {
                'v': 2,
                'adata': adata,
                'ct': b64encode(ciphertext + tag).decode(),
                'meta': {
                    'expire': expiration
                }
            }

        else:
            from hashlib import sha256
            from sjcl import SJCL

            self._data = {
                'expire': expiration,
                'formatter': formatter,
                'burnafterreading': int(burnafterreading),
                'opendiscussion': int(discussion)
            }

            if self._password:
                digest = sha256(self._password.encode("UTF-8")).hexdigest()
                password = b64encode(self._key) + digest.encode("UTF-8")
            else:
                password = b64encode(self._key)

            if self._debug: print("Password:\t{}".format(password))

            # Encrypting text
            cipher = SJCL().encrypt(self.__compress(
                self._text.encode('utf-8')),
                                    password,
                                    mode='gcm')
            for k in ['salt', 'iv', 'ct']:
                cipher[k] = cipher[k].decode()

            self._data['data'] = json_encode(cipher)

            if self._attachment:
                cipherfile = SJCL().encrypt(self.__compress(
                    self._attachment.encode('utf-8')),
                                            password,
                                            mode='gcm')
                for k in ['salt', 'iv', 'ct']:
                    cipherfile[k] = cipherfile[k].decode()

                cipherfilename = SJCL().encrypt(self.__compress(
                    self._attachment_name.encode('utf-8')),
                                                password,
                                                mode='gcm')
                for k in ['salt', 'iv', 'ct']:
                    cipherfilename[k] = cipherfilename[k].decode()

                self._data['attachment'] = json_encode(cipherfile)
                self._data['attachmentname'] = json_encode(cipherfilename)
Exemplo n.º 19
0
import falcon, json
from falcon.http_status import HTTPStatus
#from falcon import media
import socket
import threading
import time

from sjcl import SJCL

sjcl = SJCL()

config = json.loads(open('config.json').read())
print('loaded config: ', config)


# Class to take care of the nodes
class Node():
    def __init__(self, s_client, ip):
        super().__init__()
        self.s_client = s_client
        self.ip = ip

        self.latency = None
        self.cpu_usage = None

    def __eq__(self, value):
        return self.ip == value.ip


# Function to listen to new nodes that want to offer processing
def listen_for_nodes(node_list, port):
Exemplo n.º 20
0
import socket, json
from spellchecker import SpellChecker
import time

from sjcl import SJCL

sjcl = SJCL()

config = json.loads(open('config.json').read())
print('loaded config: ', config)


# Function to connect to the head and offer processing
def connect_to_head():
    ping_socket = socket.socket()
    ping_socket.connect((config['head_ip'], config['ping_port']))

    ping_socket.send('connect'.encode(encoding='utf-8'))

    ping_socket.close()


def calculate_bill(n_words):
    return n_words * config['price_per_word']


def decode_cipher_dict(cipher_dict):
    for k, v in cipher_dict.items():
        if type(v) == bytes:
            cipher_dict[k] = v.decode()
Exemplo n.º 21
0
 def _get_decrypted_text(self, ciphertext, key):
     data = eval(base64.b64decode(ciphertext))
     return SJCL().decrypt(data, key).strip('"')
Exemplo n.º 22
0
 def __init__(self, server, blog, shared_secret, limit=5):
     self.server = server
     self.blog = blog
     self.shared_secret = shared_secret
     self.limit = limit  # how many posts/comments to fetch with one request
     self.sjcl = SJCL()
Exemplo n.º 23
0
class Cryptedblog:
    """ This module downloads all content of a blog from www.cyptedblog.com via the
    JSON api, decrypts the SJCL encrpted posts/comments/images and saves both, the
    encrypted and decrypted data to disk.

    This module may also be used as a backup solution for cryptedblog.
    """

    def __init__(self, server, blog, shared_secret, limit=5):
        self.server = server
        self.blog = blog
        self.shared_secret = shared_secret
        self.limit = limit  # how many posts/comments to fetch with one request
        self.sjcl = SJCL()

    def download_images(self, fname_parts, key_image):
        response = requests.get(URL_IMAGES % {"server": self.server, "image": key_image})
        data = response.json()
        # special case: images are server from blobstrore and do normally not
        # contain a "success" field !!!
        if not data.get("success", True):
            raise Exception("error image")
        write_file(fname_parts + ["images-encrypted.json"], json.dumps(data, indent=4, sort_keys=True))

        images = json.loads(self.sjcl.decrypt(data, self.shared_secret))
        for (counter, image) in enumerate(images):
            write_file(fname_parts + ["image_%02d.json" % counter], json.dumps(image, indent=4, sort_keys=True))
            # data uri of inline images starts like "data:image/jpeg;base64,"
            file_type = image["data"].split("image/")[1].split(";")[0]
            binary_data = base64.b64decode(image["data"].split("base64,")[1])
            write_file(fname_parts + ["image_%02d.%s" % (counter, file_type)], binary_data)

    def download_comments(self, key_post):
        offset = 0
        while True:

            response = requests.get(
                URL_COMMENT
                % {"server": self.server, "blog": self.blog, "post": key_post, "offset": offset, "limit": self.limit}
            )
            data = response.json()
            if not data.get("success", False):
                raise Exception("error comment")

            for comment in data["data"]:
                key_comment = comment["comment"]
                fname_parts = [self.blog, "posts", key_post, "comments", key_comment]

                # write original data
                write_file(fname_parts + ["comment.json"], json.dumps(comment, indent=4, sort_keys=True))
                # decrypt and write again
                comment["comment-decrypted"] = json.loads(
                    self.sjcl.decrypt(comment["comment-encrypted"], self.shared_secret)
                )
                write_file(fname_parts + ["comment-decrypted.json"], json.dumps(comment, indent=4, sort_keys=True))
                # get images
                if "images" in comment:
                    self.download_images(fname_parts + ["images"], comment["images"])

                offset += 1

            if len(data["data"]) == 0:
                break

    def download_posts(self):
        offset = 0
        while True:
            response = requests.get(
                URL_POST % {"server": self.server, "blog": self.blog, "offset": offset, "limit": self.limit}
            )
            data = response.json()
            for post in data["data"]:
                key_post = post["post"]
                fname_parts = [self.blog, "posts", key_post]

                # write original data
                write_file(fname_parts + ["post.json"], json.dumps(post, indent=4, sort_keys=True))

                # decrypt and write again
                post["post-decrypted"] = json.loads(self.sjcl.decrypt(post["post-encrypted"], self.shared_secret))
                write_file(fname_parts + ["post_decrypted.json"], json.dumps(post, indent=4, sort_keys=True))

                # get images
                if "images" in post:
                    self.download_images(fname_parts + ["images"], post["images"])

                self.download_comments(key_post)
                offset += 1

            # break if there are no further posts
            if len(data["data"]) == 0:
                break
Exemplo n.º 24
0
 def decrypt(self, ciphertext, passphrase):
     ciphertext = json.loads(ciphertext)
     return SJCL().decrypt(ciphertext, passphrase)
Exemplo n.º 25
0
    # print(sys.argv[1])
    file = open(sys.argv[1], 'rb')
    hash = hashlib.md5()
    blocksize = 65536
    for block in iter(lambda: file.read(blocksize), b""):
        hash.update(block)
    md5sum = hash.hexdigest()
    file.close()
    file = open(sys.argv[1], 'rb')
    text = file.read()
    # print(text)
    b = base64.b64encode(text)
    #b = text
    # print(b)
    strr = data['key']
    cyphertext = SJCL().encrypt(b, str(strr))
    # sys.exit()
    for key in cyphertext:
        if type(cyphertext[key]) is bytes:
            cyphertext[key] = cyphertext[key].decode('ascii')
    temp = tempfile.NamedTemporaryFile(mode='w+')
    temp.name = file.name
    temp.write(json.dumps(cyphertext))
    temp.seek(0)
    # f = open('newnewtemp.file','w')
    # f.write(json.dumps(cyphertext))
    # f.close()
    # f = open('newnewtemp.file', 'r')
    files = {'document': temp}
except IOError:
    print("file {} not found".format(sys.argv[1]))
Exemplo n.º 26
0
def decrypt(etxt, salt=salt):
    """
        Decrypts a given string by provided salt(optional)
    """
    etxt = decode(etxt)
    return SJCL().decrypt(etxt, salt)
Exemplo n.º 27
0
                #     try:
                #         text[it] = int(text[it])
                #     except:
                #         pass
                # print(text)

                # class mydict(dict):
                #     def __str__(self):
                #         return json.dumps(self)
                # text = mydict(text)
                for key in text:
                    if key == 'salt' or key == 'ct' or key == 'iv':
                        text[key] = text[key].encode('ascii')
                # print(text)
                # text = {"salt": "1sMrwmhD9uo=", "iter": 10000, "ks": 128, "ct": "IY3k1LcEUSQ=", "iv": "JReeuzEISWe1PjLzNCLMXw==", "cipher": "aes", "mode": "ccm", "adata": "", "v": 1, "ts": 64}
                dec = SJCL().decrypt(text, 'shared_secret')
                # dec = dec.decode('ascii')
                # dec = base64.b64decode(dec)
                # dec = base64.decodebytes(dec)
                # dec = ('data:text/plain;base64,') + dec
                dec = base64.b64decode(dec)
                # dec = base64.b64decode('data:image/jpeg;base64,') + dec
                dec = dec.decode('ascii')
                # prepend_info = 'data:image/jpeg;base64'
                # dec = base64.decodebytes(dec)
                #output file
                # print(dec)
                f.write(dec)
                f.close()
                print(green + "done" + end_c)
            except () as e:
Exemplo n.º 28
0
def send(args, api_client):
    if args.stdin:
        text = args.stdin.read()
    elif args.text:
        text = args.text
    elif args.file:
        text = "Sending a file to you!"
    else:
        print("Nothing to send!")
        sys.exit(1)

    # Formatting request
    request = {'expire':args.expire,'formatter':args.format,'burnafterreading':int(args.burn),'opendiscussion':int(args.discus)}

    passphrase = b64encode(os.urandom(32))
    if args.debug: print("Passphrase:\t{}".format(passphrase))

    # If we set PASSWORD variable
    if args.password:
        digest = hashlib.sha256(args.password.encode("UTF-8")).hexdigest()
        password = passphrase + digest.encode("UTF-8")
    else:
        password = passphrase

    if args.debug: print("Password:\t{}".format(password))

    # Encrypting text
    cipher = SJCL().encrypt(compress(text.encode('utf-8')), password, mode='gcm')

    # TODO: should be implemented in upstream
    for k in ['salt', 'iv', 'ct']: cipher[k] = cipher[k].decode()

    request['data'] = json.dumps(cipher, ensure_ascii=False).replace(' ','')

    # If we set FILE variable
    if args.file:
        check_readable(args.file)
        with open(args.file, "rb") as f:
            contents = f.read()
            f.close()
        mime = guess_type(args.file)
        if args.debug: print("Filename:\t{}\nMIME-type:\t{}".format(path_leaf(args.file), mime[0]))

        file = "data:" + mime[0] + ";base64," + b64encode(contents).decode()
        filename = path_leaf(args.file)

        cipherfile = SJCL().encrypt(compress(file.encode('utf-8')), password, mode='gcm')
        # TODO: should be implemented in upstream
        for k in ['salt', 'iv', 'ct']: cipherfile[k] = cipherfile[k].decode()
        cipherfilename = SJCL().encrypt(compress(filename.encode('utf-8')), password, mode='gcm')
        for k in ['salt', 'iv', 'ct']: cipherfilename[k] = cipherfilename[k].decode()

        request['attachment'] = json.dumps(cipherfile, ensure_ascii=False).replace(' ','')
        request['attachmentname'] = json.dumps(cipherfilename, ensure_ascii=False).replace(' ','')

    if args.debug: print("Request:\t{}".format(request))

    # If we use dry option, exit now
    if args.dry: sys.exit(0)

    result = api_client.post(request)

    if args.debug: print("Response:\t{}\n".format(result))

    try:
        result = json.loads(result)
    except ValueError as e:
        print("PBinCLI Error: {}".format(e))
        sys.exit(1)

    if 'status' in result and not result['status']:
        print("Paste uploaded!\nPasteID:\t{}\nPassword:\t{}\nDelete token:\t{}\n\nLink:\t\t{}?{}#{}".format(result['id'], passphrase.decode(), result['deletetoken'], api_client.server, result['id'], passphrase.decode()))
    elif 'status' in result and result['status']:
        print("Something went wrong...\nError:\t\t{}".format(result['message']))
        sys.exit(1)
    else:
        print("Something went wrong...\nError: Empty response.")
        sys.exit(1)
Exemplo n.º 29
0
def get(args, api_client):
    pasteid, passphrase = args.pasteinfo.split("#")

    if pasteid and passphrase:
        if args.debug: print("PasteID:\t{}\nPassphrase:\t{}".format(pasteid, passphrase))

        if args.password:
            digest = hashlib.sha256(args.password.encode("UTF-8")).hexdigest()
            password = passphrase + digest.encode("UTF-8")
        else:
            password = passphrase

        if args.debug: print("Password:\t{}".format(password))

        result = api_client.get(pasteid)
    else:
        print("PBinCLI error: Incorrect request")
        sys.exit(1)

    if args.debug: print("Response:\t{}\n".format(result))

    try:
        result = json.loads(result)
    except ValueError as e:
        print("PBinCLI Error: {}".format(e))
        sys.exit(1)

    if 'status' in result and not result['status']:
        print("Paste received! Text inside:")
        data = json.loads(result['data'])

        if args.debug: print("Text:\t{}\n".format(data))

        text = SJCL().decrypt(data, password)
        print("{}\n".format(decompress(text.decode())))

        check_writable("paste.txt")
        with open("paste.txt", "wb") as f:
            f.write(decompress(text.decode()))
            f.close

        if 'attachment' in result and 'attachmentname' in result:
            print("Found file, attached to paste. Decoding it and saving")

            cipherfile = json.loads(result['attachment']) 
            cipherfilename = json.loads(result['attachmentname'])

            if args.debug: print("Name:\t{}\nData:\t{}".format(cipherfilename, cipherfile))

            attachmentf = SJCL().decrypt(cipherfile, password)
            attachmentname = SJCL().decrypt(cipherfilename, password)

            attachment = decompress(attachmentf.decode('utf-8')).decode('utf-8').split(',', 1)[1]
            file = b64decode(attachment)
            filename = decompress(attachmentname.decode('utf-8')).decode('utf-8')

            print("Filename:\t{}\n".format(filename))

            check_writable(filename)
            with open(filename, "wb") as f:
                f.write(file)
                f.close

        if 'burnafterreading' in result['meta'] and result['meta']['burnafterreading']:
            print("Burn afrer reading flag found. Deleting paste...")
            result = api_client.delete(pasteid, 'burnafterreading')

            if args.debug: print("Delete response:\t{}\n".format(result))

            try:
                result = json.loads(result)
            except ValueError as e:
                print("PBinCLI Error: {}".format(e))
                sys.exit(1)

            if 'status' in result and not result['status']:
                print("Paste successfully deleted!")
            elif 'status' in result and result['status']:
                print("Something went wrong...\nError:\t\t{}".format(result['message']))
                sys.exit(1)
            else:
                print("Something went wrong...\nError: Empty response.")
                sys.exit(1)

    elif 'status' in result and result['status']:
        print("Something went wrong...\nError:\t\t{}".format(result['message']))
        sys.exit(1)
    else:
        print("Something went wrong...\nError: Empty response.")
        sys.exit(1)
Exemplo n.º 30
0
data = json.load(sys.stdin)

if len(sys.argv) < 4:
    sys.stderr.write("configure.py chrome-dir ext-id cryptpw")
    sys.exit(1)

chrome_dir = sys.argv[1]
ext_id = sys.argv[2]
cryptpw = sys.argv[3]

settings = data['settings']
accounts = settings['accounts']

encrypted_accounts = SJCL().encrypt(bytes(json.dumps(accounts),
                                          encoding='utf-8'),
                                    cryptpw,
                                    count=1000,
                                    dkLen=32)

json_accounts = json.dumps({
    x: str(y, encoding='utf-8') if isinstance(y, bytes) else y
    for x, y in encrypted_accounts.items()
})
settings['accounts'] = str(base64.b64encode(
    bytes(json_accounts, encoding='utf-8')),
                           encoding='utf-8')

data['settings'] = json.dumps(settings)
data['activeTab'] = '"search"'

db_path = path.join(chrome_dir, "Default/Local Extension Settings", ext_id)
Exemplo n.º 31
0
def send(secret, expires, outmode, outformat):
    """Submit secret to server. Optionally pipe secret via stdin.

    """
    backend = os.environ.get("YOPASS_BACKEND_URL")
    if backend is None:
        click.echo("""YOPASS_BACKEND_URL is not defined, run export
            YOPASS_BACKEND_URL=<your backend> first""")
        exit(1)
    frontend = os.environ.get("YOPASS_FRONTEND_URL")
    if frontend is None and outmode != "id":
        click.echo("""YOPASS_FRONTEND_URL is not defined, run export
            YOPASS_FRONTEND_URL=<your frontend> first""")
        exit(1)
    try:
        secret = secret.read()
    except AttributeError:
        pass

    passphrase = generate_passphrase(15)
    cypherdict = SJCL().encrypt(secret.encode(), passphrase)
    converted_cypherdict = {}

    for key, value in cypherdict.items():
        try:
            converted_cypherdict[key] = value.decode("utf-8")
        except AttributeError:
            converted_cypherdict[key] = value

    expiry_dict = {"1h": 3600, "1d": 86400, "1w": 604800}
    payload = {
        "expiration": expiry_dict[expires],
        "secret": json.dumps(converted_cypherdict),
    }
    response = {}
    try:
        response = requests.post("{:s}/secret".format(backend),
                                 data=json.dumps(payload))
    except requests.exceptions.HTTPError as errh:
        click.echo("HTTP Error: {:s}".format(errh))
        exit(1)
    except requests.exceptions.ConnectionError as errc:
        click.echo("Error Connecting: {:s}".format(errc))
        exit(1)
    except requests.exceptions.Timeout as errt:
        click.echo("Timeout: {:s}".format(errt))
        exit(1)
    except requests.exceptions.RequestException as err:
        click.echo("Request Exception: {:s}".format(err))
        exit(1)

    secret_id = json.loads(response.text)["message"]

    one_click_link = "{:s}/#/s/{:s}/{:s}".format(frontend, secret_id,
                                                 passphrase)
    short_link = "{:s}/#/s/{:s}".format(frontend, secret_id)

    if outmode == "verbose":
        if outformat == "json":
            click.echo(
                json.dumps({
                    "one-click-link": one_click_link,
                    "short-link": short_link,
                    "decryption-key": passphrase,
                }))
        else:
            click.echo(one_click_link)
            click.echo(short_link)
            click.echo(passphrase)
    elif outmode == "short-link":
        if outformat == "json":
            click.echo(
                json.dumps({
                    "short-link": short_link,
                    "decryption-key": passphrase
                }))
        else:
            click.echo(short_link)
            click.echo(passphrase)
    elif outmode == "id":
        if outformat == "json":
            click.echo(
                json.dumps({
                    "id": secret_id,
                    "decryption-key": passphrase
                }))
        else:
            click.echo(secret_id)
            click.echo(passphrase)
    elif outmode == "one-click-link":
        if outformat == "json":
            click.echo(json.dumps({"one-click-link": one_click_link}))
        else:
            click.echo(one_click_link)
Exemplo n.º 32
0
def encrypt(txt, salt=salt):
    """
        Encrypts a given string by provided salt(optional)
    """
    return encode(json.dumps(SJCL().encrypt(bytes(txt, "utf8"), salt)))