コード例 #1
0
def run(args):
    try:
        me = Me.get(profile=args.profile)
    except DoesNotExist:
        print('You need to run setup first!')
        return 1

    try:
        recipient = Person.get(email=args.email, profile=args.profile)
    except DoesNotExist:
        print('Nobody with email {} exists.'.format(args.email))
        return 1

    private_key = me.private_key
    public_key = recipient.public_key

    try:
        input_file = open(args.input, 'rb') if args.input else sys.stdin.buffer
    except FileNotFoundError:
        print('File does not exist')
        return 1

    output_file = open(args.output, 'wb') if args.output else sys.stdout.buffer

    box = Box(private_key, public_key)
    encrypted_message = box.encrypt(input_file.read())
    output_file.write(encrypted_message)
コード例 #2
0
 def init(self, password, new=True) -> str:
     headers = {"Content-Type": "application/json"}
     tname = j.core.identity.me.tname
     username = j.core.identity.me.tname.split(".")[0]
     url = os.path.join(MARKETPLACE_URL, PUBLIC_KEY_ENDPOINT)
     response = requests.post(url)
     if response.status_code != 200:
         raise Exception("Can not get threebot deployer publickey")
     mrkt_pub_key = nacl.public.PublicKey(response.json().encode(),
                                          nacl.encoding.Base64Encoder)
     priv_key = j.core.identity.me.nacl.private_key
     box = Box(priv_key, mrkt_pub_key)
     password_encrypted = box.encrypt(
         password.encode(), encoder=nacl.encoding.Base64Encoder).decode()
     data = {
         "threebot_name": tname,
         "passwd": password_encrypted,
         "new": new,
         "token": BACKUP_TOKEN
     }
     url = os.path.join(MARKETPLACE_URL, CREATE_USER_ENDPOINT)
     response = requests.post(url, json=data, headers=headers)
     if response.status_code != 200:
         raise j.exceptions.Value(
             f"can not create user with name:{username}, error={response.text}"
         )
     config_dict = dict(zip(REPO_NAMES, response.json()))
     for repo_name, serverip in config_dict.items():
         print(repo_name, serverip)
         repo = j.tools.restic.get(repo_name)
         repo.repo = f"rest:http://{username}:{password}@{serverip}:8000/{username}/"
         repo.password = password
         repo.init_repo()
         repo.save()
     return j.data.serializers.json.dumps({"data": "backup repos inited"})
コード例 #3
0
def decrypt_message(messageDataHexString,userKeySet,debug):
	#begin decrypt_message
	if debug:print('**Decrypting_message',line_number()) #debug
	try:
		messageDataBytes=binascii.unhexlify(messageDataHexString) #translate message data from hex to bytes
	except:
		if debug:return '**plaintext message on blockchain <%i>'%messageDataHexString
		return ''
	encryptedKeys,plaintextTimestamp,cipherText,numRecipients,senderPublicKey=parse_message_bin(messageDataBytes,debug) #parse message into parts

	userPublicKey,userPrivateKey=userKeySet #get user key set
	decryptKeyBox=Box(userPrivateKey,senderPublicKey) #box for decryption of secret key

	notAuthorized=True
	for each in encryptedKeys:
		try:
			secretKey=decryptKeyBox.decrypt(each) #decrypt key
			notAuthorized=False
		except:
			continue

		if len(secretKey)==32: 
			secretBox=secret.SecretBox(secretKey) #make box for 
			plainText=secretBox.decrypt(cipherText) #get bytes of plaintext
			decryptedTimestamp=plainText[:26].decode() #extract timestamp from plaintext
			if debug:print('**timeStamp comparison:',decryptedTimestamp==plaintextTimestamp,line_number()) #debug
			if not decryptedTimestamp==plaintextTimestamp: #test for tampering
				print('Timestamps dont match: Tampering detected') #std out
				pass
			plainText=plainText[:19].decode()+'(UTC) '+plainText[26:].decode() #truncate timestamp add space
			if debug:print('**plaintext:',plainText,line_number()) #debug
	if notAuthorized:plainText=''
	return plainText #return plaintext from message
