def setUp(self):
        self.pem_priv_key = """-----BEGIN PRIVATE KEY-----
MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDDLrmt4lKRpm6P
2blptwJsa1EBuxuuAayLjwNqKGvm5c1CAUEa/NtEpUMM8WYKRDwxzakUIGI/BdP3
NOEMphcs5+OekgJLhzoSdtAIrXPy8JIidENZE6FzCJ2b6fHU5O4hoNvv1Bx5yoZr
HVaWJIZMRRocJJ0Nf9oMaU8IE6m6OdBzQHEwcnL2/a8Q3VxstHufzjILmaZD9WL+
6AESlQMKZPNQ+Xd7d4nvnVkY4ZV46tA+KvADGuotgovQwG+uiyQoGRrQUms21vHF
zIvd3G9OCiyCTCHSyfsE3g7tks33NZ8O8gF8xa9OmU9TQPwwAyUr6JQXz0CW77o7
Cr9LpHuNAgMBAAECggEBAJRbMbtfqc8XqDYjEfGur2Lld19Pb0yl7RbvD3NjYhDR
X2DqPyhaRfg5fWubGSp4jyBz6C5qJwMsVN80DFNm83qoj7T52lC6aoOaV6og3V8t
SIZzxLUyXKdpRxM5kR13HSHmeQYkPbi9HcrRM/1PqdzTMXNuyQl3wq9oZDAJchsf
fmoh080htkaxhEb1bMXa2Lj7j2OIkHOsQeIu6BdbxIKRPIT+zrcklE6ocW8fTWAS
Qi3IZ1FYLL+fs6TTxjx0VkC8QLaxWxY0pqTiwS7ndZiZKc3l3ARuvRk8buP+X3Jg
BD86FQ18OXZC9boMbDbzv2cOLtdkq5pS3lJE4F9gjYECgYEA69ukU2pNWot2OPwK
PuPwAXWNrvnvFzQgIc0qOiCmgKJU6wqunlop4Bx5XmetHExVyJVBEhaHoDr0F3Rs
gt8IclKDsWGXoVcgfu3llMimiZ05hOf/XtcGTCZwZenMQ30cFh4ZRuUu7WCZ9tqO
28P8jCXB3IcaRpRnNvVvmCr5NXECgYEA09nUzRW993SlohceRW2C9fT9HZ4BaPWO
5wVlnoo5mlUfAyzl+AGT/WlKmrn/1gAHIznQJ8ZIABQvPaBXhvkANXZP5Ie0lObw
jA7qFuKt7yV4GGlDnU1MOLh+acABMQBGSx8BJDaomH7glTiPEPTZjoP6wfAsd1uv
Knjt7jH2ad0CgYEAx9ghknRd+rx0fbBBVix4riPW20324ihOmZVnlD0aF6B0Z3tz
ncUz+irmQ7GBIpsjjIO60QK6BHAvZrhFQVaNp6B26ZORkSlr5WDZyImDYtMPa6fP
36I+OcPQNOo3I3Acnjj+ne2PJ59Ula92oIudr3pGmv72qpsQIacw2TSAWGECgYEA
sdNAN+HPMn68ZaGoLDjvW8uIB6tQnay5hhvWn8yA65YV0RGH+7Q/Z9BQ6i3EnPor
A5uMqUZbu4011jHYJpiuXzHvf/GVWAO92KLQReOCgqHd/Aen1MtEdrwOiG+90Ebd
ukLNL3ud61tc4oS2OlJ8p48LFm2mtY3FLA6UEYPoxhUCgYEAtsfWIGnBh7XC+HwI
2higSgN92VpJHSPOyOi0aG/u5AEQ+fsCUIi3KakxzvmiGMAEvWItkKyz2Gu8smtn
2HVsGxI5UW7aLw9s3qe8kyMSfUk6pGamVhJUQmDr77+5zEzykPBxwGwDwdeR43CR
xVgf/Neb/avXgIgi6drj8dp1fWA=
-----END PRIVATE KEY-----
        """
        rsa_priv_key = RSA.importKey(self.pem_priv_key)
        self.priv_key = PKCS1_v1_5.new(rsa_priv_key)
        self.pub_key = PKCS1_v1_5.new(rsa_priv_key.publickey())
        unittest.TestCase.setUp(self)
Beispiel #2
0
def main(argv):
    encrypt = argv[0]
    keyfile = argv[1]
    service = argv[2]
    username = argv[3]

    if isinstance(encrypt, str):
        if encrypt.lower().startswith('t'):
            encrypt = True
        else:
            encrypt = False

    if encrypt:
        password = argv[4]
        key = RSA.generate(1024)
        cipher = PKCS1_v1_5.new(key)

        keyring.set_password(service, username, key.exportKey())

        with open(keyfile, 'wb') as outf:
            outf.write(cipher.encrypt(password))
    else:
        key = RSA.importKey(keyring.get_password(service, username))
        cipher = PKCS1_v1_5.new(key)

        with open(keyfile, 'rb') as inf:
            return cipher.decrypt(inf.read(), None)
Beispiel #3
0
def importKey(objId):
	public = open(objId + '.pub.pem', 'rb')
	private = open(objId + '.pri.pem', 'rb')
	pub = RSA.importKey(public.read())
	pri = RSA.importKey(private.read())
	pubN = PKCS1_v1_5.new(pub)
	priN = PKCS1_v1_5.new(pri)
	secret = pubN.encrypt('410015216'.encode())
	mess = priN.decrypt(secret, None)
	print(mess)
def decrypt(messageFile):
    
    #Read private key from file
    f = open("rsa_priv.pem", 'r')
    private = RSA.importKey(f.read())
    f.close() 

    #Read the message from the file
    f = open(messageFile, 'r')
    msg = f.read()
    f.close()

    #Decrypt the message from the sender
    print PKCS1_v1_5.new(private).decrypt(msg.decode("string-escape"), 0)
