Ejemplo n.º 1
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 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')
Ejemplo n.º 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
Ejemplo n.º 4
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')
Ejemplo n.º 5
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
Ejemplo n.º 6
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
 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
 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
Ejemplo n.º 9
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)
Ejemplo n.º 10
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
Ejemplo n.º 11
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')
Ejemplo n.º 12
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)
Ejemplo n.º 13
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)
Ejemplo n.º 14
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'))
Ejemplo n.º 15
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)
Ejemplo n.º 16
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()
Ejemplo n.º 17
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
Ejemplo n.º 18
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)
Ejemplo n.º 19
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
Ejemplo n.º 20
0
Archivo: core.py Proyecto: 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())
Ejemplo n.º 21
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)
Ejemplo n.º 22
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)
Ejemplo n.º 23
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()
Ejemplo n.º 24
0
def sign_block(b):
    with open('rsa.pri', 'r') as f:
        privatekey = PrivateKey.load_pkcs1(f.read())

    return sign(b.hash, privatekey, 'SHA-256').encode('hex')
Ejemplo n.º 25
0
def ctrl(conn):
    """
    读取控制命令,并在本机还原操作
    """
    with open("privkey.pem", "rb") as x:
        private_key = x.read()
        private_key = PrivateKey.load_pkcs1(private_key)  # 私钥

    def Op(key, op, ox, oy):
        # print(key, op, ox, oy)
        if key == 1:
            if op == 100:
                # 左键按下
                mouse.move(ox, oy)
                mouse.press(button=mouse.LEFT)
            elif op == 117:
                # 左键弹起
                x, y = mouse.get_position()
                if ox != x or oy != y:
                    if not mouse.is_pressed():
                        mouse.press(button=mouse.LEFT)
                    mouse.move(ox, oy)
                mouse.release(button=mouse.LEFT)
        elif key == 2:
            # 滚轮事件
            if op == 0:
                # 向上
                mouse.move(ox, oy)
                mouse.wheel(delta=-1)
            else:
                # 向下
                mouse.move(ox, oy)
                mouse.wheel(delta=1)
        elif key == 3:
            # 鼠标右键
            if op == 100:
                # 右键按下
                mouse.move(ox, oy)
                mouse.press(button=mouse.RIGHT)
            elif op == 117:
                # 右键弹起
                mouse.move(ox, oy)
                mouse.release(button=mouse.RIGHT)
        else:
            k = official_virtual_keys.get(key)
            if k is not None:
                if op == 100:
                    keyboard.press(k)
                elif op == 117:
                    keyboard.release(k)

    try:
        base_len = 21
        while True:
            cmd = b''
            rest = base_len - 0
            while rest > 0:
                cmd += conn.recv(rest)
                rest -= len(cmd)
            key = int(decrypt(cmd[:16], private_key))
            op = cmd[16]
            x = struct.unpack('>H', cmd[17:19])[0]
            y = struct.unpack('>H', cmd[19:21])[0]
            Op(key, op, x, y)
    except:
        return
Ejemplo n.º 26
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')
Ejemplo n.º 27
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)
Ejemplo n.º 28
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
Ejemplo n.º 29
0
import json
import sys
from rsa import PrivateKey

with open(sys.argv[1], 'rb') as input:
    key = PrivateKey.load_pkcs1(input.read())
    d = {}
    d['n'] = key.n
    d['e'] = key.e
    d['d'] = key.d
    d['p'] = key.p
    d['q'] = key.q
    with open(sys.argv[2], 'w') as output:
        output.write(json.dumps(d))
Ejemplo n.º 30
0
 def __init__(self, private_key_data):
     self.private_key_data = private_key_data
     self.pk = PrivateKey.load_pkcs1(private_key_data, 'PEM')
Ejemplo n.º 31
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")
Ejemplo n.º 32
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()