コード例 #4
0
    def rpc_complete_order(self, sender, pubkey, encrypted):
        try:
            box = Box(self.signing_key.to_curve25519_private_key(),
                      PublicKey(pubkey))
            order = box.decrypt(encrypted)
            json.loads(order, object_pairs_hook=OrderedDict)
            temp = Contract(self.db,
                            contract=json.loads(order,
                                                object_pairs_hook=OrderedDict),
                            testnet=self.multiplexer.testnet)
            c = Contract(self.db,
                         hash_value=unhexlify(temp.get_order_id()),
                         testnet=self.multiplexer.testnet)

            contract_id = c.accept_receipt(self.get_notification_listener(),
                                           self.multiplexer.blockchain,
                                           receipt_json=json.dumps(
                                               temp.contract["buyer_receipt"],
                                               indent=4))
            self.router.addContact(sender)
            self.log.info("received receipt for order %s" % contract_id)
            return ["True"]
        except Exception, e:
            self.log.error("unable to parse receipt from %s" % sender)
            return [e.message]
コード例 #5
0
    def nacl_profile_decrypt(self,
                             encrypted: str,
                             public_key: str = 'empty') -> str:
        """
        It reads in a str after encode-decode an EncryptedMessage object
        and decrypt it to a plaintext (str).
        :param encrypted: a str after the encode-decode an EncryptedMessage object
        :param public_key: by default to be self.public_key if not provided
        :return: plaintext string
        """
        if public_key == 'empty':
            public_key = self.public_key

        encoder = NaClDSEncoder.NaClDSEncoder()
        public_key = encoder.encode_public_key(public_key)
        private_key = encoder.encode_private_key(self.private_key)

        the_box = Box(private_key, public_key)
        # convert the encrypted input into the byte version of itself
        # since the box.decrypt() method needs a byte object as parameter
        bencrypted = encrypted.encode(encoding='UTF-8')

        bdecrypted = the_box.decrypt(bencrypted,
                                     encoder=nacl.encoding.Base64Encoder)
        # needs to be decoded to convert from byte to str
        decrypted = bdecrypted.decode(encoding='UTF-8')
        return decrypted
コード例 #6
0
    def set_up_encryption(self):

        sk = None
        pk = None

        if not self.box:
            if ("localhost", str(sock352portRx)) in privateKeys:
                sk = privateKeys["localhost", str(sock352portRx)]
            elif ("*", str(sock352portRx)) in privateKeys:
                sk = privateKeys["*", str(sock352portRx)]
            elif ("*", "*") in privateKeys:
                sk = privateKeys["*", "*"]
            elif ("localhost", "*") in privateKeys:
                sk = privateKeys["localhost", "*"]

            (host, port) = self.connections[0]

            if (host, str(port)) in publicKeys:
                pk = publicKeys[host, str(port)]

            if not sk or not pk:
                print("Error decrypting.")
                return None

            #print(sk, pk)

            self.box = Box(sk, pk)
            self.nonce = nacl.utils.random(Box.NONCE_SIZE)
コード例 #7
0
    def test_put_password_with_invalid_json(self):
        """
        Tests PUT method on password with invalid json
        """

        url = reverse('password')

        update_data_nonce = nacl.utils.random(Box.NONCE_SIZE)
        update_data_nonce_hex = nacl.encoding.HexEncoder.encode(update_data_nonce)

        crypto_box = Box(PrivateKey(self.user_private_key, encoder=nacl.encoding.HexEncoder),
                         PublicKey(self.verifier_public_key, encoder=nacl.encoding.HexEncoder))


        update_data_dec = crypto_box.encrypt('narf'.encode("utf-8"), update_data_nonce)

        update_data = update_data_dec[len(update_data_nonce):]
        update_data_hex = nacl.encoding.HexEncoder.encode(update_data)

        data = {
            'username': self.test_username,
            'recovery_authkey': self.test_recovery_authkey,
            'update_data': update_data_hex.decode(),
            'update_data_nonce': update_data_nonce_hex.decode(),
        }

        self.client.force_authenticate(user=self.test_user_obj)
        response = self.client.put(url, data)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