Beispiel #5
0
def serverkeyexgprocess(csession, ssession, p):
    pubkey = str(p[Raw])[:64]
    csession.crypto.server.rsa.pubkey = pubkey
    ssession.crypto.server.rsa.pubkey = pubkey
    prikey = getD(pubkey)

    n = int(pubkey.encode('hex'), 16)
    e = long(65537)
    d = int(getD(pubkey).encode('hex'), 16)
    csession.crypto.server.rsa.privkey = prikey
    ssession.crypto.server.rsa.privkey = prikey
    key = RSA.construct((n, e, d))
    csession.crypto.server.rsa.cipher = PKCS1_v1_5.new(key)
    ssession.crypto.server.rsa.cipher = PKCS1_v1_5.new(key)
    return p
Beispiel #6
0
 def encrypt(self, data):
     cipher = PKCS1_v1_5.new(self.key)
     try:
         return ''.join(reversed(cipher.encrypt(data)))  # Because MICROSOFT
     except ValueError:
         log.msg("Message too large to encrypt")
         return None
Beispiel #7
0
 def decrypt(self, data):
     cipher = PKCS1_v1_5.new(self.key)
     try:
         return cipher.decrypt(''.join(reversed(data)), None)  # For now
     except ValueError:
         log.msg("Message too large to decrypt")
         return None
Beispiel #8
0
def rsa_base64_encrypt(data,key):
    '''
    1. rsa encrypt
    2. base64 encrypt
    '''
    cipher = PKCS1_v1_5.new(key)
    return base64.b64encode(cipher.encrypt(data))
Beispiel #9
0
def encrypt_for_master(data):
    # Encrypt the file so it can only be read by the bot master
    h=SHA.new(data)
    key = RSA.importKey(open(os.path.join("pastebot.net", "master_rsa.pub")).read())
    cipher = PKCS1_v1_5.new(key)
    ciphertext = cipher.encrypt(data+h.digest())
    return ciphertext
    def encrypt_using_bot_public(data):
        public_key = RSA.importKey(open("../PublicKeyDir.Keys/botpubkey.pem", 'rb').read())
        h = SHA256.new(data)
        cipher = PKCS1_v1_5.new(public_key)
        ciphertext = cipher.encrypt(data + h.digest())

        return ciphertext
 def process(self,p):
     if p.haslayer(TLSHandshake):
         if p.haslayer(TLSClientHello):
             if not self.params.handshake.client:
                 self.params.handshake.client=p[TLSClientHello]
                 if not self.crypto.session.randombytes.client:
                     self.crypto.session.randombytes.client=struct.pack("!I",p[TLSClientHello].gmt_unix_time)+p[TLSClientHello].random_bytes
         if p.haslayer(TLSServerHello):
             if not self.params.handshake.server: 
                 self.params.handshake.server=p[TLSServerHello]
                 if not self.crypto.session.randombytes.server:
                     self.crypto.session.randombytes.server=struct.pack("!I",p[TLSServerHello].gmt_unix_time)+p[TLSServerHello].random_bytes
             if not self.params.negotiated.ciphersuite:
                 self.params.negotiated.version=p[TLSServerHello].version
                 self.params.negotiated.ciphersuite=p[TLSServerHello].cipher_suite
                 self.params.negotiated.compression=p[TLSServerHello].compression_method
                 self.parseCipherSuite()
                 #kex,enc,mac = describe_ciphersuite(self.params.negotiated.ciphersuite)
                 #self.params.negotiated.key_exchange=kex
                 #self.params.negotiated.encryption=enc
                 #self.params.negotiated.mac=mac
         if p.haslayer(TLSCertificateList):
             if self.params.negotiated.key_exchange and "RSA" in self.params.negotiated.key_exchange:
                 cert = p[TLSCertificateList].certificates[0].data
                 self.crypto.server.rsa.pubkey = PKCS1_v1_5.new(x509_extract_pubkey_from_der(cert))
         if p.haslayer(TLSClientKeyExchange) and self.crypto.server.rsa.privkey:  
             self.crypto.session.encrypted_premaster_secret = str(p[TLSClientKeyExchange].load)
             self.crypto.session.premaster_secret = self.crypto.server.rsa.cipher.decrypt(self.crypto.session.encrypted_premaster_secret,None)
             #print 'PMS',self.crypto.session.premaster_secret.encode('hex') 
             self.keysFromPreMasterSecret()
             # one for encryption and one for decryption to not mess up internal states
             self.crypto.client.enc = self.ciphersuite_factory(self.crypto.session.key.client.encryption,self.crypto.session.key.client.iv)
             self.crypto.client.dec = self.ciphersuite_factory(self.crypto.session.key.client.encryption,self.crypto.session.key.client.iv)
             self.crypto.server.enc = self.ciphersuite_factory(self.crypto.session.key.server.encryption,self.crypto.session.key.server.iv)
             self.crypto.server.dec = self.ciphersuite_factory(self.crypto.session.key.server.encryption,self.crypto.session.key.server.iv)
Beispiel #12
0
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: int

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

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

    # get crypto module, then encode
    try:
        from rsa import PublicKey, encrypt
        rpk = PublicKey(modulus, key)
        new_data = {key: encrypt(value, rpk).encode('hex') for key, value in data_dict.iteritems()}
    except ImportError:
        from Crypto.PublicKey import RSA
        from Crypto.Cipher import PKCS1_OAEP, PKCS1_v1_5
        cipher = PKCS1_v1_5.new(RSA.construct((modulus, key)))
        new_data = {key: cipher.encrypt(value).encode('hex') for key, value in data_dict.iteritems()}

    return new_data
Beispiel #13
0
    def encrypt_prepend(self, prepend, query_str_len):
        buf = []

        # 2 AES keys generated at run time, 16 bytes each
        aes_encrypt_key = "".join([chr(random.getrandbits(8)) for i in range(16)])
        aes_decrypt_key = "".join([chr(random.getrandbits(8)) for i in range(16)])
        buf.append(aes_encrypt_key)
        buf.append(aes_decrypt_key)

        # query str len
        size_field = struct.pack("I", query_str_len)
        buf.append(size_field)

        buf.append(prepend)

        rsa_key = RSA.importKey(self.rsa_key_pem)
        rsa = PKCS1_v1_5.new(rsa_key)

        enc_prepend = rsa.encrypt("".join(buf))

        keys = {
            "enc": aes_encrypt_key,
            "dec": aes_decrypt_key
        }

        return enc_prepend, keys
