Esempio n. 1
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 main():
    if len(argv) < 3:
        print 'Format: enc.py <identifier> <message>'
        return

    ID = argv[1]  # Identifier of origin
    MESSAGE = argv[2]

    # Read private key of origin
    with open(ID + '.pr', 'r') as f:
        privatekey = PrivateKey.load_pkcs1(f.read())

    # Sign message with private key
    SIGN = sign(MESSAGE, privatekey, 'SHA-256').encode('hex')

    # Concatenate message, signature and identifier
    TEXT = padding(MESSAGE, 100) + padding(SIGN, 400) + padding(ID, 100)

    # Create QR code
    qr = QRCode(
        version=1,
        error_correction=ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )

    qr.add_data(TEXT)
    qr.make(fit=True)

    img = qr.make_image()
    img.save(ID + '.png')
Esempio n. 3
0
    def __init__(self, private_key_data):
        """

        :param private_key_data:
        """
        self.private_key_data = private_key_data
        self.pk = PrivateKey.load_pkcs1(private_key_data, 'PEM')
def pack_license_key(data, privkey_args):
    """
    Pack a dictionary of license key data to a string. You typically call this
    function on a server, when a user purchases a license. Eg.:

        lk_contents = pack_license_key({'email': '*****@*****.**'}, ...)

    The parameter `privkey_args` is a dictionary containing values for the RSA
    fields "n", "e", "d", "p" and "q". You can generate it with fbs's command
    `init_licensing`.

    The resulting string is signed to prevent the end user from changing it.
    Use the function `unpack_license_key` below to reconstruct `data` from it.
    This also verifies that the string was not tampered with.

    This function has two non-obvious caveats:

    1) It does not obfuscate the data. If `data` contains "key": "value", then
       "key": "value" is also visible in the resulting string.

    2) Calling this function twice with the same arguments will result in the
    same string. This may be undesirable when you generate multiple license keys
    for the same user. A simple workaround for this is to add a unique parameter
    to `data`, such as the current timestamp.
    """
    data_bytes = _dumpb(data)
    signature = rsa.sign(data_bytes, PrivateKey(**privkey_args), 'SHA-1')
    result = dict(data)
    if 'key' in data:
        raise ValueError('Data must not contain an element called "key"')
    result['key'] = b64encode(signature).decode('ascii')
    return json.dumps(result)
    def __add_private_key_to_blockchain(
            self,
            blockchain: Blockchain,
            medical_data_transaction_id: str,
            private_key_for_medical_data: PrivateKey,
            third_party=None):
        """
        create a new acl entry via acl_data
        :param blockchain: the wordlwide blockchain
        :param acl_name: the name of the acl_name
        :param acl_data: list of {transaction_id : private_key}.
         The private_key decrypt the data in the transaction with the id transaction_id
        :return:
        """
        third_party = third_party or self
        key_name = f'atomic ACL for {medical_data_transaction_id}'

        acl_data_json = json.dumps({
            'key_name':
            key_name,
            'private_key':
            private_key_for_medical_data.save_pkcs1().decode('utf8'),
            'medical_data_transaction_id':
            medical_data_transaction_id,
        })

        crypted_medical_data = CryptingTools.crypt_data(
            acl_data_json, self.get_public_key())
        transaction = blockchain.add_transaction(crypted_medical_data, self,
                                                 third_party)
        transaction_id = transaction.id

        self.add_key_to_keychain(key_name, [transaction_id])
        return transaction_id