コード例 #8
0
ファイル: crypto.py プロジェクト: omirror/toxmail
def decrypt_text(text, secret_key, sender_public_key):
    """Decrypts a text
    """
    secret_key = PrivateKey(secret_key.decode('hex'))
    sender_public_key = PublicKey(sender_public_key.decode('hex'))
    box = Box(secret_key, sender_public_key)
    return box.decrypt(text)
コード例 #9
0
    async def _bg_key_exchange(
        self,
        nursery: trio.Nursery,
        whitelist: Optional[PublicKey] = None
            ) -> None:

        # send key right away and await remote key
        nursery.start_soon(
            partial(
                self.send_raw,
                bytes(self.key.public_key),
                encrypted=False
                )
            )

        async with self.inbound.subscribe(
            lambda *args: isinstance(args[0], bytes) and (len(args[0]) == 32),
            history=True
                ) as pkqueue:
            data = await pkqueue.receive()

        rkey = PublicKey(data)

        # drop context if not in whitelist
        if (whitelist is not None) and \
                (rkey not in whitelist):
            await self.inbound.send(UDPContext.F_DROPPED)
            return

        self.remote_pkey = rkey
        self.boxes[self.addr] = Box(self.key, self.remote_pkey)

        await self.inbound.send(UDPContext.F_KEYEX)

        return None
コード例 #10
0
def decrypt_server_login_info(login_info_hex, login_info_nonce_hex,
                              session_public_key, session_private_key):
    """
    Takes the login info and nonce together with the session public and private key.
    Will decrypt the login info and interpret it as json and return the json parsed object.
    :param login_info:
    :type login_info:
    :param login_info_nonce:
    :type login_info_nonce:
    :param session_public_key:
    :type session_public_key:
    :param session_private_key:
    :type session_private_key:

    :return:
    :rtype:
    """

    crypto_box = Box(
        PrivateKey(session_private_key, encoder=nacl.encoding.HexEncoder),
        PublicKey(session_public_key, encoder=nacl.encoding.HexEncoder))

    login_info = nacl.encoding.HexEncoder.decode(login_info_hex)
    login_info_nonce = nacl.encoding.HexEncoder.decode(login_info_nonce_hex)

    login_info = json.loads(
        crypto_box.decrypt(login_info, login_info_nonce).decode())

    return login_info
コード例 #11
0
ファイル: crypto.py プロジェクト: omirror/toxmail
def encrypt_text(text, secret_key, rcpt_public_key):
    """Encrypts a text
    """
    secret_key = PrivateKey(secret_key.decode('hex'))
    rcpt_public_key = PublicKey(rcpt_public_key.decode('hex'))
    box = Box(secret_key, rcpt_public_key)
    return box.encrypt(text, nacl.utils.random(Box.NONCE_SIZE))
コード例 #12
0
ファイル: invitation.py プロジェクト: ggozad/petmail
    def processM1(self, msg):
        #print "processM1", self.petname
        self.theirTempPubkey = PublicKey(msg)
        self.db.update(
            "UPDATE invitations SET theirTempPubkey=?"
            " WHERE id=?", (self.theirTempPubkey.encode(Hex), self.iid),
            "invitations", self.iid)
        # theirTempPubkey will committed by our caller, in the same txn as
        # the message send

        my_privkey = self.getMyTempPrivkey()
        my_channel_record = self.getMyPublicChannelRecord()
        b = Box(my_privkey, self.theirTempPubkey)
        signedBody = b"".join([
            self.theirTempPubkey.encode(),
            my_privkey.public_key.encode(),
            my_channel_record.encode("utf-8")
        ])
        my_sign = self.getMySigningKey()
        body = b"".join([
            b"i0:m2a:",
            my_sign.verify_key.encode(),
            my_sign.sign(signedBody)
        ])
        nonce = os.urandom(Box.NONCE_SIZE)
        nonce_and_ciphertext = b.encrypt(body, nonce)
        #print "ENCRYPTED n+c", len(nonce_and_ciphertext), nonce_and_ciphertext.encode("hex")
        #print " nonce", nonce.encode("hex")
        msg2 = "i0:m2:" + nonce_and_ciphertext
        self.send(msg2)
        self.nextExpectedMessage = 2