Beispiel #14
0
def RSA_encrypt(public_key, message):
    if not globals().get('RSA'):
        return ''
    rsakey = RSA.importKey(public_key)
    rsakey = PKCS1_v1_5.new(rsakey)
    encrypted = rsakey.encrypt(message.encode('utf-8'))
    return base64.encodestring(encrypted).decode('utf-8').replace('\n', '')
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
            instance_id = dict(required=True),
            key_file = dict(required=True),
        )
    )
    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg='Boto required for this module.')

    instance_id = module.params.get('instance_id')
    key_file = expanduser(module.params.get('key_file'))

    ec2 = ec2_connect(module)

    data = ec2.get_password_data(instance_id)
    decoded = b64decode(data)

    f = open(key_file, 'r')
    key = RSA.importKey(f.read())
    cipher = PKCS1_v1_5.new(key)
    sentinel = 'password decryption failed!!!'

    try:
      decrypted = cipher.decrypt(decoded, sentinel)
    except ValueError as e:
      decrypted = None

    if decrypted == None:
        module.exit_json(win_password='', changed=False)
    else:
        module.exit_json(win_password=decrypted, changed=True)
def encrypt_for_master(data):
    # Encrypt the file so it can only be read by the bot master
    
    # Generate key pairs
    key = RSA.generate(2048)
    
    # Export public key to file
    export_pukey = key.publickey().exportKey('PEM')
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "wb")
    publickey_file.write(export_pukey)
    publickey_file.close()
    
    # Create RSA object from public key
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "rb").read()
    public_key = RSA.importKey(publickey_file)
    
    # Hash message
    hashed_m = SHA256.new(data)
    
    # Encrypt message using public key
    cipher = PKCS1_cipher.new(public_key)
    ciphertext = cipher.encrypt(data+hashed_m.digest())
    
    # Export private key to be prefixed to ciphertext
    export_prkey = key.exportKey('PEM')
    
    # Sign message using private key
    prkey = RSA.importKey(export_prkey)
    signer = PKCS1_v1_5.new(prkey)
    signature = signer.sign(hashed_m)
    
    # Return private key and ciphertext, as well as signature separately
    return export_prkey + b"\n" + ciphertext, signature
def key_decryption(bytes_key):
    private_rsa_key = RSA.importKey(open('c:/cygwin64/certs/fred.pri.key').read())
    dsize = SHA.digest_size
    sentinel = Random.new().read(AES.block_size)
    cipher = PKCS1_v1_5.new(private_rsa_key)
    raw_aes_key = cipher.decrypt(bytes_key, sentinel)
    return raw_aes_key
def sign_file(f):
    # TODO: For Part 2, you'll use public key crypto here
    # The existing scheme just ensures the updates start with the line 'Caesar'
    # This is naive -- replace it with something better!
    
    # Generate key pairs
    key = RSA.generate(2048)
    
    # Export public key to file
    export_pukey = key.publickey().exportKey('PEM')
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "wb")
    publickey_file.write(export_pukey)
    publickey_file.close()
    
    # Create RSA object from public key
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "rb").read()
    public_key = RSA.importKey(publickey_file)
    
    # Hash message
    hashed_m = SHA256.new(f)
    
    # Encrypt message using public key
    cipher = PKCS1_cipher.new(public_key)
    ciphertext = cipher.encrypt(f+hashed_m.digest())
    
    # Export private key to be prefixed to ciphertext
    export_prkey = key.exportKey('PEM')
    
    # Sign message using private key
    prkey = RSA.importKey(export_prkey)
    signer = PKCS1_v1_5.new(prkey)
    signature = signer.sign(hashed_m)
    
    # Return private key and ciphertext, as well as signature separately
    return export_prkey + b"\n" + ciphertext, signature
Beispiel #19
0
 def create_encrypted_outer_aes_key_bundle(self, recipient_rsa):
     """
     The Outer AES Key Bundle is encrypted with the receipient's public
     key, so only the receipient can decrypt the header.
     """
     cipher = PKCS1_v1_5.new(recipient_rsa)
     return cipher.encrypt(self.create_outer_aes_key_bundle().encode("utf-8"))
 def encrypt_using_master_public(data):
     public_key_encryption_file = "./PublicKeyDir.Keys/pubkeys.pem"
     h = SHA256.new(data)
     key = RSA.importKey(open(public_key_encryption_file, 'rb').read())
     cipher = PKCS1_v1_5.new(key)
     ciphertext = cipher.encrypt(data + h.digest())
     return ciphertext
Beispiel #21
0
def travis_encrypt_binstar_token(repo, string_to_encrypt):
    # Copyright 2014 Matt Martz <*****@*****.**>
    # All Rights Reserved.
    #
    #    Licensed under the Apache License, Version 2.0 (the "License"); you may
    #    not use this file except in compliance with the License. You may obtain
    #    a copy of the License at
    #
    #         http://www.apache.org/licenses/LICENSE-2.0
    #
    #    Unless required by applicable law or agreed to in writing, software
    #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    #    License for the specific language governing permissions and limitations
    #    under the License.
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_v1_5
    import base64

    keyurl = "https://api.travis-ci.org/repos/{0}/key".format(repo)
    r = requests.get(keyurl, headers=travis_headers())
    r.raise_for_status()
    public_key = r.json()["key"]
    key = RSA.importKey(public_key)
    cipher = PKCS1_v1_5.new(key)
    return base64.b64encode(cipher.encrypt(string_to_encrypt.encode())).decode("utf-8")
 def decrypt_using_bot_private(data):
     private_key_encryption_file = "./lib/botPrivateKey/botprivatekey.pem"
     key = RSA.importKey(open(private_key_encryption_file, 'rb').read())
     digest_size = SHA256.digest_size
     sentinel = Random.new().read(15 + digest_size)
     cipher = PKCS1_v1_5.new(key)
     return cipher.decrypt(data, sentinel)
