示例#1
0
    def _encrypted_payload_prologue(self, envelope):
        if not self._typecheck_dict(envelope, {"public_key": str, "nonce": str,
                                               "encrypted": str}):
            self.set_status(400)
            self.json_payload(error_codes.ERROR_BAD_PAYLOAD)
            LOGGER.warn("Unable to read payload")
            return
        try:
            other_key = public.PublicKey(envelope["public_key"], KEY_ENC)
        except nacl.exceptions.CryptoError:
            LOGGER.warn("did fail req because other pk was bad")
            self.set_status(400)
            self.json_payload(error_codes.ERROR_BAD_PAYLOAD)
            return

        box = public.Box(self.settings["crypto_core"].pkey, other_key)

        try:
            nonce = nacl.encoding.Base64Encoder.decode(envelope["nonce"])
            ciphertext = nacl.encoding.Base64Encoder.decode(envelope["encrypted"])
            clear = box.decrypt(ciphertext, nonce, nacl.encoding.RawEncoder)
        except (ValueError, TypeError, nacl.exceptions.CryptoError):
            LOGGER.warn("did fail req because a base64 value was bad")
            self.set_status(400)
            self.json_payload(error_codes.ERROR_BAD_PAYLOAD)
            return

        try:
            clear = json.loads(clear.decode("utf8"))
        except (UnicodeDecodeError, TypeError):
            LOGGER.warn("did fail req because inner json decode failed")
            self.set_status(400)
            self.json_payload(error_codes.ERROR_BAD_PAYLOAD)
            return
        return clear
示例#2
0
def __encrypt_secret(public_key: str, secret_value: str) -> str:
    # https://developer.github.com/v3/actions/secrets/#example-encrypting-a-secret-using-python
    public_key = public.PublicKey(public_key.encode('utf-8'),
                                  encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode('utf-8'))
    return b64encode(encrypted).decode('utf-8')