コード例 #13
0
def asymmetric_decryption(ours_private_key, target_public_key, nonce,
                          cipher_text):
    '''Decrypt a message with our pirvate_key and the public used by target.

    Args:
        ours_private_key(bytes).
        target_public_key(bytes).
        nonce: the nonce you used to encrypt.
        cipher_text(bytes): the text you want to decrypted.

    Returns:
        A str plain_text.
        plain_text(str): decryption result.
        None: error.
    '''

    private_key_object = PrivateKey(ours_private_key)
    public_key_object = PublicKey(target_public_key)

    try:
        decrypt_box = Box(private_key_object, public_key_object)
        plain_text = decrypt_box.decrypt(ciphertext=cipher_text, nonce=nonce)
    except Exception:
        return None

    plain_text = plain_text.decode('utf-8')
    return plain_text
コード例 #14
0
def asymmetric_encryption(ours_private_key, target_public_key, plain_text):
    '''Encrypt a message with the ours private_key and the public_key used by the target.

    Args:
        ours_private_key(bytes): generate from asmmetric_key_generate.
        target_public_key(bytes): generate from asmmetric_key_generate, but user query from the server, user don't have this key.
        plain_text(str): the text you want to encrypted.

    Returns:
        A dict result_dict.
        For example:
        {
            'cipher_text': ...(bytes),
            'nonce': ...(bytes)
        }
        None: error.
    '''

    bytes_text = plain_text.encode()
    private_key_object = PrivateKey(ours_private_key)
    public_key_object = PublicKey(target_public_key)
    try:
        encrypt_box = Box(private_key_object, public_key_object)
        nonce = nacl.utils.random(Box.NONCE_SIZE)
        encrypted = encrypt_box.encrypt(bytes_text, nonce=nonce)
    except Exception:
        # print(e.args)
        return None

    result_dict = dict()
    result_dict['cipher_text'] = encrypted.ciphertext
    result_dict['nonce'] = nonce
    return result_dict
コード例 #15
0
 def startProtocol(self):
     self._clientShortKey = self._generateKey()
     self._shortLongBox = Box(self._clientShortKey, self._serverKey)
     packet = ('QvnQ5XlH' + self._serverExtension + self._clientExtension +
               str(self._clientShortKey.public_key) + '\0' * 64 +
               self._encryptForNonce('H', self._shortLongBox, '\0' * 64))
     self._helloMultiCall = self._retrySendingForHandshake(packet)
コード例 #16
0
    def rpc_complete_order(self, sender, pubkey, encrypted):
        try:
            box = Box(
                PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)),
                PublicKey(pubkey))
            order = box.decrypt(encrypted)
            c = Contract(self.db,
                         contract=json.loads(order,
                                             object_pairs_hook=OrderedDict),
                         testnet=self.multiplexer.testnet)

            def handle_result(contract_id):
                if contract_id:
                    self.router.addContact(sender)
                    self.log.info("Received receipt for order %s" %
                                  contract_id)
                    return ["True"]
                else:
                    self.log.error("Received invalid receipt from %s" % sender)
                    return ["False"]

            d = c.accept_receipt(self.multiplexer.ws,
                                 self.multiplexer.blockchain)
            d.addCallback(handle_result)
        except Exception:
            self.log.error("Unable to decrypt order receipt from %s" % sender)
            return ["False"]
コード例 #17
0
 def open(self, encrypted_message: bytes, sender_public_key: PublicKey, nonce: bytes) -> bytes:
     # Decrypts an encrypted message with the appropriate sender information.
     box = Box(BoxPrivateKey(self.get_key()[:32]), BoxPublicKey(sender_public_key.get_key()))
     try:
         return box.decrypt(encrypted_message, nonce)
     except CryptoError:
         return bytes()