def start_ciphering(file_to_encrypt):

    pubkey = RSA.importKey(open(configuration_file.get("Encrypt_server", "pubkey_location")).read())
    random_bytes = os.urandom(32)
    # pid = os.fork()
    # if pid == 0 :
    disk_manager(file_name=file_to_encrypt)
    # sys.exit()
    # encrypt file with 256MB chunks and 512Mb file size takes about 17 seconds
    print "Start cifer for %s at %s" % (file_to_encrypt, datetime.now())
    encrypt_file(
        key=random_bytes,
        in_filename=file_to_encrypt,
        out_filename=configuration_file.get("Encrypt_server", "encrypted_files_location")
        + os.path.basename(file_to_encrypt + ".enc"),
        chunksize=configuration_file.getint("Encrypt_server", "chunksize"),
    )
    # cifer random key to post decrypt
    public_cipher = PKCS1_v1_5.new(pubkey)
    ciphertext = public_cipher.encrypt(random_bytes)
    # doing this on a fuction so i can perform saves on databases to (later on the project)
    save_signature(
        KeyToSave=ciphertext,
        Public_Cipher=public_cipher,
        FileName=configuration_file.get("Encrypt_server", "encrypted_files_location")
        + os.path.basename(file_to_encrypt),
    )
    print "Ended cifer for %s at %s\n" % (file_to_encrypt, datetime.now())
    os.system("rm %s" % (file_to_encrypt))
    return "DONE:%s" % (file_to_encrypt)
Beispiel #24
0
def assymmetric_encrypt(val, public_key):
    modulusDecoded = long(public_key["n"], 16)
    exponentDecoded = long(public_key["e"], 16)
    keyPub = RSA.construct((modulusDecoded, exponentDecoded))
    # Generate a cypher using the PKCS1.5 standard
    cipher = PKCS1_v1_5.new(keyPub)
    return cipher.encrypt(val)
Beispiel #25
0
def get_encrypted_password(password, rsa_mod, pub_exp):
    """ Encrypts a Steam password for web login using RSA with PKCS1_v1_5. 
        Returns the base64 encoded ciphertext since that's what Steam's login endpoint wants. """
    public_key = RSA.construct((rsa_mod, pub_exp))
    cipher = PKCS1_v1_5.new(public_key)
    ciphertext = cipher.encrypt(bytes(password, 'utf_8'))
    return base64.b64encode(ciphertext)
    def __init__(self, user, password):
        # Generate an RSA key
        self.rsa_full = RSA.generate(2048)
        self.cipher_full = PKCS1_v1_5.new(self.rsa_full)
        self._content_type_json = 'application/json; charset=utf-8'
        self._login_stage = ['email', 'twocfactor', 'captcha']
        self._steamid = str(random_number(17))

        # Register URIs
        httpretty.register_uri(httpretty.POST, 'https://steamcommunity.com/mobilelogin/getrsakey/',
                                body=json.dumps({
                                        'success': True,
                                        'publickey_mod': format(self.rsa_full.n, 'x').upper(),
                                        'publickey_exp': format(self.rsa_full.e, 'x').upper(),
                                        'timestamp': '64861350000', # TODO don't know how this is constructed
                                }),
                                content_type=self._content_type_json)

        httpretty.register_uri(httpretty.POST, 'https://steamcommunity.com/mobilelogin/dologin/',
                                body=self.generate_dologin_response)

        httpretty.register_uri(httpretty.GET, 'https://steamcommunity.com/public/captcha.php',
                                body=self.generate_captcha_response,
                                adding_headers={
                                    'Set-Cookie': 'sessionid=%s; path=/' % (
                                        random_ascii_string(24),
                                    ),
                                })

        httpretty.register_uri(httpretty.POST, 'https://steamcommunity.com/login/transfer',
                                body='Success',
                                status=200)

        super(SteamWebBrowserMocked, self).__init__(user, password)
Beispiel #27
0
    def decrypt(self, ciphertext, key, padding="pkcs1_padding"):
        if padding == "pkcs1_padding":
            cipher = PKCS1_v1_5.new(key)
            if self.with_digest:
                dsize = SHA.digest_size
            else:
                dsize = 0
            sentinel = Random.new().read(32+dsize)
            text = cipher.decrypt(ciphertext, sentinel)
            if dsize:
                _digest = text[-dsize:]
                _msg = text[:-dsize]
                digest = SHA.new(_msg).digest()
                if digest == _digest:
                    text = _msg
                else:
                    raise DecryptionFailed()
            else:
                if text == sentinel:
                    raise DecryptionFailed()
        elif padding == "pkcs1_oaep_padding":
            cipher = PKCS1_OAEP.new(key)
            text = cipher.decrypt(ciphertext)
        else:
            raise Exception("Unsupported padding")

        return text
    def __init__(self, data, ignoreDigestErrors=False):
        data = data[:512]
        
        self.PublicKeyId = hexpad(bigEndian(binaryToByteArray(data[0:16])), 32)
        self.DataLength = struct.unpack('B', data[16])[0]
        if self.DataLength != 128:
            raise Exception("Got an unexpected Data Length from the MixHeader:", self.DataLength)
        self.TDESKey = data[17:145]
        self.IV = data[145:153]
        self.EncHeader = data[153:481]
        self.Padding = data[481:512]
        
        self.TDESKey_Decrypted = 0
        
        ks = getKeyStore()
        privKey = ks.getPrivateKey(self.PublicKeyId)
        if not privKey:
            raise Exception("Could not decrypt MixHeader, Private Key for " + self.PublicKeyId + " not found in keystore: " + str(ks.listPrivateKeys()))
        
        rsa = PKCS1_v1_5.new(privKey.getPCPrivateKey())
        self.TDESKey_Decrypted = rsa.decrypt(self.TDESKey, "This is most certainly not the key")
        
        if self.TDESKey_Decrypted == "This is most certainly not the key":
            raise Exception("Could not decrypt MixHeader Encrypted Header")
        
        des = DES3.new(self.TDESKey_Decrypted, DES3.MODE_CBC, IV=self.IV)
        self.EncHeader_Decrypted = des.decrypt(self.EncHeader)

        self.DecryptedHeader = EncryptedMixHeader(self.EncHeader_Decrypted, ignoreDigestErrors)
