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 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")
Beispiel #10
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 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
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 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 #18
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 #19
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 #20
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)
Beispiel #21
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
Beispiel #22
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 __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)
    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 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 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)
 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
    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 #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()
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 #31
0
 def decrypt(self, cipher_text):
     rsakey = RSA.importKey(self.rsa_private_key)
     cipher = Cipher_pkcs1_v1_5.new(rsakey)
     random_generator = Random.new().read
     text = cipher.decrypt(base64.b64decode(cipher_text), random_generator)
     return text.decode('utf8')
Beispiel #32
0
 def encrypt(self, msg):
     msg = msg.encode('utf-8')
     rsakey = RSA.importKey(self.rsa_public_key)
     cipher = Cipher_pkcs1_v1_5.new(rsakey)
     cipher_text = base64.b64encode(cipher.encrypt(msg))
     return cipher_text
Beispiel #33
0
#!/usr/bin/env python

from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
from Crypto.Cipher import PKCS1_v1_5
import sys

if len(sys.argv) <=1:
 print "Usage : pkcs1_v1_5_decrypt.py <encryptfile.txt> < output_decrypt.txt>"
 exit()

file1_object = open(sys.argv[1], "rb")
contents = file1_object.read()
key_object = RSA.importKey(open("/root/privatekey.txt").read())
sha_object = SHA.new(sys.argv[1])
object_encrypt = PKCS1_v1_5.new(key_object)
file2_object = open(sys.argv[2], "a+")
file2_object = open(sys.argv[2], "wb")
file2_object.write(object_encrypt.decrypt(contents , sha_object))
file2_object = open(sys.argv[2], "rb")
file2_object.read()
Beispiel #34
0
#!/usr/bin/env python
# -*- coding:utf-8

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import json
import base64

privateKeyFile = open("czdap.private.key", "r")
key = RSA.importKey(privateKeyFile.read())
cipher = PKCS1_v1_5.new(key)
privateKeyFile.close()

credsFile = open("credentials.json", "r")
credsData = json.load(credsFile)
credsFile.close()

print "server,username,password"

for creds in credsData:
    piecesJSON = cipher.decrypt(base64.b64decode(creds['credentials']), 0)
    if not piecesJSON:
        print "\nError: Decryption failed, do you have the correct keyfile?"
        exit(1)
    pieces = json.loads(piecesJSON)
    username = unicode(base64.b64decode(pieces[0]), "utf-8")
    password = unicode(base64.b64decode(pieces[1]), "utf-8")
    print ",".join([creds['host'], username, password])
Beispiel #35
0
    if k == 0:
        continue
    else:
        break
        print k
        if try_square_root(4 * e * k * n + 1):
            print k
            p = (math.sqrt(4 * e * k * n + 1) - 1) / (2 * k)
            print p
            q = n / p
            print q
            d = inverse(e, (p - 1) * (q - 1))

            print d

            privkey = RSA.construct((n, e, d))
            print PKCS1_v1_5.new(privkey).decrypt(
                open("flag.encrypted", "rb").read(), "!")
            break

k = 54080
print try_square_root(4 * e * k * n + 1)
p = (try_square_root(4 * e * k * n + 1) - 1) / (2 * k)
q = n / p
d = inverse(e, (p - 1) * (q - 1))
print p
print q
print d
privkey = RSA.construct((n, e, d))
print PKCS1_v1_5.new(privkey).decrypt(open("flag.encrypted", "rb").read(), "!")
Beispiel #36
0
from __future__ import print_function, unicode_literals

import base64
import sys

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey.RSA import construct

# prepare public key
e = int('10001', 16)
n = int('10011', 16)
pubkey = construct((n, e))

# create a cipher via PKCS1.5
cipher = PKCS1_v1_5.new(pubkey)

# encrypt
cipher_text = cipher.encrypt("Hello RSA!".encode())