コード例 #18
0
    def send_message(self, receiving_node, public_key, message_type, message, subject=None):
        """
        Sends a message to another node. If the node isn't online it
        will be placed in the dht for the node to pick up later.
        """
        pro = Profile().get()
        if len(message) > 1500:
            return
        p = objects.Plaintext_Message()
        p.sender_guid = self.kserver.node.id
        p.signed_pubkey = self.kserver.node.signed_pubkey
        p.encryption_pubkey = PrivateKey(self.signing_key.encode()).public_key.encode()
        p.type = message_type
        p.message = message
        if subject is not None:
            p.subject = subject
        if pro.handle:
            p.handle = pro.handle
        if pro.avatar_hash:
            p.avatar_hash = pro.avatar_hash
        p.timestamp = int(time.time())
        signature = self.signing_key.sign(p.SerializeToString())[:64]
        p.signature = signature

        skephem = PrivateKey.generate()
        pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
        box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder))
        nonce = nacl.utils.random(Box.NONCE_SIZE)
        ciphertext = box.encrypt(p.SerializeToString(), nonce)

        def get_response(response):
            if not response[0]:
                self.kserver.set(receiving_node.id, pkephem, ciphertext)
        self.protocol.callMessage(receiving_node, pkephem, ciphertext).addCallback(get_response)
コード例 #19
0
    def set_up_decryption(self):

        sk = None
        pk = None

        if not self.box:
            if ("127.0.0.1", str(sock352portRx)) in privateKeys:
                sk = privateKeys["127.0.0.1", str(sock352portRx)]
            elif ("*", str(sock352portRx)) in privateKeys:
                sk = privateKeys["*", str(sock352portRx)]
            elif ("*", "*") in privateKeys:
                sk = privateKeys["*", "*"]
            elif ("127.0.0.1", "*") in privateKeys:
                sk = privateKeys["127.0.0.1", "*"]
            elif ("localhost", str(sock352portRx)) in privateKeys:
                sk = privateKeys["localhost", str(sock352portRx)]

            (host, port) = self.connections[0]

            if (host, str(port)) in publicKeys:
                pk = publicKeys[host, str(port)]
            elif host == "127.0.0.1" and ("localhost", str(port)) in publicKeys:
                pk = publicKeys["localhost", str(port)]

            if not sk or not pk:
                print("Error decrypting.")
                return None



            self.box = Box(sk, pk)
コード例 #20
0
 def parse_messages(messages):
     if messages is not None:
         for message in messages:
             try:
                 value = objects.Value()
                 value.ParseFromString(message)
                 try:
                     box = Box(PrivateKey(self.signing_key.encode()), PublicKey(value.valueKey))
                     ciphertext = value.serializedData
                     plaintext = box.decrypt(ciphertext)
                     p = objects.Plaintext_Message()
                     p.ParseFromString(plaintext)
                     signature = p.signature
                     p.ClearField("signature")
                     verify_key = nacl.signing.VerifyKey(p.signed_pubkey[64:])
                     verify_key.verify(p.SerializeToString(), signature)
                     h = nacl.hash.sha512(p.signed_pubkey)
                     pow_hash = h[64:128]
                     if int(pow_hash[:6], 16) >= 50 or hexlify(p.sender_guid) != h[:40]:
                         raise Exception('Invalid guid')
                     listener.notify(p.sender_guid, p.encryption_pubkey, p.subject,
                                     objects.Plaintext_Message.Type.Name(p.type), p.message)
                 except Exception:
                     pass
                 signature = self.signing_key.sign(value.valueKey)[:64]
                 self.kserver.delete(self.kserver.node.id, value.valueKey, signature)
             except Exception:
                 pass