Beispiel #29
0
	def encrypt(self, msg, pubKeyStr):
		'''
		Encrypt a message
		'''
		# prepare for AES
		aes_rand = Random.new().read(32)
		aes_iv_rand = Random.new().read(AES.block_size)
		aes_key = AES.new(aes_rand,AES.MODE_CBC,aes_iv_rand)
		pre_msg = str(json.dumps(msg))

		# Pad the msg
		length = 16 - (len(pre_msg) % 16)

		# Now encrypt AES
		aes_msg = aes_key.encrypt(str.encode(pre_msg) + bytes([length])*length)

		# Prepare PKCS1 1.5 Cipher
		pubKey = RSA.importKey(pubKeyStr)
		cipher = PKCS1_v1_5.new(pubKey)

		# encrypt RSA
		rsa_aes_key = cipher.encrypt(aes_rand)
		rsa_aes_iv = cipher.encrypt(aes_iv_rand)
		combined = rsa_aes_key + rsa_aes_iv + aes_msg
		b64out  = base64.b64encode(combined)

		return b64out.decode()
Beispiel #30
0
    def packet_decrypt(self, packet):
        """Unpack a received Mixmaster email message header.  The spec calls
        for 512 Bytes, of which the last 31 are padding.

           Public key ID                [  16 bytes]
           Length of RSA-encrypted data [   1 byte ]
           RSA-encrypted session key    [ 128 bytes]
           Initialization vector        [   8 bytes]
           Encrypted header part        [ 328 bytes]
           Padding                      [  31 bytes]

        """
        # Unpack the header components.  This includes the 328 Byte
        # encrypted component.
        (keyid, datalen, sesskey, iv, enc,
         pad) = struct.unpack('@16sB128s8s328s31s', packet.encheads[0])
        if not len(sesskey) == datalen:
            raise ValidationError("Incorrect session key size")
        keyid = keyid.encode("hex")
        log.debug("Message is encrypted to key: %s", keyid)
        # Use the session key to decrypt the 3DES Symmetric key
        seckey = self.secring[keyid]
        if seckey is None:
            raise ValidationError("Secret Key not found")
        pkcs1 = PKCS1_v1_5.new(seckey)
        deskey = pkcs1.decrypt(sesskey, "Failed")
        # Process the 328 Bytes of encrypted header using our newly discovered
        # 3DES key obtained from the pkcs1 decryption.
        desobj = DES3.new(deskey, DES3.MODE_CBC, IV=iv)
        packet.set_dhead(desobj.decrypt(enc))
