Python rsa.encrypt() Examples

The following are 30 code examples of rsa.encrypt(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rsa , or try the search function .
Example #1
Source File: security.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def aes_encrypt(self, data):
		count = 0
		encrypt = []

		if common.is_python2x():
			for i in data:
				encrypt.append(chr(ord(i) ^ ord(self.aes[count % len(self.aes)])))
				count += 1
			
			return b"".join(encrypt)
		else:
			for i in data:
				encrypt.append(i ^ self.aes[count % len(self.aes)])
				count += 1

			return bytes(encrypt)
				
		#aes_obj_enc = AES.new(self.aes, AES.MODE_CBC, self.iv)
		#return aes_obj_enc.encrypt(pad(data)) 
Example #2
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 6 votes vote down vote up
def to_encrypt(cls, message, public_path=None, public_key=None, be_base64=True):
        # 非对称加密
        """
        :param message: 待加密字符串或者字节
        :param public_path: 公钥路径  二选一
        :param public_key: 公钥字符串  二选一
        :return: base64密文字符串
        """

        message = cls.check_message(message)
        public_key_obj = cls.load_public_key(public_path, public_key)

        cryto_msg = rsa.encrypt(message, public_key_obj)  # 生成加密文本
        if be_base64: return base64.b64encode(cryto_msg).decode("utf-8")  # 将加密文本转化为 base64 编码

        return cryto_msg  # 将字节类型的 base64 编码转化为字符串类型


### 当前时间 
Example #3
Source File: bcrypt_hash.py    From listen-now with MIT License 6 votes vote down vote up
def Creat_Return_Token(self, token_crypto):

        tag = bytes("NQZ",encoding="utf8")

        # with open('../project/Helper/pubkey.pem','r') as f:
        #     pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())

        with open('../project/Helper/privkey.pem','r') as f:
            privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())
        token_message = token_crypto
        # token_crypto = rsa.encrypt(token_message.encode(), pubkey)
        # 不进行公钥加密
        # 直接反馈加上标准内容的信息
        token_crypto = bytes(token_crypto, encoding='utf8') + tag
        signature = rsa.sign(token_message.encode(), privkey, 'SHA-1')
        print("token message encode = ", token_message.encode())
        # 利用私钥对信息进行签名
        signature = base64.encodestring(signature)
        return (token_crypto, signature)
        # 返回生成的token 和 sign 签名值 
Example #4
Source File: sinal2.py    From sinal2 with MIT License 5 votes vote down vote up
def encrypt_passwd(self, passwd, pubkey, servertime, nonce):
        key = rsa.PublicKey(int(pubkey, 16), int('10001', 16))
        message = str(servertime) + '\t' + str(nonce) + '\n' + str(passwd)
        passwd = rsa.encrypt(message.encode('utf-8'), key)
        return binascii.b2a_hex(passwd) 
Example #5
Source File: encrypter.py    From opsbro with MIT License 5 votes vote down vote up
def generate_challenge(self, zone_name):
        challenge_string = get_uuid()
        RSA = self.get_RSA()
        public_key = self.get_mf_pub_key()
        raw_encrypted_string = RSA.encrypt(unicode_to_bytes(challenge_string), public_key)  # encrypt 0=dummy param not used
        encrypted_challenge = bytes_to_unicode(base64.b64encode(raw_encrypted_string))  # base64 returns bytes
        return challenge_string, encrypted_challenge 
Example #6
Source File: cli.py    From opsbro with MIT License 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args=None):
        '''Encrypts files.'''

        return rsa.encrypt(indata, pub_key) 
Example #7
Source File: auth.py    From AsyncLine with MIT License 5 votes vote down vote up
def __rsa_crypt(self, message,RSA):
		pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
		crypto  = rsa.encrypt(message, pub_key)
		return crypto 
Example #8
Source File: bilibili.py    From bilibili-live-tools with MIT License 5 votes vote down vote up
def calc_name_passw(self, key, Hash, username, password):
        pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(key.encode())
        password = base64.b64encode(rsa.encrypt(
            (Hash + password).encode('utf-8'), pubkey))
        password = parse.quote_plus(password)
        username = parse.quote_plus(username)
        return username, password 
Example #9
Source File: Sina.py    From dHydra with Apache License 2.0 5 votes vote down vote up
def get_sp(self, passwd, pubkey, servertime, nonce):
        key = rsa.PublicKey(int(pubkey, 16), int('10001', 16))
        message = str(servertime) + '\t' + str(nonce) + '\n' + str(passwd)
        passwd = rsa.encrypt(message.encode('utf-8'), key)
        return binascii.b2a_hex(passwd).decode('ascii') 
Example #10
Source File: cli.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args=None):
        """Encrypts files."""

        return rsa.encrypt(indata, pub_key) 