コード例 #21
0
 def rpc_message(self, sender, pubkey, encrypted):
     try:
         box = Box(self.signing_key.to_curve25519_private_key(),
                   PublicKey(pubkey))
         plaintext = box.decrypt(encrypted)
         p = PlaintextMessage()
         p.ParseFromString(plaintext)
         signature = p.signature
         p.ClearField("signature")
         verify_key = nacl.signing.VerifyKey(p.pubkey)
         verify_key.verify(p.SerializeToString(), signature)
         h = nacl.hash.sha512(p.pubkey)
         pow_hash = h[40:]
         if int(pow_hash[:6], 16) >= 50 or p.sender_guid.encode(
                 "hex") != h[:40] or p.sender_guid != sender.id:
             raise Exception('Invalid guid')
         self.log.info("received a message from %s" % sender)
         self.router.addContact(sender)
         for listener in self.listeners:
             try:
                 verifyObject(MessageListener, listener)
                 listener.notify(p, signature)
             except DoesNotImplement:
                 pass
         return ["True"]
     except Exception:
         self.log.warning("received invalid message from %s" % sender)
         return ["False"]
コード例 #22
0
ファイル: site.py プロジェクト: joshland/wgmesh
def hostImport(data: str, site: core.Sitecfg, hosts: list) -> list:
    ''' import/update a host from a site '''

    outer_message = base64.decodebytes( data.encode('ascii') ).decode()
    logger.debug(f'Host import: {data}')
    outer = yaml.load(outer_message, Loader=yaml.RoundTripLoader)
    logger.trace(f'Outer message: {outer}')
    HPub = keyimport( outer['public_key'], PublicKey)
    logger.trace(f'HPub/{HPub} -- SKey/{site.MSK}')
    SBox = Box(site.MSK, HPub)

    inner_decoded = base64.decodebytes( outer['message'] )
    inner_message = SBox.decrypt( inner_decoded )
    inner = yaml.load (inner_message, Loader=yaml.RoundTripLoader)
    logger.debug(f'Host Decode: {inner}')
    
    key = inner['public_key'].lower()

    hostname = inner['hostname'].lower()
    del inner['hostname']
    host = Host(hostname, site, **inner)

    found = False
    for x in hosts:
        if x.uuid == host.uuid:
            x.update(host)
            found = True
            continue
        continue

    if not found:
        hosts.append(host)
        pass

    return CheckConfig(site, hosts)
コード例 #23
0
 def send_client_key(self):
     client_pub = PublicKey(self.decode_base64(self.client_key))
     nonce = nacl.utils.random(Box.NONCE_SIZE)
     box = Box(self.key, client_pub)
     message = base64.b64encode(box.encrypt(self.aes_key, nonce))
     self.send_xt_client('secondlayer', 'encryption',
                         self.proxy_pub_key_b64.decode(), message.decode())
コード例 #24
0
 def rpc_order(self, sender, pubkey, encrypted):
     try:
         box = Box(PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)), PublicKey(pubkey))
         order = box.decrypt(encrypted)
         c = Contract(self.db, contract=json.loads(order, object_pairs_hook=OrderedDict),
                      testnet=self.multiplexer.testnet)
         if c.verify(sender.signed_pubkey[64:]):
             self.router.addContact(sender)
             self.log.info("received an order from %s, waiting for payment..." % sender)
             payment_address = c.contract["buyer_order"]["order"]["payment"]["address"]
             chaincode = c.contract["buyer_order"]["order"]["payment"]["chaincode"]
             masterkey_b = c.contract["buyer_order"]["order"]["id"]["pubkeys"]["bitcoin"]
             buyer_key = derive_childkey(masterkey_b, chaincode)
             amount = c.contract["buyer_order"]["order"]["payment"]["amount"]
             listing_hash = c.contract["buyer_order"]["order"]["ref_hash"]
             signature = self.signing_key.sign(
                 str(payment_address) + str(amount) + str(listing_hash) + str(buyer_key))[:64]
             c.await_funding(self.multiplexer.ws, self.multiplexer.blockchain, signature, False)
             return [signature]
         else:
             self.log.warning("received invalid order from %s" % sender)
             return ["False"]
     except Exception:
         self.log.error("unable to decrypt order from %s" % sender)
         return ["False"]