Esempio n. 6
0
def main():
    command = sys.argv[1]
    if command == 'create_new_wallet':
        create_new_wallet()
        return

    PUB = ''.join(open('rsa.pub').read().split('\n')[1:4])

    receiver = command
    amount = sys.argv[2]
    timestamp = time()

    sha = hasher.sha256()
    sha.update(str(PUB) + str(receiver) + str(amount) + str(timestamp))
    hash = sha.hexdigest()

    with open('rsa.pri', 'r') as f:
        PRI = PrivateKey.load_pkcs1(f.read())

    sig = sign(hash, PRI, 'SHA-256').encode('hex')

    try:
        requests.post('http://{ip}:8000/new_transaction/'.format(
            ip=MINERS[randint(0,
                              len(MINERS) - 1)]),
                      data={
                          'timestamp': timestamp,
                          'sender': PUB,
                          'receiver': receiver,
                          'amount': amount,
                          'hash': hash,
                          'sign': sig,
                      })
    except:
        pass
 def _load_key_file(self, file):
     # 从.pem文件中读取key
     try:
         with open(file) as f:
             p = f.read()
             self._private_key = PrivateKey.load_pkcs1(p.encode())
     except Exception as error:
         raise error
Esempio n. 8
0
def private_key_from_pref(pref_cert):
    """Load private key from string."""
    if PYTHONTHREE:
        private_key = PrivateKey.load_pkcs1(base64.b64decode(pref_cert))
    else:
        private_key = load_privatekey(FILETYPE_PEM, base64.b64decode(pref_cert))

    return private_key
Esempio n. 9
0
def get_client_pri_key():
    return PrivateKey(
        9659409811222239424053139659514350094343427389834135540932282496665611583618159590834922783558917852795055561382877564364710885749628173307757081925597489,
        65537,
        1350522179840843795758104867481422553892744940614464866587767284388162395131790899554868688522906461439000088568816762804091645889133667242002096698398417,
        5559425529932599305598725281545023902835884959815769154010890312251665313855301237,
        1737483443067065782717045867372208780049132259225788701387959997763307597
    )
Esempio n. 10
0
def private_key_from_pref_data(pref_cert):
    """Load private key from NSData."""
    if PYTHONTHREE:
        private_key = PrivateKey.load_pkcs1(bytes(pref_cert))
    else:
        private_key = load_privatekey(FILETYPE_PEM, str(pref_cert))

    return private_key
 def _load_key_file(self, file):
     # 从.pem文件中读取key
     try:
         with open(file) as f:
             p = f.read()
             self._private_key = PrivateKey.load_pkcs1(p.encode())
         return True
     except Exception as error:
         print(error)
         return False
Esempio n. 12
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('长度异常')
Esempio n. 13
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)
Esempio n. 14
0
def private_key_from_file(key_file):
    """Load private key from file path."""
    with open(key_file, 'r') as f:
        data = f.read()

    if PYTHONTHREE:
        private_key = PrivateKey.load_pkcs1(data.encode('utf8'))
    else:
        private_key = load_privatekey(FILETYPE_PEM, data)

    return private_key
Esempio n. 15
0
def private_key_from_str(private_key_str):
    """ Loads a private key from a given PEM-formatted string.

    Args:
        private_key_str (bytearray): A byte string which contains the private 
                                     key in a PEM format.
    Returns:
        rsa.PrivateKey: The private key that results from reading the given 
                        file.
    """
    return PrivateKey.load_pkcs1(private_key_str, format='PEM')
Esempio n. 16
0
    def decrypt(self, crypt_path, name):
        with open(self.privkey, "r") as f2:
            priv_key = PrivateKey.load_pkcs1(f2.read().encode())

        with open(name, "rb") as f3:
            mge = f3.read()

        un_rsa_key = decrypt(mge, priv_key).decode()
        key_file = os.path.join(crypt_path, name[0:-4])
        with open(key_file, "w+") as f4:
            f4.write(un_rsa_key)
Esempio n. 17
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)
Esempio n. 18
0
 def _sign(self, content):
     if keystore is None or not path.exists(keystore):
         raise IllegalArgumentException(
             'Unable to find the keystore: ' + keystore)
     with open(keystore, 'r') as key_file:
         private_key = PrivateKey.load_pkcs1(key_file.read().encode())
     try:
         signature = sign(content, private_key, 'SHA-256')
         return urlsafe_b64encode(signature)
     except TypeError:
         signature = sign(content.encode(), private_key, 'SHA-256')
         return urlsafe_b64encode(signature).decode()