# do base64 encode
cipher_text = base64.b64encode(cipher_text)
print(cipher_text.decode('utf-8'))
Beispiel #37
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 #38
0
 def __init__(self, account, pwd):
     self.account = account
     self.pwd = pwd
     self.cipher_text = base64.b64encode(
         Cipher_pkcs1_v1_5.new(RSA.importKey(self.rsa_public_key)).encrypt(
             bytes(self.pwd, encoding="utf8")))
Beispiel #39
0
 def setUp(self):
     self.key = RSA.generate(2048)
     self.public_key = self.key.publickey().export_key()
     self.partner_id = "001"
     self.signatureObj = Signature(self.partner_id, self.public_key)
     self.cipher = PKCS1_v1_5.new(self.key.exportKey())
Beispiel #40
0
def rsa_encrypt(pubkey,data):
    pub_key = RSA.importKey(str(pubkey))
    cipher = PKCS1_cipher.new(pub_key)
    rsa_text = base64.b64encode(cipher.encrypt(bytes(data.encode("utf8"))))
    # print(rsa_text.decode('utf-8'))
    return rsa_text
Beispiel #41
0
def rsa_decrypt(prikey,data):
    pri_key = RSA.importKey(prikey)
    cipher = PKCS1_cipher.new(pri_key)
    back_text = cipher.decrypt(base64.b64decode(data), 0)
    # print(back_text.decode('utf-8'))
    return back_text
Beispiel #42
0
 def rsa_encrypt(self, data: bytes):
     key = RSA.construct((int(self.rsa_keys['MR'],
                              16), int(self.rsa_keys['ER'], 16)))
     # noinspection PyTypeChecker
     pkcs = PKCS1_v1_5.new(key)
     return pkcs.encrypt(data)
Beispiel #43
0
 def testMemoryview(self):
     pt = b"XER"
     cipher = PKCS.new(self.key1024)
     ct = cipher.encrypt(memoryview(bytearray(pt)))
     pt2 = cipher.decrypt(memoryview(bytearray(ct)), "---")
     self.assertEqual(pt, pt2)
Beispiel #44
0
def rsaEncrypt(message):
    pubkey = "MIICkTCCAfoCCQDtC3okdmjaOTANBgkqhkiG9w0BAQUFADCBjDELMAkGA1UEBhMCQ04xEjAQBgNVBAgMCUd1YW5nRG9uZzELMAkGA1UEBwwCU1oxDzANBgNVBAoMBk1pblRvdTEPMA0GA1UECwwGTWluVG91MRUwEwYDVQQDDAxtaW50b3VqZi5jb20xIzAhBgkqhkiG9w0BCQEWFHNlcnZpY2VAbWludG91amYuY29tMB4XDTE2MDgxNzE4NTMxNloXDTI2MDgxNTE4NTMxNlowgYwxCzAJBgNVBAYTAkNOMRIwEAYDVQQIDAlHdWFuZ0RvbmcxCzAJBgNVBAcMAlNaMQ8wDQYDVQQKDAZNaW5Ub3UxDzANBgNVBAsMBk1pblRvdTEVMBMGA1UEAwwMbWludG91amYuY29tMSMwIQYJKoZIhvcNAQkBFhRzZXJ2aWNlQG1pbnRvdWpmLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAsOUUh/sLlrK5Q1ToHzMWjJxUXl7/3UdrIIwUHaSFQDUl2AuxO7otmi2qHPyfvtE1wgy9Dkc+GIlQ+kQdaGoU82+hdgEDZmqawWzPb5W7S4m0/9EBKMq3oe+YBOfq9HdcoFExFOcllFf4rMvb8d2qZCOv/l9Ln5OdCd5056OK2pcCAwEAATANBgkqhkiG9w0BAQUFAAOBgQAGqrJeCzjP5GLt6owQjb1MeTZBlwYaRg8/xbEz+1JkBBnw6YXCDz62pjc2KX90htzfwIFYKny96fBEaclM3xe9vVQtd0OVLfeA1BHETPcCmsTQzMlzxHmEoYKpBTEf+HPdZHUpsCvkCDp66tv3k7egJUtwl8gBqPBzdQrxE7yyew=="
    rsaKey = RSA.importKey(base64.b64decode(pubkey))
    cipher = Cipher_pkcs1_v1_5.new(rsaKey)
    temp = cipher.encrypt(message.encode())
    return binascii.b2a_hex(temp)
