예제 #1
0
def encrypt(key, message):
    """
    Encrypt message with Public Key
    """
    public_key = PublicKey.load_pkcs1(key.encode(ENCODING))
    enc_msg = rsa_encrypt(message.encode(ENCODING), public_key)
    return enc_msg.decode(ISO_ENCODING)
예제 #2
0
파일: utils.py 프로젝트: esrefozturk/poa
def validate_block(data):
    sha = hasher.sha256()
    sha.update(
        str(data['index']) + str(data['timestamp']) + str(data['payload']) +
        str(data['previous_hash']))
    hash = sha.hexdigest()

    if hash != data['hash']:
        return False

    PUB = PublicKey.load_pkcs1('''
        -----BEGIN RSA PUBLIC KEY-----
        {p}
        -----END RSA PUBLIC KEY-----
        '''.format(p='\n'.join(
        [data['miner'][i:i + 64] for i in range(0, len(data['miner']), 64)])))

    if not verify(hash, data['sign'].decode('hex'), PUB):
        return False

    MINER_PUBS = loads(Block.objects.get(index=0).payload)['miners']
    if not data['miner'] in MINER_PUBS:
        return False

    for i in data['transactions']:
        validate_transaction(i)

    return True
예제 #3
0
def rsa_load_key(public_file=None, private_file=None, dir=None):
    """
    Загружаем ключи из файлов
    :param public_file: файл публичного ключа
    :param private_file: файл приватного ключа
    :param dir: папка с ключами
    :return: возвращаем публичный и приватный ключи
    """
    try:
        if dir:
            if dir[-1] not in sep:
                dir += sep
            public_file = dir + 'public.key'
            private_file = dir + 'private.key'

            if not exists(public_file) or not exists(private_file):
                raise IOError("Key files not found!")

            with open(public_file, 'rb') as f:
                public_file = f.read()
            with open(private_file, 'rb') as f:
                private_file = f.read()
        pubkey = PublicKey.load_pkcs1(keyfile=public_file)
        privkey = PrivateKey.load_pkcs1(keyfile=private_file)
        return pubkey, privkey
    except IOError as e:
        print("Error: %s" % e)
        return None, None
예제 #4
0
 def _load_key_file(self):
     # 从.pem文件中读取key
     try:
         with open(self._key_source) as f:
             p = f.read()
             self._pub_rsa_key = PublicKey.load_pkcs1(p.encode())
     except Exception as error:
         raise error
예제 #5
0
 def from_files(cls,
                pub_path: str,
                priv_path: str,
                key_format: str = 'PEM') -> 'Rsa':
     """Parse an RSA keypair from existing files."""
     with open(pub_path, "rb") as f:
         pub = PublicKey.load_pkcs1(f.read(), format=key_format)
     with open(priv_path, "rb") as f:
         priv = PrivateKey.load_pkcs1(f.read(), format=key_format)
     return cls(pub, priv)
예제 #6
0
파일: crypto.py 프로젝트: arkaic/hermes
def public_key_from_file(filepath):
    """ Loads a public key from a given filepath.

    Args:
        filepath (string): A path to the file which contains the public key in a PEM format.
    Returns:
        rsa.PublicKey: The public key that results from reading the given file.
    """
    with open(filepath, 'rb') as f:
        pk = PublicKey.load_pkcs1(f.read(), format='PEM')
    return pk
예제 #7
0
 def _load_key_file_exe(self):
     try:
         if getattr(sys, 'frozen', False):  # 是否Bundle Resource
             base_path = sys._MEIPASS
         else:
             base_path = os.path.abspath(".")
         with open(os.path.join(base_path, self._key_source)) as f:
             p = f.read()
             self._pub_rsa_key = PublicKey.load_pkcs1(p.encode())
     except Exception as error:
         raise error
예제 #8
0
파일: main.py 프로젝트: qiacu/RemoteControl
def encryp(data):
    """
    使用RSA对byte类型的数据进行加密
    """
    global public_key
    if public_key is None:
        with open("source/keys/pubkey.pem", "rb") as x:
            public_key = x.read()
            public_key = PublicKey.load_pkcs1(public_key)  # 取公钥

    data = bytes(str(data), encoding='utf8')
    return encrypt(data, public_key)  # 返回加密结果
