Example #1
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
Example #2
0
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
Example #3
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)
Example #4
0
 def __init__(self):
     self.pu_key = PublicKey(
         19735300506366648606809216260158404176991332663628844568568026082041291980614950071160539355137829291271188972558194742721953221513772994466286888523194228311787678838953845226430147092007785706549758818109192986816887331261903861953256462164040176658411001537549117573103140507145588122488253420778855640532181785964137645395870857136938675215567810046598271028199409003312375275298936097068677737339756232305563294718805792340951177321641782846630266963106739768917160296776963166674599827856065092425962157137181596241284820050081104622439052827918934452544173902432257458043382774342045732563308224737052453803991,
         65537)
     self.block_address = ''
     self.req_pu_key = ''
     self.info()
def unpack_license_key(key_str, pubkey_args):
    """
    Decode a string of license key data produced by `pack_license_key`. In other
    words, this function is the inverse of `pack_...` above:

        data == unpack_license_key(pack_license_key(data, ...), ...)

    If the given string is not a valid key, `InvalidKey` is raised.

    The parameter `pubkey_args` is a dictionary containing values for the RSA
    fields "n" and "e". It can be generated with fbs's command `init_licensing`.
    """
    try:
        result = json.loads(key_str)
    except ValueError:
        raise InvalidKey() from None
    try:
        signature = result.pop('key')
    except KeyError:
        raise InvalidKey() from None
    try:
        signature_bytes = b64decode(signature.encode('ascii'))
    except ValueError:
        raise InvalidKey() from None
    try:
        rsa.verify(_dumpb(result), signature_bytes, PublicKey(**pubkey_args))
    except VerificationError:
        raise InvalidKey() from None
    return result
Example #6
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
def encrypt_request_data(data_dict, key, modulus):
    """
    Encrypts request data using the ArcGIS Server REST Admin API Public Key from an ArcGIS Server instance.
    According to Esri's documentation, the public key should be retrieved every time a request is sent, as it may
    change. This is also backed by Esri's own software, which follows this practice and doesn't cache the key.  As
    such, each request to this function should ensure it is providing an up-to-date key/modulus pair.

    :param data_dict: The data to be encrypted. The data will not be modified, instead a new dictionary with the
        encrypted data will be returned.
    :type data_dict: Dict

    :param key: The ArcGIS Server REST Admin API RSA public key
    :type key: Integer

    :param modulus: The ArcGIS Server REST Admin API RSA modulus
    :type modulus: Integer

    :returns: A new copy of the dictionary with all values encrypted using the public key and the RSA PKCS v1.5
        algorithm.
    :rtype: Dict
    """

    rpk = PublicKey(modulus, key)
    return {
        key: b2a_hex(encrypt(bytes(value, "utf-8"), rpk))
        for key, value in iteritems(data_dict)
    }
Example #8
0
def decrypt_by_public_key(publickey, message):
    rsa_public_key = PublicKey.load_pkcs1_openssl_der(
        base64.b64decode(publickey))
    text_str = transform.bytes2int(base64.b64decode(message))
    final_text = transform.int2bytes(
        core.decrypt_int(text_str, rsa_public_key.e, rsa_public_key.n))
    final_qr_code = final_text[final_text.index(0) + 1:]
    return final_qr_code.decode()
Example #9
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
Example #10
0
 def decrypt(rsa_key, rsa_str):
     rsa_bytes = base64.decodebytes(rsa_str.encode())
     rsa_key = PublicKey.load_pkcs1_openssl_pem(rsa_key.encode())
     num = transform.bytes2int(rsa_bytes)
     decry = core.decrypt_int(num, rsa_key.e, rsa_key.n)
     out = transform.int2bytes(decry)
     sep_idx = out.index(b"\x00", 2)
     out = out[sep_idx + 1:]
     return out
Example #11
0
 def loads_publickey_from_file(file_path):
     """
     从文件中加载生成 pub_key 对象
     :param file_path:
     :return:
     """
     n, e = RsaCrypto.loads_strs_from_file(file_path).split("\n")[1].split(
         RsaCrypto.SPLIT_CODE)
     return PublicKey(int(n), int(e))
Example #12
0
def get_key(path='key.bin'): #By default path is 'key.bin'
    with open(path,'rb') as f:
        mykeybin=f.read()
    #RSA 512 has public key length of 64 bytes (512 bits)
    #These are still in byte form
    publicKey=mykeybin[3:]
    exponent=mykeybin[:3]

    rsaPubKey= PublicKey(int.from_bytes(publicKey,byteorder=BYTE_ORDER),int.from_bytes(exponent,byteorder=BYTE_ORDER))
    return rsaPubKey