コード例 #25
0
ファイル: sock352.py プロジェクト: MarcusLomi/PySocket-pt.3
    def accept(self, *args):
        global socketBox
        global partnerPublicKey
        print "Accepting..."
        if len(args) >= 1:
            if args[0] is ENCRYPT:
                self.encryption = True

        self.getPacket()

        # Setting up the encryption box for the server
        if self.encryption:
            for pubAddr in publicKeys:
                print "Checking value for", pubAddr
                if pubAddr[0] == self.partnerAddress[0] and (
                        int(pubAddr[1]) == self.partnerAddress[1]
                        or pubAddr[1] == "*"):
                    partnerPublicKey = publicKeys[pubAddr]
                    print "Partner public Key set"
            if partnerPublicKey is None or partnerPublicKey == -1:  # This means that the partner public key isn't set. We'll assume its the default
                partnerPublicKey = hostPublicKey
            socketBox = Box(hostPrivateKey, partnerPublicKey)
        print "Socketbox successfully created"

        (clientsocket, address) = (self, self.partnerAddress)
        return (clientsocket, address)
コード例 #26
0
def read_config(section=None, config_path='/tmp/secrets.conf', private_key=''):
    """
    reads credentials section or app with data in specific configuration path using a private key
    data keys prefixed with __ are considered private and will be encrypted.

    @param section str: application or section name.
        e.g: myapp, githubuser, gitlaborg
    @param config_path str: secretconf path defaults to /tmp/secrets.conf
    @param private_key: key of 32 bytes (you should use sha256 or hash32 function on the bytes of your private key)
     """

    data = {}
    if not os.path.exists(config_path):
        os.makedirs(os.path.dirname(config_path), exist_ok=True)
        os.mknod(config_path)

    conf = ConfigParser()
    conf.read_file(open(config_path))

    sk = PrivateKey(private_key, nacl.encoding.Base64Encoder())
    pk = sk.public_key
    box = Box(sk, pk)

    for s in conf.sections():
        secdict = {}
        for k, v in conf[s].items():
            if k.startswith("__"):
                v = decrypt(v, box)
            secdict[k] = v
        data[s] = secdict

    return data
コード例 #27
0
ファイル: keys.py プロジェクト: jamesaxl/scripts
    def key_select(self):
        """Environment Setup"""
        import base64, nacl.utils, zlib
        from lib.keys import PyNaCl_keys
        from nacl.public import PrivateKey, PublicKey, Box
        pynacl = PyNaCl_keys()
        kChoice = raw_input(
            '[G]enerate a Private Key or [I]mport a Private Key?\n')
        if (kChoice == 'g' or kChoice == 'G'):
            privObj, privKey = pynacl.key_gen()
            kSave = raw_input('\nSave the key? [y/N]\n')
            if (kSave == 'y' or kSave == 'Y'):
                print ''
                pynacl.key_save(privKey)
            print '\nYour Public Key is:\n%s' % pynacl.key_exp(privObj)
        elif (kChoice == 'i' or kChoice == 'I'):
            print ''
            from lib.crypto_env import GPG_env
            cType = GPG_env()
            plainKey = pynacl.key_imp()
            plainObj = zlib.decompress(base64.b64decode(plainKey))
            privObj = PrivateKey(plainObj)
            print '\nYour Public Key is:\n%s' % pynacl.key_exp(privObj)

        ## Import partner public key
        partner_plain = raw_input(
            '\nEnter Plaintext Public Key of Chat Partner:\n')
        print ''

        ## Can probably enclose this within PublicKey()
        partner_obj = zlib.decompress(base64.b64decode(partner_plain))
        partner_enc = PublicKey(partner_obj)

        ## Create a box for chat
        return Box(privObj, partner_enc), privObj, partner_enc