Beispiel #45
0
 def rsa_pkcs1_key_wrap(n, e, p):
     key = RSA.construct((n, e))
     cipher = PKCS1_v1_5_cipher.new(key)
     return cipher.encrypt(p)
Beispiel #46
0
def decrypt(prikey, message):
    random = Random.new().read
    rsakey = RSA.importKey(prikey)
    cipher = PKCS1_Cipher.new(rsakey)
    decrypted = cipher.decrypt(base64.b64decode(message), random)
    return decrypted.decode('utf-8')
Beispiel #47
0
def rsa_decrypt(ciphertext, key):
    cipher = PKCS1_v1_5.new(RSA.importKey(key))
    return cipher.decrypt(ciphertext, '')
def main():
    # Set login datas
    login_id = input('학번을 입력해 주세요 : ')
    login_pw = getpass.getpass(prompt='비밀번호를 입력해 주세요 : ', stream=None)
    login_datas = json.dumps({
        'loginId': login_id,
        'loginPwd': login_pw,
        'storeIdYn': 'N'
    })

    # Encrypt with RSA
    public_key = hr.postRequest(
        'https://klas.kw.ac.kr/usr/cmn/login/LoginSecurity.do').json(
        )['publicKey']
    rsa_key = RSA.import_key(base64.b64decode(public_key))
    cipher = PKCS1_v1_5.new(rsa_key)
    login_token = cipher.encrypt(bytes(login_datas, 'utf8'))
    login_token = base64.b64encode(login_token).decode()

    # Request login
    login_result = hr.postRequest(
        'https://klas.kw.ac.kr/usr/cmn/login/LoginConfirm.do', {
            'loginToken': login_token,
            'redirectUrl': '',
            'redirectTabUrl': ''
        }).json()

    if len(login_result['fieldErrors']) > 0:
        log_message('Error', login_result['fieldErrors'][0]['message'])
        return

    log_message('Info', '로그인 성공')

    # Set syllabus data
    syllabus_year = input('강의 계획서의 년도를 입력하세요 : ')
    syllabus_semester = input('강의 계획서의 학기를 입력하세요 : ')

    # Get all syllabus
    syllabus_result = hr.postRequest(
        'https://klas.kw.ac.kr/std/cps/atnlc/LectrePlanStdList.do', {
            'selectYear': syllabus_year,
            'selecthakgi': syllabus_semester,
            'selectRadio': 'all'
        }).json()

    if len(syllabus_result) == 0:
        log_message('Error', '강의 계획서 정보가 없습니다.')
        return

    syllabus_count = len(syllabus_result)
    log_message('Info', '%d개의 강의 계획서 정보를 불러왔습니다.' % syllabus_count)

    # Alert message
    if input('강의실 정보를 불러옵니다. 이 작업은 서버에 부하를 줄 수 있습니다. [Y / N] : ') != 'Y':
        return

    lecture_list = []
    progress_count = 0

    # Parse syllabus info
    for syllabus_info in syllabus_result:
        lecture_info = get_lecture_info(syllabus_info)
        lecture_list += lecture_info

        progress_count += 1
        progress_bar(progress_count, syllabus_count)
        time.sleep(0.25)

    print('')
    log_message('Info', '모든 정보를 정상적으로 불러왔습니다.')

    # Save to file
    f = open('%d-%02d.json' % (int(syllabus_year), int(syllabus_semester)),
             'w',
             encoding='utf8')
    f.write(json.dumps(lecture_list, ensure_ascii=False))
    f.close()

    log_message('Info', '모든 정보가 파일에 저장되었습니다.')