예제 #9
0
파일: utils.py 프로젝트: esrefozturk/poa
def verify_transaction(t):
    PUB = PublicKey.load_pkcs1('''
        -----BEGIN RSA PUBLIC KEY-----
        {p}
        -----END RSA PUBLIC KEY-----
        '''.format(
        p='\n'.join([t.sender[i:i + 64]
                     for i in range(0, len(t.sender), 64)])))

    if not verify(t.hash, t.sign.decode('hex'), PUB):
        return False
    return True
예제 #10
0
def f(cipher, PUBLIC_KEY):
    public_key = PublicKey.load_pkcs1(PUBLIC_KEY)
    encrypted = transform.bytes2int(cipher)
    decrypted = core.decrypt_int(encrypted, public_key.e, public_key.n)
    text = transform.int2bytes(decrypted)

    if len(text) > 0 and text[0] == '\x01':
        pos = text.find('\x00')
        if pos > 0:
            return text[pos + 1:]
        else:
            return None
예제 #11
0
파일: crypto.py 프로젝트: arkaic/hermes
def public_key_from_str(public_key_str):
    """ Interprets a PEM-formatted string into a PublicKey object.

    Args:
        public_key_str (bytearray): The bytearray that represents the public key
                                    in a PEM format.

    Returns:
        rsa.PublicKey: The public key that is the result of interpreting the
                       PEM-formatted bytearray.

    """
    return PublicKey.load_pkcs1(public_key_str, format='PEM')
예제 #12
0
 def _gen_rsa_pubkey(self):
     # 将pub key string 转换为 pub rsa key
     # p.debug("Now turn key string to rsa key")
     try:
         rsa_pubkey = PublicKey(self._modulus, self._exponent)
         # 赋值到_pub_rsa_key
         self._pub_rsa_key = PublicKey.load_pkcs1(rsa_pubkey.save_pkcs1())
         # print("self._pub_rsa_key:{}".format(rsa_pubkey))
         # p.error("self._pub_rsa_key:{}".format(self._pub_rsa_key))
     except Exception as e:
         # p.error(e)
         # p.error("Invalid public_key")
         raise e
예제 #13
0
def decrypt_with_public_key(decrypt_key_file, cipher_text):
    key = open(decrypt_key_file, "rb").read()
    pk = PublicKey.load_pkcs1(key)
    encrypted = transform.bytes2int(base64.b64decode(cipher_text))
    decrypted = core.decrypt_int(encrypted, pk.e, pk.n)
    text = transform.int2bytes(decrypted)

    if len(text) > 0 and text[0] == 1:
        pos = text.find(b'\x00')
        if pos > 0:
            return text[pos + 1:]
        else:
            return None
예제 #14
0
 def push_aes_key(self):
     from rsa import PublicKey, encrypt
     from random import sample
     from string import digits, ascii_letters, punctuation
     # 生成AES密钥
     key_rules = digits + ascii_letters + punctuation
     self.key = ''.join(sample(key_rules * 10, 32))
     # 导入加密公钥
     with open('public.pem', 'r') as f:
         pub_key = PublicKey.load_pkcs1(f.read().encode())
     # 加密数据
     crypto = encrypt(self.key.encode(), pub_key)
     return crypto
예제 #15
0
파일: token.py 프로젝트: ozmy/tg-forward
    def _load_rsa_keys(self) -> Tuple[PublicKey, PrivateKey]:
        """Load RSA keys from filesystem"""
        self.logger.debug("Load public key from %s", self.__pub_key_path)
        with open(self.__pub_key_path, "rb") as pem_file:
            pub_key_data = pem_file.read()
        self.logger.debug("RSA public key loaded")

        self.logger.debug("Load private key from %s", self.__priv_key_path)
        with open(self.__priv_key_path, "rb") as pem_file:
            priv_key_data = pem_file.read()
        self.logger.debug("RSA private key loaded")

        return PublicKey.load_pkcs1(pub_key_data), PrivateKey.load_pkcs1(
            priv_key_data)