Example #13
0
 def verifier(self):
     pu_key = PublicKey(int(self.req_pu_key[0]), int(self.req_pu_key[1]))
     nonce = Random_String.getRandomString() + str(time())
     hash_data = sha256(nonce.encode()).hexdigest().encode()
     crypto = encrypt(hash_data, pu_key)
     """This is the encrypted hash val generated by the verifier"""
     """This encrypted text is to be send across server to the requester"""
     """Remember if there is an error regarding 'TypeError' during transmission so inform me"""
     #Code to be written for sending data across server
     self.requester(crypto)
 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)
Example #15
0
def send_keys_handshake(sock: socket.socket,
                        sending_key: rsa.PublicKey) -> None:
    """
    :param sock: socket to send to
    :param sending_key: this key will be send to client (server)
    :param ftp_session_key: encrypted key to encrypt files
    """
    key = sending_key.save_pkcs1()
    msg = dp.write_json({'id': 'handshake', 'key': key.hex()})
    send(sock, msg.encode())
 def get_password(self, public_key_json):
     pubkey = public_key_json['pubkey']
     servertime = public_key_json['servertime']
     nonce = public_key_json['nonce']
     public_key = PublicKey(int(pubkey, 16), int('10001', 16))
     password_str = str(servertime) + '\t' + str(
         nonce) + '\n' + self.password
     password = b2a_hex(encrypt(password_str.encode('utf8'),
                                public_key)).decode('utf8')
     return password
Example #17
0
 def from_key_str_get_obj(s_key):
     # 先把 \n 去掉再获取
     args = [
         int(x) for x in s_key.split("\n")[1].split(RsaCrypto.SPLIT_CODE)
     ]
     if len(args) == 2:
         return PublicKey(*args)
     if len(args) == 5:
         return PrivateKey(*args)
     raise EOFError('长度异常')
Example #18
0
 def test_many_encrypt_decrypt(self):
     priv_key = PrivateKey.load_pkcs1(private_key_data)
     pub_key = PublicKey.load_pkcs1_openssl_pem(public_key_data)
     for i in range(100):
         try:
             data = randnum.read_random_bits(16 * 8)
             enc = pkcs1_v2.encrypt(data, pub_key, hasher='SHA-256')
             dec = pkcs1_v2.decrypt(enc, priv_key, hasher='SHA-256')
             self.assertEqual(dec, data, i)
         except BaseException as e:
             self.assertIsNone(e, i)
Example #19
0
 def load_pubkey_from_str(str_key):
     """
     str likes below, prefix and suffix are needed.
     -----BEGIN PUBLIC KEY-----
     MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEYkKp8k9wTzGMMBUrPfeMiS9R
     VBso8N8aC5hb0mJzm648kQLLJRA/wyiDu4AKSSIMsOOgtJD90ucvb5nDrQDI6+S3
     KDqkb9C1+36twe/kUcFtrTiiRPIL0ngWAOX5uXhJRZ4fvtzyOL03oOMXroxrUmR0
     +/nIst9tUud7+tbZ6QIDAQAB
     -----END PUBLIC KEY-----
     """
     return PublicKey.load_pkcs1_openssl_pem(str_key.encode())
 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
Example #21
0
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
Example #22
0
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)  # 返回加密结果
Example #23
0
def public_key_to_str(public_key):
    """ This function produces a string that represents the public key in PEM 
        format. This was it can be written to a database or transferred accross 
        an internet connection.

    Args:
        public_key (rsa.PublicKey): The key that is to be interpreted to a 
                                    PEM-format string.
    Returns:
        bytearray: A string of bytes representing the key in PEM format.
    """
    return PublicKey.save_pkcs1(public_key, format='PEM')
Example #24
0
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
Example #25
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
Example #26
0
 def test_many_sign_verify(self):
     priv_key = PrivateKey.load_pkcs1(private_key_data)
     pub_key = PublicKey.load_pkcs1_openssl_pem(public_key_data)
     for i in range(100):
         try:
             data = randnum.read_random_bits(16 * 8)
             signature = pkcs1_v2.sign(data, priv_key, hasher='SHA-256')
             self.assertTrue(
                 pkcs1_v2.verify(data, signature, pub_key,
                                 hasher='SHA-256'), i)
         except BaseException as e:
             self.assertIsNone(e, i)
Example #27
0
 def __set_pubkey(self, pubkey):
     """
     设置公钥
     :param pubkey:
     :return:
     """
     if self._key_is_hex:
         b_str = a2b_hex(pubkey)
         pubkey = b64encode(b_str)
     pkl = self._convert_key(pubkey)
     modulus = int(pkl[0], 16)
     exponent = int(pkl[1], 16)
     self.__pub_key = PublicKey(modulus, exponent)