Beispiel #49
0
def download_book(bookid, booksum = 1):
    global book_cnt
    detail = parse_detail_url(bookid)
    #print(detail.content)
    AuthorizeToken, Title = get_token_tile(detail)
    logging.info('%s parse detial url done!'%bookid)

    authorize = parse_authorize_url(bookid, AuthorizeToken)
    aes_key, book_url, SplitFileUrls = get_key_urls(authorize)
    logging.info('%s parse authorize url done!'%bookid)
            
    get_bookmark(bookid)

    rsakey = RSA.importKey(rsa['privateKey'])
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    text = cipher.decrypt(base64.b64decode(aes_key), None)
    aes_key = str(text, encoding='utf-8')
    logging.info('%s decrypt AES key done!'%bookid)
    
    print(SplitFileUrls)
    page_sum = len(SplitFileUrls)
    tasks = [i for i in range(1, page_sum+1)]
    tasks_path = Path(TaskFilePath+bookid+'.txt')

    if tasks_path.exists():
        tasks = load_taskfile(bookid)
        logging.info('%s taskfile already exist, jump'%bookid)#bug
    else: 
        # 第一次运行
        save_taskfile(bookid, tasks)

    while tasks:
        # popleft
        num = tasks.pop(0) # num : int
        try:
            page_url = SplitFileUrls[num - 1]
            download_pdf_page(page_url, bookid, Title, num, aes_key)
            # 存档
            save_taskfile(bookid, tasks)
            logging.info('%s<%s> page %d/%d OK [%d/%d]'%(bookid, Title, num, page_sum, book_cnt, booksum))
            slptime = round(random.uniform(10 ,20))
            time.sleep(slptime)
        except:
            tasks.append(num)
            save_taskfile(bookid, tasks)
            logging.error('%s<%s> page %d/%d ERROR [%d/%d]'%(bookid, Title, num, page_sum, book_cnt, booksum))

    # 合并PDF
    floder = os.path.join(BookPath, bookid)
    if not os.path.exists(floder):
        os.makedirs(floder)
    
    # 检查是否已经转换过
    pdf = Path(BookPath, bookid, bookid+'-'+Title+'.pdf')

    if not pdf.exists():
        logging.info('%s merge pdf ...'%bookid)
        pdfpath = os.path.join(DownloadPath, bookid)
        try:
            file_name_walk(pdfpath, bookid)
            logging.info('%s merge pdf done!'%bookid)
            book_cnt += 1
        except:
            logging.error('%s merge pdf error!'%bookid)
    else:
        book_cnt += 1
        logging.warning('%s pdf already exists!'%bookid)