Esempio n. 19
0
def private_key_to_str(private_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:
        private_key (rsa.PrivateKey): 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 PrivateKey.save_pkcs1(private_key, format='PEM')
Esempio n. 20
0
    def sign(self, privkey):
        """
        privkey: 私钥
        """
        with open(privkey, "r")as f1:
            priv_key = PrivateKey.load_pkcs1(f1.read().encode())

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

        with open(self.sha, 'wb') as f:
            f.write(sign(mess, priv_key, 'SHA-256'))
Esempio n. 21
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)
Esempio n. 22
0
def private_key_from_file(filepath):
    """ Loads a private key from a given filepath.

    Args:
        filepath (string): A path to the file which contains the private key in 
                           a PEM format.
    Returns:
        rsa.PrivateKey: The private key that results from reading the given 
                        file.
    """
    with open(filepath, 'rb') as f:
        pk = PrivateKey.load_pkcs1(f.read(), format='PEM')
    return pk
Esempio n. 23
0
def getPrivateKeyFromPS(path) -> PrivateKey:
    from source.util.ToolsFuc import StrToInt
    from source.core.const.Const import NUM_DICT_M
    file = open(path, 'rb')
    byte = file.read()
    file.close()
    pks = byte.decode('utf-8')
    pko = json.loads(pks)
    return PrivateKey(StrToInt(pko[0],
                               NUM_DICT_M), StrToInt(pko[1], NUM_DICT_M),
                      StrToInt(pko[2],
                               NUM_DICT_M), StrToInt(pko[3], NUM_DICT_M),
                      StrToInt(pko[4], NUM_DICT_M))
Esempio n. 24
0
 def requester(self, encrypted_hash_val):
     private_key = open('private_key_rsa.txt', 'r').read().split(',')
     private_key = PrivateKey(int(private_key[0]), int(private_key[1]),
                              int(private_key[2]), int(private_key[3]),
                              int(private_key[4]))
     try:
         hash_val = decrypt(encrypted_hash_val, private_key)
     except:
         print('Not an Authentic User')
         """If an error is raised here then the connection should be disconnected"""
         # code for disconnecting service and prompting user of failure
     """ 'hash' to be sent to verifier through server and verifier checks data"""
     """ if data is same as sent data then authentication is sucessfull"""