Example #11
Source File: rsaencrypt.py    From seecode-scanner with GNU General Public License v3.0 5 votes vote down vote up
def encrypt_str(self, message):
        """

        :param message:
        :return:
        """
        if not isinstance(message, bytes):
            msg = message.encode('utf-8')
        else:
            msg = message
        length = len(msg)

        # 长度不用分段
        if length < self.default_length:
            return base64.b64encode(rsa.encrypt(msg, self.public_key))
        # 需要分段
        offset = 0
        res = []
        while length - offset > 0:
            if length - offset > self.default_length:
                res.append(rsa.encrypt(msg[offset:offset + self.default_length], self.public_key))
            else:
                res.append(rsa.encrypt(msg[offset:], self.public_key))
            offset += self.default_length
        byte_data = b''.join(res)

        return base64.b64encode(byte_data) 
Example #12
Source File: connection.py    From pyexasol with MIT License 5 votes vote down vote up
def _encrypt_password(self, public_key_pem):
        pk = rsa.PublicKey.load_pkcs1(public_key_pem.encode())
        return base64.b64encode(rsa.encrypt(self.options['password'].encode(), pk)).decode() 
Example #13
Source File: bcrypt_hash.py    From listen-now with MIT License 5 votes vote down vote up
def Creat_Token(self, timevalue, nickname, ip, ua):

        token_message = str(int(time.time()+timevalue*3600))+';'+nickname+';'+ip+';'+ua+';'+str(int(time.time()))
        texts = self.Pad_Text(token_message)
        aes = AES.new(self.key, self.mode,self.key)
        res = aes.encrypt(texts)

        Token = loginer()
        Token_Crypto            = Token.Creat_Return_Token(str(b2a_base64(res), encoding= "utf-8"))
        # print(str(Token_Crypto[0]))
        self.r.set(Token_Crypto[0], nickname)
        self.r.expire(Token_Crypto[0], 60)  
        # 生成预token
        # print(self.r.get(Token_Crypto[0]))

        re_dict["token_status"] = ReturnStatus.TOKEN_CREAT_SUCCESS
        return Token_Crypto 
Example #14
Source File: Base.py    From BiliBiliHelper with GNU General Public License v3.0 5 votes vote down vote up
def openssl_public_encrypt(plaintext, key):
    key = rsa.PublicKey.load_pkcs1_openssl_pem(key)
    ciphertext = rsa.encrypt(plaintext.encode(), key)
    return ciphertext 
Example #15
Source File: Talk.py    From linezx with MIT License 5 votes vote down vote up
def __crypt(self, mail, passwd, RSA):
    message = (chr(len(RSA.sessionKey)) + RSA.sessionKey +
                   chr(len(mail)) + mail +
                   chr(len(passwd)) + passwd).encode('utf-8')

    pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
    crypto = rsa.encrypt(message, pub_key).encode('hex')

    return crypto 
Example #16
Source File: cli.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args=None):
        """Encrypts files."""

        return rsa.encrypt(indata, pub_key) 
Example #17
Source File: Talk.py    From LineChivas with GNU General Public License v3.0 5 votes vote down vote up
def __crypt(self, mail, passwd, RSA):
    message = (chr(len(RSA.sessionKey)) + RSA.sessionKey +
                   chr(len(mail)) + mail +
                   chr(len(passwd)) + passwd).encode('utf-8')

    pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
    crypto = rsa.encrypt(message, pub_key).encode('hex')

    return crypto 
Example #18
Source File: encrypter.py    From opsbro with MIT License 5 votes vote down vote up
def encrypt(self, data, dest_zone_name=None):
        encryption_key = self._get_key_from_zone(dest_zone_name)
        if encryption_key is None:  # we do not have valid key for this zone, cannot encrypt
            return unicode_to_bytes(data)
        
        AES = self.get_AES()
        
        # Be sure the data is x16 lenght
        if len(data) % 16 != 0:
            data += ' ' * (-len(data) % 16)
        # print('TO encrypt data size: %s' % len(data))
        
        try:
            cypher = AES.new(encryption_key, AES.MODE_ECB)
            encrypted_data = cypher.encrypt(data)
            encrypted_data_size = len(encrypted_data)
            key_fingerprint = self._get_finger_print_from_key(encryption_key)
            
            final_packet_format = '%ds%ds%ds' % (MAGIC_FLAG_SIZE, KEY_FINGERPRINT_SIZE, encrypted_data_size)
            # print('STRUCT FORMAT %s' % final_packet_format)
            final_packet = struct.pack(final_packet_format, unicode_to_bytes(MAGIC_FLAG), unicode_to_bytes(key_fingerprint), encrypted_data)
            # print('Final packet %s' % final_packet)
            # print('Final packet size: %s' % len(final_packet))
            return final_packet
        except Exception as exp:
            logger.error('Encryption fail:', exp)
            return u'' 