Beispiel #31
0
    def test_validate_register(self):
        self.assertEquals(
            0, len(BlogUser.objects.filter(email='*****@*****.**')))
        response = self.client.post(
            reverse('account:register'), {
                'username': '******',
                'email': '*****@*****.**',
                'password1': 'password123!q@wE#R$T',
                'password2': 'password123!q@wE#R$T',
            })
        self.assertEquals(
            1, len(BlogUser.objects.filter(email='*****@*****.**')))
        user = BlogUser.objects.filter(email='*****@*****.**')[0]
        sign = get_md5(get_md5(settings.SECRET_KEY + str(user.id)))
        path = reverse('accounts:result')
        url = '{path}?type=validation&id={id}&sign={sign}'.format(path=path,
                                                                  id=user.id,
                                                                  sign=sign)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        self.client.login(username='******', password='******')
        user = BlogUser.objects.filter(email='*****@*****.**')[0]
        user.is_superuser = True
        user.is_staff = True
        user.save()
        delete_sidebar_cache(user.username)
        category = Category()
        category.name = "categoryaaa"
        category.created_time = datetime.datetime.now()
        category.last_mod_time = datetime.datetime.now()
        category.save()

        article = Article()
        article.category = category
        article.title = "nicetitle333"
        article.body = "nicecontentttt"
        article.author = user

        article.type = 'a'
        article.status = 'p'
        article.save()

        response = self.client.get(article.get_admin_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get(reverse('account:logout'))
        self.assertIn(response.status_code, [301, 302, 200])

        response = self.client.get(article.get_admin_url())
        self.assertIn(response.status_code, [301, 302, 200])

        response = self.client.get(reverse('account:login'))
        self.assertEqual(response.status_code, 200)

        pub_key = response.context['form'].initial['pub_key']
        pubobj = Cipher_pkcs1_v1_5.new(RSA.importKey(pub_key))
        pw = base64.b64encode(pubobj.encrypt('qwer!@#$ggg'.encode()))
        response = self.client.post(
            reverse('account:login'), {
                'username': '******',
                'password': pw.decode(),
                'pub_key': pub_key
            })
        self.assertIn(response.status_code, [301, 302, 200])

        response = self.client.get(article.get_admin_url())
        self.assertIn(response.status_code, [301, 302, 200])
Beispiel #32
0
def rsa_decrypt(input_string, private_key):
    input_bytes = base64.b64decode(input_string)
    rsa_key = RSA.importKey("-----BEGIN RSA PRIVATE KEY-----\n" + private_key + "\n-----END RSA PRIVATE KEY-----")
    cipher = PKCS1_v1_5.new(rsa_key)
    # noinspection PyArgumentList
    return str(cipher.decrypt(input_bytes, Random.new().read), 'utf-8')
Beispiel #33
0
def rsa_encode(text, public_key):
    key = RSA.importKey(b64decode(public_key))
    cipher = PKCS1_v1_5.new(key)
    return b64encode(cipher.encrypt(text.encode(encoding='utf-8'))).decode('utf-8')
Beispiel #34
0
import rsa

random_generator=Random.new().read
file="secret.txt"
c=""
with open(file,"rb") as f:
    cipher=f.read()
    instr=base64.b64decode(cipher)
    print(instr)
    #instr=str(binascii.b2a_hex(instr),'utf-8')
file="rsa_private_key.pem"
default_length=117
with open(file,"rb") as f:
    line=f.read()
    rsaKey=RSA.importKey(line)
    decryptor=PKCS1_v1_5.new(rsaKey)
    privkey = rsa.PrivateKey.load_pkcs1(line)
    #encrypted_byte=base64.b64decode(cipher.encode())
    '''length=len(encrypted_byte)
    if length < default_length:
        decrypt_byte = decryptor.decrypt(encrypted_byte, 'failure')
    else:
        offset = 0
        res = []
        while length - offset > 0:
            if length - offset > default_length:
                res.append(decryptor.decrypt(encrypted_byte[offset: offset + default_length], 'failure'))
            else:
                res.append(decryptor.decrypt(encrypted_byte[offset:], 'failure'))
            offset += default_length
        decrypt_byte = b''.join(res)
Beispiel #35
0
def rsaDecrypt(m, rsa_private_key):
    rsakey = RSA.importKey(rsa_private_key.encode())
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    text = cipher.decrypt(base64.b64decode(m), None)
    c = text.decode('utf8')
    return eval(c)
Beispiel #36
0
 def testEncrypt2(self):
     # Verify that encryption fail if plaintext is too long
     pt = '\x00' * (128 - 11 + 1)
     cipher = PKCS.new(self.key1024)
     self.assertRaises(ValueError, cipher.encrypt, pt)
Beispiel #37
0
 def encode(self, str):
     cipher = PKCS1_v1_5.new(self.public_key)
     return base64.encodebytes(cipher.encrypt(str))
Beispiel #38
0
 def decode(self, decode_str):
     cipher = PKCS1_v1_5.new(self.private_key)
     return cipher.decrypt(base64.b64decode(decode_str), random_generator)
Beispiel #39
0
# coding=utf-8
import json
import base64
import requests
from . import constants, exceptions

from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
# TODO change this later. Currently kushki uses PKCS1 both in php and this implementation (they should use OAEP).
# TODO masking with MGF1 and hashing with SHA1 will be used for PHP if the constant changes to OAEP setting.
encrypter = PKCS1_v1_5.new(RSA.importKey(constants.KUSHKI_PUBLIC_KEY))


class Request(object):
    """
    Abstraccion para realizar una peticion al servidor de Kushki.
    """
    def __init__(self, url, params, content_type=constants.CONTENT_TYPE):
        self._url = url
        self._params = params
        self._content_type = content_type

    url = property(lambda self: self._url)
    params = property(lambda self: self._params)
    content_type = property(lambda self: self._content_type)

    def param(self, param_name):
        """
        Obtiene un parametro de la request.
        :param param_name: nombre del parametro a obtener.
        :return:
Beispiel #40
0
    for cookie in r.headers['Set-Cookie'].split(';'):
        s = cookie.split('=')
        cookies[s[0]] = s[1] if len(s) == 2 else None
    return cookies


r = requests.post(get_token_url)
if r.status_code != 200:
    raise Exception("Can not get Token")

public_key = json.loads(r.content)['data']['public_key']
public_key = "-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----" % public_key
print "Get public key:\n", public_key

rsakey = RSA.importKey(public_key)
cipher = PKCS1_v1_5.new(rsakey)
password_encrypted = base64.b64encode(cipher.encrypt(password))

form = {
    'username': username,
    'password': password_encrypted,
}
print "Request Form:\n", form

cookies = get_cookie(r)
r = requests.post(login_url, form, cookies=cookies)
print r.status_code, r.reason  #, r.content
if r.status_code != 200:
    raise Exception("Can not login")

ret_url = json.loads(r.content)['data']['retUrl']
Beispiel #41
0
def rsa(src):
    rsakey = RSA.construct((int(define.__LOGIN_RSA_VER158_KEY_N__,
                                16), define.__LOGIN_RSA_VER158_KEY_E__))
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    encrypt_buf = cipher.encrypt(src)
    return encrypt_buf
Beispiel #42
0
 def testMemoryview(self):
     pt = b"XER"
     cipher = PKCS.new(self.key1024)
     ct = cipher.encrypt(memoryview(bytearray(pt)))
     pt2 = cipher.decrypt(memoryview(bytearray(ct)), b'\xFF' * len(pt))
     self.assertEqual(pt, pt2)
def check_pay(request):
    '''获取用户支付的结果'''

    # receive data from bank
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('0.0.0.0', 8080))
    server_socket.listen(5)
    print("server is ready:")
    while True:
        print("-------")
        tmp_socket, CLIENT_ADDR = server_socket.accept()
        sleep(1)
        try:
            msg = tmp_socket.recv(2048)
            print(msg)
            break
        except Exception as e:
            continue

    # connect to bank
    # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # sock.settimeout(1)
    # print('ss')
    msg_list = msg.split('&&')
    if len(msg_list) != 3:
        if send_to_bank(tmp_socket, 'NO'):
            return JsonResponse({'res': 7, 'errmsg': '银行网络错误'})
        return JsonResponse({'res': 0, 'errmsg': '订单格式错误'})

    # Ek(key), iv, cipher text
    k = RSA.importKey(settings.PRIKEY)
    cipher = PKCS1_v1_5.new(k)
    key = cipher.decrypt(base64.b64decode(msg_list[0]), None)
    iv = base64.b64decode(msg_list[1])
    plaintext = msg_list[2].decode('hex')
    cipher = AES.new(key, AES.MODE_CBC, iv)
    pt = unpad(cipher.decrypt(plaintext), 16)

    # verify infomation
    try:
        tmp = pt.split("&&", 2)
    except:
        if send_to_bank(tmp_socket, 'NO'):
            return JsonResponse({'res': 7, 'errmsg': '银行网络错误'})
        return JsonResponse({'res': 0, 'errmsg': '订单格式错误'})
    OI = urllib.unquote(tmp[0])
    PI_hash = tmp[1]
    DS = tmp[2]
    # print("DS:"+DS)
    try:
        OI_info = OI.split("AAAAA", 3)
    except:
        if send_to_bank(tmp_socket, 'NO'):
            return JsonResponse({'res': 7, 'errmsg': '银行网络错误'})
        return JsonResponse({'res': 0, 'errmsg': '订单格式错误'})

    order_id = OI_info[1]
    # print(order_id)
    # 数据校验
    if not order_id:
        if send_to_bank(tmp_socket, 'NO'):
            return JsonResponse({'res': 7, 'errmsg': '银行网络错误'})
        return JsonResponse({'res': 1, 'errmsg': '订单不存在'})

    try:
        order = OrderInfo.objects.get(order_id=order_id,
                                      status=1,
                                      pay_method=1)  # secret payment
    except OrderInfo.DoesNotExist:
        if send_to_bank(tmp_socket, 'NO'):
            return JsonResponse({'res': 7, 'errmsg': '银行网络错误'})
        return JsonResponse({'res': 2, 'errmsg': '订单信息出错'})
    # verify DS
    sh = sha256()
    try:
        sh.update(base64.b64encode(OI))
    except Exception as e:
        if send_to_bank(tmp_socket, 'NO'):
            return JsonResponse({'res': 7, 'errmsg': '银行网络错误'})
        return JsonResponse({'res': 5, 'errmsg': '编码错误'})
    OI_hash = sh.hexdigest()
    # print("OI_hash:"+OI_hash)
    # plaintext m = sha256(OI_hash+PI_hash)
    # print("PI_hash:" + PI_hash)
    sh = sha256()
    sh.update(OI_hash + PI_hash)
    m = sh.hexdigest()
    # print(m)
    # get user PUBkey
    a = Passport.objects.get_passport_by_id(request.session['passport_id'])

    pKey = str(a.pubkey)
    pKey = pKey.replace('\\n', '\n')
    try:
        if not my_verify(m, DS, pKey):
            if send_to_bank(tmp_socket, 'NO'):
                return JsonResponse({'res': 7, 'errmsg': '银行网络错误'})
            return JsonResponse({'res': 6, 'errmsg': '签名错误'})
    except Exception as e:
        print(e)

    # after verify, listen to bank, watch if paid
    print("suc")
    # back_url = "http://localhost:8000/user/order/"
    send_to_bank(tmp_socket, 'YES')
    # return JsonResponse({'res': 3, 'errmsg': '支付成功'})
    while True:
        print("-------")
        sleep(1)
        try:
            msg = tmp_socket.recv(2048)
            print(msg)
            if msg == '10000':
                return JsonResponse({'res': 7, 'errmsg': '银行验证出错'})
            elif msg == '20000':
                print('aaa')
                return JsonResponse({'res': 3, 'errmsg': '支付成功', 'data': DS})
            else:
                return JsonResponse({'res': 4, 'errmsg': '支付出错'})
        except Exception as e:
            return JsonResponse({'res': 7, 'errmsg': '银行网络错误'})
Beispiel #44
0
def make_message(pwd):
    rsakey = RSA.importKey(public_key)
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    cipher_text = base64.b64encode(cipher.encrypt(pwd.encode(encoding="utf-8")))
    return cipher_text.decode('utf8')
Beispiel #45
0
 def testByteArray(self):
     pt = b"XER"
     cipher = PKCS.new(self.key1024)
     ct = cipher.encrypt(bytearray(pt))
     pt2 = cipher.decrypt(bytearray(ct), '\xFF' * len(pt))
     self.assertEqual(pt, pt2)
Beispiel #46
0
 def _encrypt_pwd(self, public_key):
     rsa_key = RSA.importKey(public_key)
     encryptor = Cipher_pkcs1_v1_5.new(rsa_key)
     cipher = b64encode(encryptor.encrypt(self.password.encode('utf-8')))
     return cipher.decode('utf-8')
Beispiel #47
0
def rsa_decode(cipher_text, private_key):
    rsakey = RSA.importKey(private_key)  # 导入读取到的私钥
    cipher = PKCS1_v1_5.new(rsakey)  # 生成对象
    # 将密文解密成明文,返回的是一个bytes类型数据,需要自己转换成str
    text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
    return text.decode()
Beispiel #48
0
 def Encrypt(self, message):
     cipher_rsa = PKCS1_v1_5.new(self.public_key)
     ciphertext = cipher_rsa.encrypt(message)
     return ciphertext
def get_crypt_password(private_key, password):
    rsa = RSA.importKey(private_key)
    cipher = PKCS1_v1_5.new(rsa)
    ciphertext = encrypt(password, cipher)
    return ciphertext
Beispiel #50
0
def encrypt_by_public_key(publickey, message):
    byte = PKCS1_v1_5.new(RSA.importKey(base64.b64decode(publickey))).encrypt(
        message.encode(encoding="utf8"))
    return base64.b64encode(byte).decode(encoding="utf8")
Beispiel #51
0
def rsaCrypto(adict, rsa_public_key):
    rsakey = RSA.importKey(rsa_public_key.encode())
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    cipher_text = base64.b64encode(cipher.encrypt(str(adict).encode()))
    return cipher_text.decode('utf8')
Beispiel #52
0
def encrypt_pwd(password, public_key=RSA_PUBLIC_KEY):
    rsa_key = RSA.importKey(public_key)
    encryptor = Cipher_pkcs1_v1_5.new(rsa_key)
    cipher = b64encode(encryptor.encrypt(password.encode('utf-8')))
    return cipher.decode('utf-8')
Beispiel #53
0
 def encode(self,pub_key,msg):
     rsakey = RSA.importKey(pub_key)
     cipher = Cipher_pkcs1_v1_5.new(rsakey)
     cipher_text = base64.b64encode(cipher.encrypt(msg))
     return cipher_text
Beispiel #54
0
def asymm_encrypt(text, pub_key):
    key = RSA.importKey(pub_key)
    cipherText = Cipher_pkcs1_v1_5.new(key).encrypt(text)
    return cipherText
print 'received=', repr(ok_pubkey4)

if not ok_pubkey4:
    raise Exception('failed to set the RSA key')

print 'Assert that the received public N match the one generated locally'
print 'Local Public N=', repr(public_n)
ok_pubkey = ok_pubkey1 + ok_pubkey2 + ok_pubkey3 + ok_pubkey4
assert ok_pubkey == public_n
print 'Ok, public N matches'
print

message = 'Secret message'
#h = SHA.new(message)
cipher = PKCS1_v1_5.new(key)
ciphertext = cipher.encrypt(message)

#hex_enc_data = bin2hex(enc_data)
print 'encrypted payload = ', repr(ciphertext)
print


# Compute the challenge pin
h = hashlib.sha256()
h.update(ciphertext)
d = h.digest()

assert len(d) == 32

def get_button(byte):
Beispiel #56
0
def asymm_decrypt(ciphertext, priv_key):
    rg = Random.new().read
    key = RSA.importKey(priv_key)
    text = Cipher_pkcs1_v1_5.new(key).decrypt(ciphertext, rg)
    return text
Beispiel #57
0
def encrypt(message):
    h = SHA.new(message)
    cipher = PKCS1_v1_5.new(key)
    ciphertext = cipher.encrypt(message + h.digest())
    return ciphertext
Beispiel #58
0
    except:
        print("Cannot import public key.")
        support.put_exception("import key")
        hand.client(["quit"])
        hand.close()
        sys.exit(0)

    #if conf.pgdebug > 1:
    print("Got pub key", hand.pubkey, "size =", hand.pubkey.size())

    # Generate communication key
    conf.sess_key = Random.new().read(512)
    sss = SHA512.new()
    sss.update(conf.sess_key)

    cipher = PKCS1_v1_5.new(hand.pubkey)
    #print ("cipher", cipher.can_encrypt())

    if conf.pgdebug > 2:
        support.shortdump("conf.sess_key", conf.sess_key)

    sess_keyx = cipher.encrypt(conf.sess_key)
    ttt = SHA512.new()
    ttt.update(sess_keyx)

    if conf.pgdebug > 2:
        support.shortdump("sess_keyx", sess_keyx)

    #print("Key Hexdigest", ttt.hexdigest()[:16])

    #resp3 = hand.client(["sess",], "", False) 3 error responses
Beispiel #59
0
    def __init__(self, data_folder, config):
        self.data_folder = data_folder
        self.data_folder_bn = data_folder.replace('/', '').replace(
            '\\', '').replace('.', '').replace(' ', '')
        self.key_bn = os.path.join(data_folder, self.data_folder_bn)

        self.RSA_KEY_SIZE = config['SSL_KEY_LENGTH']
        print "RSA_KEY_SIZE", self.RSA_KEY_SIZE

        self.rsa_private_key_file_name = '%s_rsa_%d_priv.pem' % (
            self.key_bn, self.RSA_KEY_SIZE)
        self.rsa_public_key_file_name2 = '%s_rsa_%d_pub.pem' % (
            self.key_bn, self.RSA_KEY_SIZE)
        self.rsa_public_key_file_name3 = os.path.join(
            dir_path, "templates",
            '%s_rsa_%d_pub.pem' % (self.data_folder_bn, self.RSA_KEY_SIZE))
        self.rsa_public_key_file_name = '%s_rsa_%d_pub.pem' % (
            self.data_folder_bn, self.RSA_KEY_SIZE)

        print "rsa private key file name     ", self.rsa_private_key_file_name
        print "rsa public  key file name full", self.rsa_public_key_file_name2
        print "rsa public  key file name bkp ", self.rsa_public_key_file_name3
        print "rsa public  key file name temp", self.rsa_public_key_file_name

        if (not os.path.exists(self.rsa_private_key_file_name)) or (
                not os.path.exists(self.rsa_public_key_file_name2)):
            print "one of the ssl keys is missing. deleting"
            if (os.path.exists(self.rsa_private_key_file_name)):
                print "ssl key % exists. deleting" % self.rsa_private_key_file_name
                os.remove(self.rsa_private_key_file_name)

            if (os.path.exists(self.rsa_public_key_file_name2)):
                print "ssl key %s exists. deleting" % self.rsa_public_key_file_name2
                os.remove(self.rsa_public_key_file_name2)

            print "PUBLIC KEY %s OR PRIVATE KEY %s DOES NOT EXISTS. CREATING" % (
                self.rsa_private_key_file_name, self.rsa_public_key_file_name2)
            #(pubkey, privkey) = rsa.newkeys(RSA_KEY_SIZE, accurate=True, poolsize=1)
            #open(rsa_public_key_file_name , 'w').write( pubkey.save_pkcs1()  )
            #open(rsa_private_key_file_name, 'w').write( privkey.save_pkcs1() )

            self.privkey = RSA.generate(self.RSA_KEY_SIZE)
            self.pubkey = self.privkey.publickey()

            open(self.rsa_public_key_file_name2,
                 'w').write(self.pubkey.exportKey('PEM'))
            open(self.rsa_private_key_file_name,
                 'w').write(self.privkey.exportKey('PEM'))

            print "saved public and private keys"

        if (os.path.exists(self.rsa_public_key_file_name3)):
            print "ssl key %s exists. deleting" % self.rsa_public_key_file_name3
            os.remove(self.rsa_public_key_file_name3)

        shutil.copy2(self.rsa_public_key_file_name2,
                     self.rsa_public_key_file_name3)

        self.rsa_private_key = RSA.importKey(
            open(self.rsa_private_key_file_name, 'r').read())
        self.rsa_public_key = RSA.importKey(
            open(self.rsa_public_key_file_name2, 'r').read())

        self.enc_cipher = PKCS1_v1_5.new(self.rsa_public_key)
        self.dec_cipher = PKCS1_v1_5.new(self.rsa_private_key)

        print "encryption test"
        message = "test"
        encmess = self.encrypter(message)
        decmess = self.decrypter(encmess)

        print "message ", message
        print "encmess ", encmess
        print "decmess ", decmess

        assert message == decmess, "decrypted message %s does not match original message %s" % (
            decmess, message)
Beispiel #60
0
#!/usr/local/bin/python3

plaintext = b'Attack at dawn'

from Crypto.PublicKey import RSA

# generate pair of keys (and export them)
rsa_key = RSA.generate(2048)
privkey = rsa_key.exportKey(pkcs=8)
pubkey = rsa_key.publickey().export_key()

from Crypto.Cipher import PKCS1_v1_5

# encryption
k = RSA.importKey(pubkey)
cipher = PKCS1_v1_5.new(k)
ciphertext = cipher.encrypt(plaintext)
print(ciphertext)

# decryption
k = RSA.importKey(privkey)
cipher = PKCS1_v1_5.new(k)
d = cipher.decrypt(ciphertext, "thisisarandomsentinelmessage")
print(d)

from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256

# signature
k = RSA.importKey(privkey)
signer = PKCS1_v1_5.new(k)