Beispiel #50
0
def secrecy(params):
    try:
        if params['type'] in ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'sha3_224', 'sha3_256', 'sha3_384',
                              'sha3_512', 'blake2b', 'blake2s', 'shake_128', 'shake_256']:
            return True, getattr(hashlib, params['type'])(params['text'].encode()).hexdigest()
        elif params['type'] == 'AES':
            if len(params['key']) > 32:
                return False, 'The \'key\' cannot be longer than 32'
            while len(params['key']) not in [16, 24, 32]:
                params['key'] += ' '
            while len(params['text']) % 32 != 0:
                params['text'] += ' '
            aes = AES.new(params['key'].encode("utf-8"), AES.MODE_ECB)
            return True, base64.encodebytes(aes.encrypt(params['text'].encode('utf-8'))).decode().rstrip('\n')
        elif params['type'] == 'D-AES':
            if len(params['key']) > 32:
                return False, 'The \'key\' cannot be longer than 32'
            while len(params['key']) not in [16, 24, 32]:
                params['key'] += ' '
            aes = AES.new(params['key'].encode("utf-8"), AES.MODE_ECB)
            return True, aes.decrypt(base64.decodebytes(params['text'].encode())).decode().rstrip(' ')
        elif params['type'] == 'DES':
            if len(params['key']) > 8:
                return False, 'The \'key\' cannot be longer than 8'
            while len(params['key']) < 8:
                params['key'] += ' '
            while len(params['text']) % 8 != 0:
                params['text'] += ' '
            des = DES.new(params['key'].encode("utf-8"), DES.MODE_ECB)
            return True, base64.encodebytes(des.encrypt(params['text'].encode('utf-8'))).decode().rstrip('\n')
        elif params['type'] == 'D-DES':
            if len(params['key']) > 8:
                return False, 'The \'key\' cannot be longer than 8'
            while len(params['key']) < 8:
                params['key'] += ' '
            des = DES.new(params['key'].encode("utf-8"), DES.MODE_ECB)
            return True, des.decrypt(base64.decodebytes(params['text'].encode())).decode().rstrip(' ')
        elif params['type'] == 'DES3':
            if len(params['key']) > 16:
                return False, 'The \'key\' cannot be longer than 16'
            while len(params['key']) < 16:
                params['key'] += ' '
            while len(params['text']) % 8 != 0:
                params['text'] += ' '
            des3 = DES3.new(params['key'].encode("utf-8"), DES3.MODE_ECB)
            return True, base64.encodebytes(des3.encrypt(params['text'].encode('utf-8'))).decode().rstrip('\n')
        elif params['type'] == 'D-DES3':
            if len(params['key']) > 16:
                return False, 'The \'key\' cannot be longer than 16'
            while len(params['key']) < 16:
                params['key'] += ' '
            des3 = DES3.new(params['key'].encode("utf-8"), DES3.MODE_ECB)
            return True, des3.decrypt(base64.decodebytes(params['text'].encode())).decode().rstrip(' ')
        elif params['type'] == 'rsa-k':
            length = params.get('length', '1024')
            if int(length) < 1024:
                length = "1024"
            password = params.get('password', None)
            if password == "":
                password = None
            x = RSA.generate(int(length), Random.new().read)
            s_key = x.export_key(passphrase=password, pkcs=8, protection="scryptAndAES128-CBC")
            g_key = x.publickey().export_key()
            return True, [s_key.decode(), g_key.decode()]
        elif params['type'] == 'rsa-e':
            password = params.get('password', None)
            if password == "":
                password = None
            g_key = PKCS1_v1_5.new(RSA.importKey(params['pub_k'], passphrase=password))
            en_data = g_key.encrypt(params['text'].encode())
            return True, base64.b64encode(en_data).decode()
        elif params['type'] == 'rsa-d':
            password = params.get('password', None)
            if password == "":
                password = None
            s_key = PKCS1_v1_5.new(RSA.importKey(params['pri_k'], passphrase=password))
            de_data = s_key.decrypt(base64.b64decode(params['text']), Random.new().read).decode()
            return True, de_data
        else:
            return False, 'params error'
    except Exception as ex:
        return False, str(ex)
    -102, -76, 47, 124, 124, 65, -127, -65, 50, 28, -63, -56, 48, 127, 48, -36,
    -121, -109, 6, -114, 72, -96, -100, -3, 72, -62, -55, -52, 24, 6, -24, 1,
    -113, 50, 116, 68, 74, 71, -70, -8, 14, -96, 121, 10, -98, 92, -4, -119,
    -55, 112, 102, 54, 73, 1, -20, 71, -113, -28, -123, -8, -99, 9
]

# create key object
n = [ctypes.c_ubyte(i).value for i in n]
d = [ctypes.c_ubyte(i).value for i in d]
n = int(''.join(format(x, '02x') for x in n), 16)
d = int(''.join(format(x, '02x') for x in d), 16)
priKey = RSA.construct((n, e, d)).exportKey()
pubKey = RSA.construct((n, e)).exportKey()
private_key = RSA.import_key(priKey)
public_key = RSA.import_key(pubKey)
cipher_rsa_pri = PKCS1_v1_5.new(private_key)

#########################  MONGODB ACCESS
db_client = MongoClient('localhost', 27017)
db_db = db_client.xtldb
db_xtlcard = db_db.xtlcard


def verify_transactions_first_stage(cipherTxs):
    dsize = SHA.digest_size
    sentinel = Random.new().read(15 + dsize)

    userCredentials = None
    userHash = None
    serverInvocationCounter = None
    balance = None
Beispiel #52
0
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64encode