Esempio n. 25
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)
Esempio n. 26
0
def private_key_to_file(private_key, filepath):
    """ Writes a private 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:
        private_key (rsa.PrivateKey): 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 = PrivateKey.save_pkcs1(private_key, format='PEM')
        f.write(pk)
Esempio n. 27
0
    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
Esempio n. 28
0
 def __set_privkey(self, priv_key):
     """
     设置私钥
     :param priv_key:
     :return:
     """
     if self._key_is_hex:
         b_str = a2b_hex(priv_key)
         priv_key = b64encode(b_str)
     pkl = self._convert_key(priv_key, is_pubkey=False)
     n = int(pkl[0], 16)
     e = int(pkl[1], 16)
     d = int(pkl[2], 16)
     p = int(pkl[3], 16)
     q = int(pkl[4], 16)
     self.__priv_key = PrivateKey(n, e, d, p, q)
Esempio n. 29
0
    def miner_Side(self):
        file_obj = open('miner_private_key.txt', 'r')
        arr = file_obj.read().split(',')
        file_obj.close()
        p_key = PrivateKey(int(arr[0]), int(arr[1]), int(arr[2]), int(arr[3]),
                           int(arr[4]))
        try:
            self.block_address = int(decrypt(self.block_address, p_key))
        except:
            print('Error raised disconnecting the service')
            """If an error is raised here then the connection should be disconnected"""
            #code for disconnecting service and prompting user of failure

        self.req_pu_key = BlockChain.obj.blockchain[
            self.block_address]['auth_public_key'].split(',')
        self.verifier()
Esempio n. 30
0
File: core.py Progetto: jarig/suton
 def __init__(self, connection_string, keys_folder):
     super().__init__(connection_string, keys_folder)
     self._data = json.loads(connection_string)
     self._private_key = None
     if self._data.get("encryption_key_name"):
         if not os.path.exists(
                 os.path.join(keys_folder,
                              self._data.get("encryption_key_name"))):
             raise Exception(
                 "Couldn't initialize environment-based secret-manager, as encryption name with name {} do not exist."
                 .format(self._data.get("encryption_key_name")))
         with open(
                 os.path.join(keys_folder,
                              self._data.get("encryption_key_name")),
                 "rb") as f:
             # PEM key
             self._private_key = PrivateKey.load_pkcs1(f.read())
Esempio n. 31
0
    def test_many_encrypt_decrypt_fixed_data(self):
        priv_key = PrivateKey.load_pkcs1(private_key_data)
        pub_key = PublicKey.load_pkcs1_openssl_pem(public_key_data)
        all_enc = set()
        for i in range(100):
            try:
                data = b'a simple test message, which will be encrypted'
                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)
                all_enc.add(enc)
            except BaseException as e:
                self.assertIsNone(e, i)

        # Make sure the seed is doing what it's supposed to do
        # This test might (theoretically) fail, although it really shouldn't
        # A fail here might indicate a bad RNG
        self.assertGreater(len(all_enc), 1)
Esempio n. 32
0
    def test_many_sign_verify_fixed_data(self):
        priv_key = PrivateKey.load_pkcs1(private_key_data)
        pub_key = PublicKey.load_pkcs1_openssl_pem(public_key_data)
        all_signatures = set()
        for i in range(100):
            try:
                data = b'a simple test message, which will be signed'
                signature = pkcs1_v2.sign(data, priv_key, hasher='SHA-256')
                self.assertTrue(
                    pkcs1_v2.verify(data, signature, pub_key,
                                    hasher='SHA-256'), i)
                all_signatures.add(signature)
            except BaseException as e:
                self.assertIsNone(e, i)

        # Make sure the salt is doing what it's supposed to do
        # This test might (theoretically) fail, although it really shouldn't
        # A fail here might indicate a bad RNG
        self.assertGreater(len(all_signatures), 1)
Esempio n. 33
0
# prepare environment
home = environ.get('HOME')
user = environ.get('USER')
os.chdir('{home}/.sams/'.format(home=home))

# get pubkey
addressbook = Addressbook('addressbook.csv')
own_address = addressbook.get_by_name(user)
n = int(own_address['n'])
e = int(own_address['e'])
pubkey = PublicKey(n, e)

# get privkey
with open('private.pem', 'r') as privatefile:
    keydata = privatefile.read()
privkey = PrivateKey.load_pkcs1(keydata)

# receive messages
receiver = Receiver(privkey, pubkey)
mtime = 0
files = os.listdir('messages/')
for file in files:
    filestat = os.stat('messages/{file}'.format(file=file))
    if filestat.st_mtime > mtime:
        mtime = filestat.st_mtime
if mtime:
    dt = datetime.fromtimestamp(mtime)
    messages = receiver(dt)
else:
    messages = receiver()
Esempio n. 34
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)
Esempio n. 35
0
 def __init__(self, private_key_data):
     self.private_key_data = private_key_data
     self.pk = PrivateKey.load_pkcs1(private_key_data, 'PEM')
Esempio n. 36
0
 def test_sign(self):
     priv_key = PrivateKey.load_pkcs1(private_key_data)
     sig = pkcs1_v2.sign(b'test', priv_key, salt_len=0)
     self.assertEqual(sig, sig_data)
Esempio n. 37
0
 def test_decrypt(self):
     priv_key = PrivateKey.load_pkcs1(private_key_data)
     message = pkcs1_v2.decrypt(enc_data, priv_key)
     self.assertEqual(message, b'test')
Esempio n. 38
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