Example #28
0
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')
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
Example #30
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
Example #31
0
def check_coin(obj, data):
    """

        {"address":<addr>, "hash":<hash>, "starter":starter}

    """
    check = config.db.find("coins", {"hash": data['hash']})
    if check:
        print "Coin already exists."
        return
    check_addr = config.nodes.find("nodes", {"address": data['address']})
    difficulty = config.db.find("coins", "all")
    if not difficulty:
        difficulty = []
    difficulty = len(difficulty) / 50500 + 7
    if difficulty < 7:
        difficulty = 7

    if check_addr:
        c = check_addr[0]
        if len(data['hash']) == 128:
            if hashlib.sha512(str(data['starter'])).hexdigest(
            ) == data['hash'] and data['hash'].startswith(
                    "1" * int(difficulty)):
                key = re.findall("([0-9]*)", c['public'])
                key = filter(None, key)
                key = PublicKey(int(key[0]), int(key[1]))
                data['plain'] = data['starter']
                data['starter'] = base64.b64encode(
                    encrypt(str(data['starter']), key))
                obj.send(json.dumps({"response": "Coin Confirmed!"}))
                while os.path.exists("db.lock"):
                    time.sleep(0.1)
                open("db.lock", 'w').close()
                for x in range((difficulty - 6) * 7):
                    config.db.insert(
                        "coins", {
                            "starter": data['starter'],
                            "hash": data['hash'],
                            "address": data['address'],
                            "difficulty": difficulty,
                            "id": uuid.uuid4().hex
                        })
                    config.db.save()
                os.remove("db.lock")
            else:
                print "Invalid Coin!"
        else:
            print "Hash not long enough"
    else:
        print "Addr invalid."
Example #32
0
 def checkSign(self):
     """check if the signature attatched to the Bounty is valid"""
     try:
         from rsa import verify, PublicKey
         safeprint(keyList)
         if self.data.get('cert'):    #where key is (PublicKey.n, PublicKey.e)
             expected = str(self).encode('utf-8')
             n = self.data.get('key')[0]
             e = self.data.get('key')[1]
             if rsa.verify(str((n,e)),self.data.get('cert'),masterKey):
                 return verify(expected,self.data.get('sig'),PublicKey(n,e))
         return False
     except:
         return False
Example #33
0
    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)
    def _validate_token_against_public_key(self, access_token, public_key):
        header, encoded_payload, signature = self._split_header_payload_signature_from_token(
            access_token)
        headers = TokenManager.load_decoded_content_as_json(header)
        if headers['alg'] != 'RS256':
            # As public key is used, algorithm has to be RS256
            raise SecurityError('Invalid algorithm!', code=401)

        decoded_signature = TokenManager.b64decode(signature)
        pubkey = PublicKey.load_pkcs1_openssl_pem(public_key)
        message = header + '.' + encoded_payload
        verified = rsa.verify(message.encode('utf-8'), decoded_signature,
                              pubkey)
        return verified, encoded_payload
Example #35
0
def bytes_to_key(mbytes):
    """
    Create rsa.PublicKey object from its serialized bytes form
    :param mbytes: bytes
    :return: rsa.PublicKey
    """

    parts = struct.unpack('>' + 64 * 'L', mbytes)

    res = 0
    for p in reversed(parts):
        res *= 2**32
        res += p

    return PublicKey(res, 2**16 + 1)
Example #36
0
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
Example #37
0
from rsa import verify, sign, encrypt, decrypt, PublicKey, PrivateKey, newkeys, pkcs1

PUB_KEY_DST = '../../tests/testing_data/user2_test_pub.pem'
PRIV_KEY_DST = '../../tests/testing_data/user2_test.pem'

(public,private) = newkeys(4096, poolsize=4)

with open(PUB_KEY_DST, 'wb+') as f:
    pk = PublicKey.save_pkcs1(public, format='PEM')
    f.write(pk)

with open(PRIV_KEY_DST, 'wb+') as f:
    pk = PrivateKey.save_pkcs1(private, format='PEM')
    f.write(pk)
Example #38
-1
def public_key_to_file(public_key, filepath):
    """ Writes a public key to a file in PEM format. This function will create a
        file if one does not exist and it will erase the contents of the file if
        it does exist.

    Args:
        public_key (rsa.PublicKey): The key that is to be written to the file.
        filepath (string): A path to the file where you wish to write the key.
    Returns:
        None
    """
    with open(filepath, 'wb+') as f:
        pk = PublicKey.save_pkcs1(public_key, format='PEM')
        f.write(pk)