예제 #16
0
파일: wallet.py 프로젝트: ksdme/toycoin
    def load_wallet(uri):
        """
            loads a wallet from a public key file
            and a private key file
        """
        assert not isdir(uri)

        with ZipFile(uri, "r") as walletfile:
            pub_key = (PublicKey.load_pkcs1(
                walletfile.read(WalletConf.PUBLIC_KEY_FILE_NAME)))

            priv_key = PrivateKey.load_pkcs1(
                walletfile.read(WalletConf.PRIVATE_KEY_FILE_NAME))

        return pub_key, priv_key
예제 #17
0
    def verify(self, pubkey):
        """
        pubkey: 公钥
        """
        with open(pubkey, 'r') as f1:
            pub_key = PublicKey.load_pkcs1(f1.read().encode())

        with open(self.hash_file, 'rb') as f:
            mess = f.read()

        with open(self.sha, 'rb') as f:
            s_sign = f.read()
        try:
            ver = verify(mess, s_sign, pub_key)
            print('验证成功,使用的哈希算法是:%s' % ver)
        except pkcs1.VerificationError:
            print('验证不通过')
예제 #18
0
def main():
    if len(argv) < 2:
        print 'Format: enc.py <image>'
        return

    qr = QR()
    qr.decode(argv[1])

    TEXT = qr.data

    MESSAGE = TEXT[:100].strip('*\r\n')
    SIGN = TEXT[100:500].strip('*\r\n').decode('hex')
    ID = TEXT[500:].strip('*\r\n')

    publickey = PublicKey.load_pkcs1(open('DB/' + ID + '.pub').read())

    if verify(MESSAGE, SIGN, publickey):
        print MESSAGE
    else:
        print 'VERIFICATION FAILED!'
예제 #19
0
파일: utils.py 프로젝트: esrefozturk/poa
def validate_transaction(transaction):
    sha = hasher.sha256()
    sha.update(
        str(transaction['sender']) + str(transaction['receiver']) +
        str(transaction['amount']) + str(transaction['timestamp']))
    hash = sha.hexdigest()

    if hash != transaction['hash']:
        return False

    PUB = PublicKey.load_pkcs1('''
        -----BEGIN RSA PUBLIC KEY-----
        {p}
        -----END RSA PUBLIC KEY-----
        '''.format(p='\n'.join([
        transaction['sender'][i:i + 64]
        for i in range(0, len(transaction['sender']), 64)
    ])))

    if not verify(hash, transaction['sign'].decode('hex'), PUB):
        return False
예제 #20
0
파일: crypto.py 프로젝트: arkaic/hermes
def decrypt_pubkey(ciphertext, decrypt_key):
    """ This is a variant of the asymmetric_decrypt_verify() function that is 
        meant to be used to verify a public key that was signed by the 
        associated private key. More specifically this function takes a 
        bytearray containing the ciphertext of a public key and its prepended 
        signature of 512 bytes. The function decrypts the ciphertext, creates 
        the public key object from the plaintext, and then verifies the message 
        with the public key. This function is designed primarily to establish 
        the fact that the client sending the public key is indeed the owner of 
        the private key. There is an issue with this function in that anyone 
        could listen to someone sending the same message and just resend it, 
        which would pass verification. In the Hermes protocol the server needs 
        to send a challenge to the client after this function.

    Args:
        ciphertext (bytearray): The ciphertext that is to be decrypted. 
                                The decrypted message of this ciphertext needs
                                to be the public key of the client with the 
                                signature of the public key prepended.
        decrypt_key (rsa.PrivateKey): The private key object that should be 
                                      used to decrypt the message.
    Returns:
        bytearray: A byte array containing the plaintext of the message as long 
                   as the verification passes, and None otherwise.
    """
    plaintext, signature = asymmetric_decrypt(ciphertext, decrypt_key)
    if plaintext and signature:
        try:
            public_key = PublicKey.load_pkcs1(plaintext, format='PEM')
            verify(plaintext, signature, public_key)
        except pkcs1.VerificationError:
            log("WARNING: RSA Verification Failed\n\tPLAINTEXT({0}): {1} \n\t"
                "SIGNATURE({2}): {3}".format(len(plaintext),
                                             plaintext,
                                             len(signature),
                                             signature))
            return None
        return plaintext