message = "我是要加密的訊息"
new_key = RSA.generate(1024)
prikey = new_key.exportKey("PEM").decode('ascii')
pubkey = new_key.publickey().exportKey("PEM").decode('ascii')

pubKeyObj = RSA.import_key(pubkey)
priKeyObj = RSA.import_key(prikey)
cipher = PKCS1_v1_5.new(pubKeyObj)
emsg = cipher.encrypt(message.encode())

e = PKCS1_v1_5.new(priKeyObj)
decrypt_text = e.decrypt(emsg, None).decode()
print("加密->", b64encode(emsg))
print("解密的訊息->", decrypt_text)
Beispiel #53
0
def rsa_decryption(msg, private_key):
    random_generator = Random.new().read
    cipher = Cipher_pkcs1_v1_5.new(private_key)
    text = cipher.decrypt(base64.b64decode(msg), random_generator)
    return text
Beispiel #54
0
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
from urllib import parse
from public import config

try:
    with open(config.RSA_PRIKEY_FILE_PATH, "rb") as file:
        privkey_b = file.read()
    privkey = RSA.importKey(privkey_b)
    cipher_rsa = PKCS1_v1_5.new(privkey)
except Exception as e:
    print(e)


def encrypt(context):
    return cipher_rsa.encrypt(context.encode('utf8')).decode('utf8')


def decrypt(context):
    context = parse.unquote(context)
    context = base64.b64decode(context)
    decontext = cipher_rsa.decrypt(context, None)
    if decontext is None:
        return None
    return decontext
def sign(privatekey, data):
    cipher = csign.new(privatekey)
    cipher_text = cipher.encrypt(data.encode())
    return base64.b64encode(cipher_text)
Beispiel #56
0
def rsa_encryption(msg, public_key):
    cipher = Cipher_pkcs1_v1_5.new(public_key)
    cipher_text = base64.b64encode(cipher.encrypt(msg))
    return cipher_text
Beispiel #57
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 #58
0
h+PdDw4DgC06j1VxOa2LA5tm9lPXkLUTlGDxz0blF4601hqO6XGc57tGfqECQQCT
CBZbj8H1s5WTbbeVQGsfa2CB2IFq6VehncMTEzeAmsNcrCUAsijv1M3kAUg/50kH
GaBQwkkEbSQmVAjJGFylAkBDibHDD1cms1DHyqFMxqkPG0Y50N0eu1hU7brZfQPB
kNRpW9f/TE97QOb8ux867n2i0/q0YpjWSTY6XsZncKkI
-----END RSA PRIVATE KEY-----'''


def generate_key():
    rsa_key = RSA.generate(1024)
    pri = rsa_key.exportKey()
    with open('private.pem', 'w+') as f:
        f.write(pri.decode())
        f.close()
    pub = rsa_key.publickey().exportKey()
    with open('public.pem', 'w+') as f:
        f.write(pub.decode())
        f.close()


if __name__ == '__main__':
    # generate_key()
    rsa_key = RSA.importKey(PUB_KEY)
    x = PKCS1_v1_5.new(rsa_key).encrypt('lazzy'.encode())
    x = base64.b64encode(x).decode()
    # x = 'f1lQLhP19w6p1Q0jgA2i3EIFWtnA/wj5aTp8mJn8PLEeIJ2GxLohPDMUr1GNbngIjVEmAuIFbLLku3BL8NEsll+xlovWOXV/cA5W/INPpJlUz8kBtIOn9Yj9zTqUAy2LnHHrZm0v3TapY9J/TSBYR/DjV7dV2PxZH4WMLNPyRgc='
    rsa_privkey = RSA.importKey(PRIVATE_KEY)
    y = PKCS1_v1_5.new(rsa_privkey).decrypt(base64.b64decode(x), None)
    print(y == 'lazzy'.encode('utf-8'))


Beispiel #59
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 #60
0
def rsa_encrypt(plaintext, key):
    cipher = PKCS1_v1_5.new(RSA.importKey(key))
    return cipher.encrypt(plaintext)