Example #19
Source File: encrypter.py    From opsbro with MIT License 5 votes vote down vote up
def _give_failback_raw_data_is_possible(self, raw_data):
        if self._is_our_zone_have_a_key():
            return None
        return raw_data
    
    
    # We received data from UDP, if we are set to encrypt, decrypt it 
Example #20
Source File: cli.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args=None):
        '''Encrypts files.'''

        return rsa.encrypt(indata, pub_key) 
Example #21
Source File: WeiboSuperCommentScrapy.py    From WeiboSuperSpider with Apache License 2.0 5 votes vote down vote up
def get_password(self, servertime, nonce, pubkey):
        """对密码进行 RSA 的加密"""
        rsaPublickey = int(pubkey, 16)
        key = rsa.PublicKey(rsaPublickey, 65537)  # 创建公钥
        message = str(servertime) + '\t' + str(nonce) + '\n' + str(self.password)  # 拼接明文js加密文件中得到
        message = message.encode("utf-8")
        passwd = rsa.encrypt(message, key)  # 加密
        passwd = binascii.b2a_hex(passwd)  # 将加密信息转换为16进制。
        return passwd 
Example #22
Source File: cli.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args=None):
        """Encrypts files."""

        return rsa.encrypt(indata, pub_key) 
Example #23
Source File: auth.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def RSA_encrypt(public_key, message):
    rsakey = rsa.PublicKey.load_pkcs1_openssl_pem(public_key)
    encrypted = rsa.encrypt(message.encode('utf-8'), rsakey)
    return base64.encodestring(encrypted).decode('utf-8').replace('\n', '') 
Example #24
Source File: bilibili.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def get_encryped_pwd(self, pwd):
        import rsa
        result = json.loads(utils.get_page_content(LOGIN_HASH_URL.format(random.random()),
                                                   headers={'Referer':'https://passport.bilibili.com/login'}))
        pwd = result['hash'] + pwd
        key = result['key']
        pub_key = rsa.PublicKey.load_pkcs1_openssl_pem(key)
        pwd = rsa.encrypt(pwd.encode('utf-8'), pub_key)
        pwd = base64.b64encode(pwd)
        pwd = urllib.quote(pwd)
        return pwd 
Example #25
Source File: cli.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, pub_key, cli_args=None):
        """Encrypts files."""

        return rsa.encrypt(indata, pub_key) 
Example #26
Source File: SDK基类.py    From TSDK with MIT License 5 votes vote down vote up
def RSAencrypt(self,public_key:'公钥',sign_str:str,salt:'盐'=''):
        '''通过字符串公钥提取模数和指数生成公钥去加密'''
        modulus_num , exponent_num = self.str2key(public_key)
        modulus = int(modulus_num,16)
        exponent = int(exponent_num,16)
        rsa_pubkey = rsa.PublicKey(modulus,exponent)
        crypto = rsa.encrypt(sign_str.encode(),rsa_pubkey)
        crypto = b64encode(crypto)
        return crypto.decode() 
Example #27
Source File: SDK基类.py    From TSDK with MIT License 5 votes vote down vote up
def encrypt(self,t:str):
        ''' 支付宝加密方法'''
        t = t[:245]
        counter = 0
        e = ''
        while len(e) != 344 and counter < 10:
            pass 
Example #28
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def my_encrypt(self, text):
        """
        加密方法
        :param text: 密码
        :return:
        """
        aes = AES.new(self.add_to_16(self.key), AES.MODE_ECB)
        # 先进行aes加密

        encrypt_aes = aes.encrypt(self.add_to_16(text))
        # 用base64转成字符串形式
        encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8').replace('\n', '')  # 执行加密并转码返回bytes
        # print('[INFO]: 你的加密为:{}'.format(encrypted_text))
        return encrypted_text 
Example #29
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def my_encrypt(self, text):
        length = 32
        count = len(text)
        if count < length:
            add = length - count
            text = text + ('\0' * add)

        elif count > length:
            add = (length - (count % length))
            text = text + ('\0' * add)

        cryptor = AES.new(self.key, self.mode, b'0000000000000000')
        self.ciphertext = cryptor.encrypt(text)
        return b2a_hex(self.ciphertext).decode('utf-8') 
Example #30
Source File: Talk.py    From CyberTK-Self with GNU General Public License v2.0 5 votes vote down vote up
def __crypt(self, mail, passwd, RSA):
    message = (chr(len(RSA.sessionKey)) + RSA.sessionKey +
                   chr(len(mail)) + mail +
                   chr(len(passwd)) + passwd).encode('utf-8')

    pub_key = rsa.PublicKey(int(RSA.nvalue, 16), int(RSA.evalue, 16))
    crypto = rsa.encrypt(message, pub_key).encode('hex')

    return crypto