예제 #21
0
import os

from rsa import common, transform, core, PrivateKey, PublicKey

from frame.http.exception import BusiError

try:
    current_path = os.path.abspath(__file__)
    grader_father = os.path.abspath(
        os.path.dirname(current_path) + os.path.sep + "..")
    pubkey = PublicKey.load_pkcs1(open("resource/public.pem").read())
    privkey = PrivateKey.load_pkcs1(open("resource/private.pem").read())
except:
    raise BusiError("证书文件路径错误!")


def _pad_for_encryption(message, target_length):
    max_msglength = target_length - 11
    msglength = len(message)
    if msglength > max_msglength:
        raise OverflowError("%i bytes needed for message, but there is only"
                            " space for %i" % (msglength, max_msglength))
    padding = b""
    padding_length = target_length - msglength - 3

    while len(padding) < padding_length:
        needed_bytes = padding_length - len(padding)
        new_padding = os.urandom(needed_bytes + 5)
        new_padding = new_padding.replace(b"\x00", b"")
        padding = padding + new_padding[:needed_bytes]
    assert len(padding) == padding_length
예제 #22
0
strings = []
disconnected = False
prog_is_alive = True
HOST, PORT = '127.0.0.1', 9090
nickname = ''

if __name__ == '__main__':
    try:
        while prog_is_alive:
            server_listener = Server_listener()
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            connect_to_server(HOST, PORT)

            #establishing a secure connection
            tagged_server_pub = sock.recv(1024)
            server_pub = PublicKey.load_pkcs1(tagged_server_pub)
            xor_encrypted_key = rsa_encrypt(xor_key, server_pub)
            sock.send(xor_encrypted_key)

            disconnected = False
            nickname = pick_username()
            server_listener.start()
            user_colors[nickname] = colors['blue']
            while not disconnected:
                message = get_msg()
                if len(message) > 255:
                    add_str('system: 255 symbols message limit')
                    continue
                if not (message.strip() in ('', '\n', '\t', '\r')):
                    if message[0] == '!':
                        command = parse_command(message)
예제 #23
0
def import_key(extern_key, passphrase=None):
    """Import an RSA key (public or private half), encoded in standard
    form.

    :Parameter extern_key:
        The RSA key to import, encoded as a byte string.

        An RSA public key can be in any of the following formats:

        - X.509 certificate (binary or PEM format)
        - X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM
          encoding)
        - `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding)
        - OpenSSH (textual public key only)

        An RSA private key can be in any of the following formats:

        - PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding)
        - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
          DER SEQUENCE (binary or PEM encoding)
        - OpenSSH (textual public key only)

        For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.

        The private key may be encrypted by means of a certain pass phrase
        either at the PEM level or at the PKCS#8 level.
    :Type extern_key: string

    :Parameter passphrase:
        In case of an encrypted private key, this is the pass phrase from
        which the decryption key is derived.
    :Type passphrase: string

    :Return: An RSA key object (`RsaKey`).

    :Raise ValueError/IndexError/TypeError:
        When the given key cannot be parsed (possibly because the pass
        phrase is wrong).

    .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
    .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
    .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
    .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
    """
    if passphrase is not None:
        raise ValueError("RSA key passphrase is not supported")
    if extern_key.startswith('ssh-rsa '):
        # This is probably an OpenSSH key
        keystring = binascii.a2b_base64(extern_key.split(' ')[1])
        keyparts = []
        while len(keystring) > 4:
            l = struct.unpack(">I", keystring[:4])[0]
            keyparts.append(keystring[4:4 + l])
            keystring = keystring[4 + l:]
        e = Integer.from_bytes(keyparts[1])
        n = Integer.from_bytes(keyparts[2])
        return PublicKey(n._value, e._value)

    for fmt in ("PEM", "DER"):
        try:
            return PrivateKey.load_pkcs1(extern_key, fmt)
        except:
            try:
                return PublicKey.load_pkcs1(extern_key, fmt)
            except:
                pass

    raise ValueError("RSA key format is not supported")