コード例 #28
0
def make_config(section=None,
                data=None,
                config_path='/tmp/secrets.conf',
                private_key=''):
    """
    stores credentials section or app with data in specific configuration path using a private key
    data keys prefixed with __ are considered private and will be encrypted.

    @param section str: application or section name.
        e.g: myapp, githubuser, gitlaborg
    @param data dict: dict of fields and their values [fields prefixed with __ are private]
        e.g: {'name': 'xmonader', '__password': '******'}

    @param config_path str: secretconf path defaults to /tmp/secrets.conf
    @param private_key: key of 32 bytes (you should use sha256 or hash32 function on the bytes of your private key)
     """
    data = data or {}
    if not os.path.exists(config_path):
        os.makedirs(os.path.dirname(config_path), exist_ok=True)
        os.mknod(config_path)
    conf = ConfigParser()
    conf.read_file(open(config_path))
    conf[section] = {}
    sk = PrivateKey(private_key, nacl.encoding.Base64Encoder())

    pk = sk.public_key
    box = Box(sk, pk)

    for k, v in data.items():
        if k.startswith("__"):
            v = encrypt(v, box)
        conf[section][k] = v

    with open(config_path, "w") as cf:
        conf.write(cf)
コード例 #29
0
def generate_fileserver_info():
    cluster_crypto_box = Box(
        PrivateKey(CLUSTER_PRIVATE_KEY, encoder=nacl.encoding.HexEncoder),
        PublicKey(SERVER_PUBLIC_KEY, encoder=nacl.encoding.HexEncoder))

    nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)
    encrypted = cluster_crypto_box.encrypt(
        json.dumps({
            'VERSION': VERSION,
            'HOSTNAME': HOSTNAME,
            'CLUSTER_ID': CLUSTER_ID,
            'FILESERVER_ID': FILESERVER_ID,
            'FILESERVER_PUBLIC_KEY': PUBLIC_KEY,
            'FILESERVER_SESSION_KEY': FILESERVER_SESSION_KEY,
            'SHARDS_PUBLIC': SHARDS_PUBLIC,
            'READ': READ,
            'WRITE': WRITE,
            'DELETE': DELETE,
            'ALLOW_LINK_SHARES': ALLOW_LINK_SHARES,
            'IP_READ_WHITELIST': IP_READ_WHITELIST,
            'IP_WRITE_WHITELIST': IP_WRITE_WHITELIST,
            'IP_READ_BLACKLIST': IP_READ_BLACKLIST,
            'IP_WRITE_BLACKLIST': IP_WRITE_BLACKLIST,
            'HOST_URL': HOST_URL,
        }).encode("utf-8"), nonce)

    return nacl.encoding.HexEncoder.encode(encrypted).decode()
コード例 #30
0
    def init(self, threebot_name: str, passwd: str, new=True) -> list:
        try:
            user = self.explorer.users.get(name=threebot_name)
        except requests.exceptions.HTTPError:
            raise j.exceptions.NotFound(f"3Bot name {threebot_name} is not found")

        verify_key = nacl.signing.VerifyKey(binascii.unhexlify(user.pubkey))
        box = Box(self.PRIVATE_KEY, verify_key.to_curve25519_public_key())
        password_backup = box.decrypt(passwd.encode(), encoder=nacl.encoding.Base64Encoder).decode()
        threebot_name = threebot_name.split(".")[0]
        if new:
            self._htpasswd(self.ssh_server1, threebot_name, password_backup)
            self._htpasswd(self.ssh_server2, threebot_name, password_backup)
        else:
            try:
                self.ssh_server1.sshclient.run(
                    "cd ~/backup; htpasswd -vb  .htpasswd {threebot_name} {password_backup}".format(
                        threebot_name=quote(threebot_name), password_backup=quote(password_backup)
                    )
                )
                self.ssh_server2.sshclient.run(
                    "cd ~/backup; htpasswd -vb  .htpasswd {threebot_name} {password_backup}".format(
                        threebot_name=quote(threebot_name), password_backup=quote(password_backup)
                    )
                )
            except:
                raise j.exceptions.Value(f"3Bot name or password are incorrect")

        return [self.ssh_server1.host, self.ssh_server2.host]