示例#3
0
def _encrypt_github_secret(public_key, secret_value):
    """Encrypt a Unicode string using the public key."""
    public_key = public.PublicKey(public_key.encode("utf-8"),
                                  encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
    return base64.b64encode(encrypted).decode("utf-8")
示例#4
0
def del_(addr, fil):
    pkr = requests.get(addr + "/pk", verify=False)
    sk = pkr.json()["key"]

    mypub, mysec, nospam = read_tox(fil)
    check = _compute_checksum(mypub + nospam)
    print("kotone: Deleting {0} from server.".format(mypub, check))
    inner = json.dumps({
        "public_key": mypub,  # Public key
        "timestamp": int(time.time())  # Timestamp
    })

    k = crypto.PrivateKey(mysec, crypto_encode.HexEncoder)
    nonce = os.urandom(crypto.Box.NONCE_SIZE)
    b = crypto.Box(k, crypto.PublicKey(sk, crypto_encode.HexEncoder))
    msg = b.encrypt(inner.encode("utf8"), nonce, crypto_encode.Base64Encoder)

    payload = json.dumps({
        "action":
        2,
        "public_key":
        mypub,
        "encrypted":
        msg.ciphertext.decode("utf8"),
        "nonce":
        crypto_encode.Base64Encoder.encode(nonce).decode("utf8")
    })
    resp = requests.post(addr + "/api", data=payload, verify=False)
    a = resp.json()
    if a["c"] == 0:
        print("\033[32mOK:\033[0m record deleted. "
              "It may take a minute to update.")
    else:
        print("\033[32mFailed:\033[0m {0}".format(a["c"]))
        def from_ssh_key(cls, filename):
            """
            Load an Ed25519 key from a SSH key file. The key file can be a (private) signing
            key (from a SSH private key file) or a (public) verification key (from a SSH
            public key file). A private key file must be passphrase-less.
            """
            # https://tools.ietf.org/html/draft-bjh21-ssh-ed25519-02
            # http://blog.oddbit.com/2011/05/08/converting-openssh-public-keys/

            SSH_BEGIN = u'-----BEGIN OPENSSH PRIVATE KEY-----'
            SSH_END = u'-----END OPENSSH PRIVATE KEY-----'

            with open(filename, 'r') as f:
                keydata = f.read().strip()

            if keydata.startswith(SSH_BEGIN) and keydata.endswith(SSH_END):
                # SSH private key
                # ssh_end = keydata.find(SSH_END)
                # keydata = keydata[len(SSH_BEGIN):ssh_end]
                # keydata = u''.join([x.strip() for x in keydata.split()])
                # blob = binascii.a2b_base64(keydata)
                # prefix = 'openssh-key-v1\x00'
                # data = unpack(blob[len(prefix):])
                raise Exception("loading private keys not implemented")
            else:
                # SSH public key
                keydata = _read_ssh_ed25519_pubkey(filename)
                key = public.PublicKey(keydata)
                return cls(key)
示例#6
0
文件: crypto.py 项目: moshez/luggage
def decryptDict(dct, signingPrivateKey, realPrivateKey, realPublicKey):
    """decrypt all values in a dictionary

    Assumes all values in a dictionary are base64ed encrypted with realPublicKey,
    and signed with signingPrivateKey, and decrypt them with realPrivateKey.
    If realPrivateKey and realPublicKey do not correspond to each other,
    or any value in the dictionary is not signed and encrypted correctly,
    an exception is raised.

    :param dct: encrypted dictionary
    :type dct: dictionary with string values and keys
    :param signingPrivateKey: base64 encoded NaCl private key
    :type signingPrivateKey: string
    :param realPrivateKey: base64 encoded NaCl private key
    :type realPrivateKey: string
    :param realPublicKey: base64 encoded NaCl private key
    :type realPublicKey: string
    :rtype: dictionary with string values and keys
    """
    signingPrivateKey = npublic.PrivateKey(
        base64.decodestring(signingPrivateKey))
    signingPublicKey = signingPrivateKey.public_key
    realPrivateKey = npublic.PrivateKey(base64.decodestring(realPrivateKey))
    realPublicKey = npublic.PublicKey(base64.decodestring(realPublicKey))
    if realPrivateKey.public_key.encode() != realPublicKey.encode():
        raise ValueError('private key and public key do not match',
                         realPrivateKey.public_key, realPublicKey)
    box = npublic.Box(realPrivateKey, signingPublicKey)
    ret = {}
    for key, value in six.iteritems(dct):
        decodedValue = base64.decodestring(value)
        decryptedValue = box.decrypt(decodedValue)
        ret[key] = decryptedValue
    return ret
示例#7
0
def encrypt(public_key: str, secret_value: str) -> str:
    """Encrypt a Unicode string using the public key."""
    public_key = public.PublicKey(public_key.encode("utf-8"),
                                  encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
    return b64encode(encrypted).decode("utf-8")
def encrypt(encrypt_key: str, secret_value: str) -> str:
    #private_key = public.PrivateKey.generate()
    public_key = public.PublicKey(encrypt_key.encode("utf-8"),
                                  encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
    ### print(encrypted)
    return b64encode(encrypted).decode("utf-8")
示例#9
0
def encrypt_using_key(value: str, key: str) -> str:
    sealed_box = public.SealedBox(
        public.PublicKey(
            key.encode('utf-8'),
            encoding.Base64Encoder(),
        ), )
    encrypted = sealed_box.encrypt(value.encode('utf-8'))

    return base64.b64encode(encrypted).decode('utf-8')
示例#10
0
def encrypt(publicKey: str, secretValue: str) -> str:
    publicKey = public.PublicKey(publicKey.encode("utf-8"),
                                 encoding.Base64Encoder())

    sealed_box = public.SealedBox(publicKey)

    encrypted = sealed_box.encrypt(secretValue.encode("utf-8"))

    return b64encode(encrypted).decode("utf-8")
示例#11
0
def encrypt_secret(public_key, secret_value):
    """Encrypt a Unicode string using the public key."""
    from base64 import encodebytes
    from nacl import encoding, public
    public_key = public.PublicKey(public_key.encode("utf-8"),
                                  encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
    return encodebytes(encrypted).decode("utf-8")
示例#12
0
 def encrypt_secrets(self):
     logging.info(f'正在加密{self.secrets_key}')
     public_key = public.PublicKey(self.public_key['key'].encode('utf-8'),
                                   encoding.Base64Encoder())
     sealed_box = public.SealedBox(public_key)
     encrypted = sealed_box.encrypt(self.secrets_value.encode('utf-8'))
     encrypted_value = b64encode(encrypted).decode('utf-8')
     logging.info(f'加密{self.secrets_key}成功')
     return encrypted_value
示例#13
0
def encrypt_secret(public_key: str, secret_value: str) -> str:
    """ Encrypt a string for use as a GitHub secret using a public key """
    public_key = public.PublicKey(
        public_key.encode("utf-8"),
        encoding.Base64Encoder(),
    )
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
    return b64encode(encrypted).decode("utf-8")
 def _encrypt_for_github_actions(self, public_key: str,
                                 secret_value: str) -> str:
     from base64 import b64encode
     from nacl import encoding, public
     """Encrypt a Unicode string using the public key."""
     public_key = public.PublicKey(public_key.encode("utf-8"),
                                   encoding.Base64Encoder())
     sealed_box = public.SealedBox(public_key)
     encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
     return b64encode(encrypted).decode("utf-8")
示例#15
0
def encrypt(public_key: str, secret_value: str) -> str:
    """
    Encrypt a Unicode string using the public key
    https://developer.github.com/v3/actions/secrets/#example-encrypting-a-secret-using-python
    """
    public_key = public.PublicKey(public_key.encode("utf-8"),
                                  encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
    return b64encode(encrypted).decode("utf-8")
def encrypt_secret(user_public_key: str, secret_value: str):
    """
    Encrypt a Unicode string using the public key.
        https://docs.github.com/en/rest/reference/actions#create-or-update-a-repository-secret
    """
    public_key = public.PublicKey(user_public_key.encode("utf-8"),
                                  encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
    return b64encode(encrypted).decode("utf-8")
示例#17
0
    def deserialise(stream):
        # Read verification key
        bytes_vkey = stream.read(32)
        verification_key = signing.VerifyKey(bytes_vkey)

        # Read public key
        bytes_pkey = stream.read(32)
        public_key = public.PublicKey(bytes_pkey)

        # Return a new instance
        return InstanceReference(verification_key, public_key)
示例#18
0
def encrypt(public_key: str, secret_value: str) -> str:
    """Encrypt a Unicode string using the public key.

    Args:
        public_key: (str) encryption salt public key.
        secret_value: (str) value for encrypt.

    Returns:
        Encrypted Unicode string.
    """
    public_key = public.PublicKey(public_key.encode('utf-8'), encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode('utf-8'))
    return b64encode(encrypted).decode('utf-8')
示例#19
0
def encrypt_sync_secret(public_key: str, token: str) -> str:
    """
    Encrypt the sync secret (which is the PAT).

    :param public_key: Public key of the repo we want to create a secret for
    :param token: The users PAT with repo scope as the secret
    :return: The encrypted secret (PAT)
    """
    """Encrypt a Unicode string using the public key."""
    public_key = public.PublicKey(public_key.encode("utf-8"),
                                  encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(token.encode("utf-8"))

    return b64encode(encrypted).decode("utf-8")
示例#20
0
def encrypt_sync_secret(public_key: Union[str, PublicKey],
                        token: Union[str, bool]) -> str:
    """
    Encrypt the sync secret (which is the PAT).

    :param public_key: Public key of the repo we want to create a secret for
    :param token: The users PAT with repo scope as the secret
    :return: The encrypted secret (PAT)
    """
    """Encrypt a Unicode string using the public key."""
    log.debug("Encrypting Github repository secret.")
    public_key = public.PublicKey(public_key.encode("utf-8"),
                                  encoding.Base64Encoder())  # type: ignore
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(token.encode("utf-8"))  # type: ignore

    return b64encode(encrypted).decode("utf-8")
示例#21
0
    def from_ssh(cls, filename):
        """
        Load a Ed25519 public key from a SSH public key file.
        """
        # https://tools.ietf.org/html/draft-bjh21-ssh-ed25519-02
        # http://blog.oddbit.com/2011/05/08/converting-openssh-public-keys/

        SSH_BEGIN = u'-----BEGIN OPENSSH PRIVATE KEY-----'
        SSH_END = u'-----END OPENSSH PRIVATE KEY-----'
        with open(filename, 'r') as f:
            keydata = f.read().strip()

        if keydata.startswith(SSH_BEGIN):
            # private key
            ssh_end = keydata.find(SSH_END)
            keydata = keydata[len(SSH_BEGIN):ssh_end]
            keydata = u''.join([x.strip() for x in keydata.split()])
            blob = binascii.a2b_base64(keydata)
            print(blob)
            prefix = 'openssh-key-v1\x00'
            data = unpack(blob[len(prefix):])
            print(data)
            raise Exception("loading private keys not implemented")
        else:
            # public key
            try:
                algo, keydata, comment = keydata.split()
                blob = binascii.a2b_base64(keydata)
                keydata = unpack(blob)[1]
            except Exception as e:
                raise Exception("could not parse key ({})".format(e))

            if algo != u'ssh-ed25519':
                raise Exception(
                    "loading keys of type {} not implemented".format(algo))

            if len(keydata) != 32:
                raise Exception(
                    "invalid length {} for embedded raw key (must be 32 bytes)"
                    .format(len(keydata)))

            key = public.PublicKey(keydata)

            return cls(key, comment, False)
示例#22
0
文件: crypto.py 项目: moshez/luggage
def encrypt(value, signingPrivateKey, realPublicKey):
    """encrypt and sign a value, and base64-encode the result

    :param value: a secret
    :type value: string
    :param signingPrivateKey: base64 encoded NaCl private key
    :type signingPrivateKey: string
    :param realPublicKey: base64 encoded NaCl private key
    :type realPublicKey: string
    :rtype: string
    """
    signingPrivateKey = npublic.PrivateKey(
        base64.decodestring(signingPrivateKey))
    realPublicKey = npublic.PublicKey(base64.decodestring(realPublicKey))
    box = npublic.Box(signingPrivateKey, realPublicKey)
    nonce = nutils.random(npublic.Box.NONCE_SIZE)
    encrypted = box.encrypt(value, nonce)
    encoded = base64.encodestring(encrypted)
    oneline = ''.join(encoded.splitlines())
    return oneline
示例#23
0
    def encrypt(self, public_key, value):
        """
        Encrypt a Unicode string using the public key.

        :param public_key: str
        :param value: str
        :return: str
        """
        public_key_encoded = public.PublicKey(public_key.encode("utf-8"),
                                              encoding.Base64Encoder())
        sealed_box = public.SealedBox(public_key_encoded)
        encrypted = sealed_box.encrypt(value.encode("utf-8"))
        encrypted_string = self._base64encode(encrypted)

        # In Python 3.1+ base64.encodebytes inserts "\n" after every 76 bytes of output and
        # adds a trailing newline character to follow RFC 2045
        # https://docs.python.org/3/library/base64.html#base64.encodebytes
        # To make sure GitHub API accepts payload, remove "\n" from the encrypted value.
        result = encrypted_string.replace("\n", "")
        self._log("Encrypted value %s", result)
        return result
示例#24
0
        def from_ssh_key(cls, filename):
            """
            Load an Ed25519 key from a SSH key file. The key file can be a (private) signing
            key (from a SSH private key file) or a (public) verification key (from a SSH
            public key file). A private key file must be passphrase-less.
            """
            SSH_BEGIN = u'-----BEGIN OPENSSH PRIVATE KEY-----'

            with open(filename, 'r') as f:
                keydata = f.read().strip()

            if keydata.startswith(SSH_BEGIN):
                # OpenSSH private key
                keydata, comment = _read_ssh_ed25519_privkey(keydata)
                key = signing.SigningKey(keydata, encoder=encoding.RawEncoder)
            else:
                # OpenSSH public key
                keydata, comment = _read_ssh_ed25519_pubkey(filename)
                key = public.PublicKey(keydata, encoder=encoding.RawEncoder)

            return cls(key, comment)
示例#25
0
def r(addr):
    pkr = requests.get(addr + "/pk", verify=False)
    sk = pkr.json()["key"]

    k = crypto.PrivateKey.generate()
    mypub = k.public_key.encode(
        crypto_encode.HexEncoder).upper().decode("ascii")
    nospam = "00000000"

    check = _compute_checksum(mypub + nospam)
    print("kotone: Deleting {0} from server.".format(mypub, check))
    inner = json.dumps({
        "tox_id": mypub + nospam + check,
        "timestamp": int(time.time()),
        "name": "test-" + str(random.randint(0, 999999999)),
        "bio": "top test :^)",
        "privacy": 1,
    })

    nonce = os.urandom(crypto.Box.NONCE_SIZE)
    b = crypto.Box(k, crypto.PublicKey(sk, crypto_encode.HexEncoder))
    msg = b.encrypt(inner.encode("utf8"), nonce, crypto_encode.Base64Encoder)

    payload = json.dumps({
        "action":
        1,
        "public_key":
        mypub,
        "encrypted":
        msg.ciphertext.decode("utf8"),
        "nonce":
        crypto_encode.Base64Encoder.encode(nonce).decode("utf8")
    })
    resp = requests.post(addr + "/api", data=payload, verify=False)
    print(resp.text)
    a = resp.json()
    if a["c"] == 0:
        print("\033[32mOK:\033[0m ")
    else:
        print("\033[32mFailed:\033[0m {0}".format(a["c"]))
示例#26
0
    def receive_packet(self, rudp_packet, from_addr):
        """
        Process received packet and update connection state.

        Called by protocol when a packet arrives for this connection.

        If the packet is a SYN, setup encryption infrastructure;
        if not, ensure packet is successfully decrypted before
        further processing. Silently drop malicious packages.

        Args:
            rudp_packet: Received packet.Packet.
            from_addr: Sender's address as Tuple (ip, port).
        """
        if rudp_packet.syn and self._crypto_box is None:
            # Try to create a crypto box for this connection, by
            # combining remote public key and local private key.
            try:
                remote_public_key = public.PublicKey(
                    rudp_packet.payload, encoder=encoding.RawEncoder)
                self._crypto_box = public.Box(self._private_key,
                                              remote_public_key)
            except (exceptions.CryptoError, ValueError):
                pass
            else:
                self._remote_public_key = rudp_packet.payload
                super(CryptoConnection,
                      self).receive_packet(rudp_packet, from_addr)
        elif not rudp_packet.syn and self._crypto_box is not None:
            try:
                rudp_packet.payload = self._crypto_box.decrypt(
                    rudp_packet.payload)
            except (exceptions.CryptoError, exceptions.BadSignatureError,
                    ValueError):
                pass
            else:
                super(CryptoConnection,
                      self).receive_packet(rudp_packet, from_addr)
示例#27
0
def push(addr, name, bio, fil):
    pkr = requests.get(addr + "/pk", verify=False)
    sk = pkr.json()["key"]

    mypub, mysec, nospam = read_tox(fil)
    check = _compute_checksum(mypub + nospam)
    print("kotone: Publishing {0}/{1} to server.".format(mypub, check))
    inner = json.dumps({
        "tox_id": mypub + nospam + check,  # Public key + checksum
        "name": name,  # Desired name
        "privacy": 1,  # Privacy level (1 or higher appears in FindFriends)
        "bio": bio.strip(),  # Bio (quote displayed on web)
        "timestamp": int(time.time())  # A timestamp near the server's time
    })

    k = crypto.PrivateKey(mysec, crypto_encode.HexEncoder)
    nonce = os.urandom(crypto.Box.NONCE_SIZE)
    b = crypto.Box(k, crypto.PublicKey(sk, crypto_encode.HexEncoder))
    msg = b.encrypt(inner.encode("utf8"), nonce, crypto_encode.Base64Encoder)

    payload = json.dumps({
        "action":
        1,  # Action number
        "public_key":
        mypub,  # Public key
        "encrypted":
        msg.ciphertext.decode("utf8"),  # Encrypted payload base64 (above)
        "nonce":
        crypto_encode.Base64Encoder.encode(nonce).decode("utf8")  # b64
    })
    resp = requests.post(addr + "/api", data=payload, verify=False)
    a = resp.json()
    if a["c"] == 0:
        print("\033[32mOK:\033[0m record successfully published.")
        print("Password is '{0}'.".format(a["password"]))
    else:
        print("\033[32mFailed:\033[0m {0}".format(a["c"]))
示例#28
0
def encrypt(public_key, secret_value):
    public_key = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder())
    sealed_box = public.SealedBox(public_key)
    encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
    return b64encode(encrypted).decode("utf-8")
示例#29
0
 def dsrep_decode_name(self, client, nonce, pl):
     box = public.Box(self.pkey, public.PublicKey(client))
     by = box.decrypt(pl, nonce)
     return by
示例#30
0
 def dsrec_encrypt_key(self, client, nonce, msg):
     box = public.Box(self.pkey, public.PublicKey(client))
     by = box.encrypt(msg, nonce)
     return by[24:]