Esempio n. 1
0
def encode_password(password, servertime, nonce, pubkey):
    rsaPubkey = int(pubkey, 16)
    RSAKey = rsa.PublicKey(rsaPubkey, 65537)
    codeStr = str(servertime) + '\t' + str(nonce) + '\n' + str(password)
    pwd = rsa.encrypt(codeStr, RSAKey)
    return binascii.b2a_hex(pwd)
Esempio n. 2
0
 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')
Esempio n. 3
0
def receiving():
    global clients
    while True:
        client, addr = sock.accept()
        time.sleep(int(config_data['keys_exchanging_delay']) / 2)
        client.send(str(server_pubkey.n).encode('utf-8'))
        time.sleep(int(config_data['keys_exchanging_delay']) / 2)
        client.send(str(server_pubkey.e).encode('utf-8'))
        nickname = (rsa.decrypt(client.recv(2048),
                                server_privkey)).decode('utf-8')
        current_client_pubkey_n = client.recv(2048).decode('utf-8')
        current_client_pubkey_e = client.recv(2048).decode('utf-8')
        current_client_pubkey = rsa.PublicKey(int(current_client_pubkey_n),
                                              int(current_client_pubkey_e))
        client_info = client, current_client_pubkey
        for i in clients:
            client_addr, client_pubkey = i
            client_addr.send(
                rsa.encrypt(
                    ('{res}[{green}{nickname}{res}]{blue} →  Join chat {res}'.
                     format(res=res_C,
                            nickname=nickname,
                            green=green_C,
                            blue=blue_C)).encode('utf-8'), client_pubkey))
        clients.append(client_info)
        list_of_users.append(nickname)
        print('[{addr}] [{nickname}] Connected'.format(addr=str(addr),
                                                       nickname=str(nickname)))
        while True:
            permission_to_transmission = True
            data = client.recv(2048)
            data = (rsa.decrypt(data, server_privkey)).decode('utf-8')
            if data == '!exit':
                client.close()
                print('[{addr}] [{nickname}] Disconnected'.format(
                    addr=str(addr), nickname=str(nickname)))
                time.sleep(0.1)
                clients.remove(client_info)
                list_of_users.remove(nickname)
                for i in clients:
                    client_addr, client_pubkey = i
                    client_addr.send(
                        rsa.encrypt((
                            '{res}[{green}{nickname}{res}]{blue} →  Left chat {res}'
                            .format(res=res_C,
                                    nickname=nickname,
                                    green=green_C,
                                    blue=blue_C)).encode('utf-8'),
                                    client_pubkey))
                break
            elif data == '!aou':
                amount = str(len(list_of_users))
                client.send(
                    rsa.encrypt(
                        ('{green}Amount of users online: {blue}{amount}{res}'.
                         format(green=green_C,
                                blue=blue_C,
                                amount=amount,
                                res=res_C)).encode('utf-8'),
                        current_client_pubkey))
                permission_to_transmission = False
            elif data == '!lou':
                for i in list_of_users:
                    client.send(
                        rsa.encrypt((green_C + i + res_C).encode('utf-8'),
                                    current_client_pubkey))
                permission_to_transmission = False

            if permission_to_transmission:
                print('[{addr}] [{nickname}] →  '.format(
                    addr=str(addr), nickname=str(nickname)) + 'sent a message')
                transmission(data, nickname, client)
Esempio n. 4
0
 def public_key(self):
     if isinstance(self._prepared_key, pyrsa.PublicKey):
         return self
     return self.__class__(
         pyrsa.PublicKey(n=self._prepared_key.n, e=self._prepared_key.e),
         self._algorithm)
Esempio n. 5
0
 def get_sp(self):
     '''同样是看的ssologin.js里面的代码,直接抄写了第一篇博客的代码'''
     publickey = rsa.PublicKey(int(self.pubkey, 16), int('10001', 16))
     message = str(self.servertime) + '\t' + str(self.nonce) + '\n' + str(self.password)
     self.sp = rsa.encrypt(message.encode(), publickey)
     return b2a_hex(self.sp)
Esempio n. 6
0
	def login(self, username, password, mode='mobile', crackvcFunc=None, **kwargs):
		# 设置代理
		self.session.proxies.update(kwargs.get('proxies', {}))
		# 移动端接口
		if mode == 'mobile':
			self.__initializeMobile()
			data = {
					'username': username,
					'password': password,
					'savestate': '1',
					'r': 'https://weibo.cn/',
					'ec': '0',
					'pagerefer': 'https://weibo.cn/pub/',
					'entry': 'mweibo',
					'wentry': '',
					'loginfrom': '',
					'client_id': '',
					'code': '',
					'qq': '',
					'mainpageflag': '1',
					'hff': '',
					'hfp': ''
					}
			res = self.session.post(self.login_url, headers=self.login_headers, data=data)
			res_json = res.json()
			# 登录成功
			if res_json['retcode'] == 20000000:
				print('[INFO]: Account -> %s, login successfully...' % username)
				infos_return = {'username': username}
				infos_return.update(res_json)
				return infos_return, self.session
			# 用户名或密码错误
			elif res_json['retcode'] == 50011002:
				raise RuntimeError('Account -> %s, fail to login, username or password error...' % username)
			# 其他错误
			else:
				raise RuntimeError(res_json['msg'])
		# PC端接口
		elif mode == 'pc':
			self.__initializePC()
			# 进行模拟登录
			add_verification_code = False
			while True:
				# --是否需要验证码
				if add_verification_code:
					params = {
								'r': str(int(random.random()*100000000)),
								's': '0'
							}
					res = self.session.get(self.pin_url, headers=self.headers, params=params)
					saveImage(res.content, os.path.join(self.cur_path, 'captcha.jpg'))
					if crackvcFunc is None:
						showImage(os.path.join(self.cur_path, 'captcha.jpg'))
						captcha = input('Input the Verification Code:')
					else:
						captcha = crackvcFunc(os.path.join(self.cur_path, 'captcha.jpg'))
					removeImage(os.path.join(self.cur_path, 'captcha.jpg'))
				# --请求prelogin_url
				su = base64.b64encode(username.encode())
				params = {
							'entry': 'weibo',
							'su': su,
							'rsakt': 'mod',
							'checkpin': '1',
							'client': 'ssologin.js(v1.4.19)',
							'_': str(int(time.time()*1000))
						}
				res = self.session.get(self.prelogin_url, headers=self.headers, params=params, verify=False)
				res_json = res.json()
				nonce = res_json.get('nonce', '')
				pubkey = res_json.get('pubkey', '')
				rsakv = res_json.get('rsakv', '')
				servertime = res_json.get('servertime', '')
				# --请求ssologin_url
				publickey = rsa.PublicKey(int(pubkey, 16), int('10001', 16))
				sp = rsa.encrypt((str(servertime)+'\t'+nonce+'\n'+password).encode(), publickey)
				sp = b2a_hex(sp)
				data_post = {
								'entry': 'account',
								'gateway': '1',
								'from': '',
								'savestate': '30',
								'useticket': '0',
								'useticket': '1',
								'pagerefer': '',
								'vsnf': '1',
								'su': su,
								'service': 'account',
								'servertime': str(int(servertime)+random.randint(1, 20)),
								'nonce': nonce,
								'pwencode': 'rsa2',
								'rsakv': rsakv,
								'sp': sp,
								'sr': '1536 * 864',
								'encoding': 'UTF - 8',
								'cdult': '3',
								'domain': 'sina.com.cn',
								'prelt': '95',
								'returntype': 'TEXT'
							}
				if add_verification_code:
					data_post['door'] = captcha
				res = self.session.post(self.ssologin_url, headers=self.headers, data=data_post, allow_redirects=False, verify=False)
				res_json = res.json()
				# --登录成功
				if res_json['retcode'] == '0':
					break
				# --用户名或密码错误
				elif res_json['retcode'] == '101':
					raise RuntimeError('Account -> %s, fail to login, username or password error...' % username)
				# --验证码错误
				elif res_json['retcode'] == '2070':
					raise RuntimeError('Account -> %s, fail to login, crack captcha error...' % username)
				# --需要验证码
				elif res_json['retcode'] == '4049':
					add_verification_code = True
				# --其他错误
				else:
					raise RuntimeError(res_json.get('reason', ''))
			ticket, ssosavestate = re.findall(r'ticket=(.*?)&ssosavestate=(.*?)"', res.text)[0]
			# 请求login_url和home_url, 进一步验证登录是否成功
			params = {
						'ticket': ticket,
						'ssosavestate': str(ssosavestate),
						'callback': 'sinaSSOController.doCrossDomainCallBack',
						'scriptId': 'ssoscript0',
						'client': 'ssologin.js(v1.4.19)',
						'_': str(int(time.time() * 1000))
					}
			params = '&'.join(['%s=%s' % (key, value) for key, value in params.items()])
			res = self.session.get(self.login_url+params, headers=self.headers, verify=False)
			uid = re.findall(r'"uniqueid":"(.*?)"', res.text)[0]
			res = self.session.get(self.home_url % uid, headers=self.headers, verify=False)
			if '我的首页' in res.text:
				print('[INFO]: Account -> %s, login successfully...' % username)
				infos_return = {'username': username}
				infos_return.update(res_json)
				return infos_return, self.session
			else:
				raise RuntimeError('Account -> %s, fail to login, visit %s error...' % (username, self.home_url % uid))
		else:
			raise ValueError('Unsupport argument in weibo.login -> mode %s, expect <mobile> or <pc>...' % mode)
Esempio n. 7
0
 def rsa_encrypt(self, value):
     result = rsa.pkcs1.encrypt(value.encode('ascii'),
                                rsa.PublicKey(self.modulus, self.exponent))
     return ''.join('%02x' % c for c in reversed(result))
Esempio n. 8
0
 def encode_password(code_str):
     pub_key = rsa.PublicKey(int(self.pubkey, 16), 65537)
     crypto = rsa.encrypt(code_str.encode('utf8'), pub_key)
     return binascii.b2a_hex(crypto)  # 转换成16进制
Esempio n. 9
0
class QQ:
    '''
    >>> qq = QQ(12345678, 'password')
    >>> qq.login()
    >>> qq.sayHi()
    '''
    appid = 549000912
    action = '4-22-1450611437613'
    urlSuccess = 'http://qzs.qq.com/qzone/v5/loginsucc.html?para=izone'
    urlCheck = 'http://check.ptlogin2.qq.com/check'
    # urlCheck = 'https://ssl.ptlogin2.qq.com/check'
    urlImage = 'http://captcha.qq.com/getimage'
    urlLogin = '******'
    # urlLogin = '******'
    urlXLogin = '******'

    def __init__(self, user, pwd):
        self.user = user
        self.pwd = pwd
        self.nick = None
        self.session = requests.Session()
        self.xlogin()

    def fetch(self, url, data=None, **kw):
        if data is None:
            func = self.session.get
        else:
            kw['data'] = data
            func = self.session.post
        return func(url, **kw)

    def xlogin(self):
        '''
        Get a log-in signature in cookies.
        '''
        self.fetch(self.urlXLogin,
                   params={
                       'proxy_url':
                       'http://qzs.qq.com/qzone/v6/portal/proxy.html',
                       'daid': 5,
                       'no_verifyimg': 1,
                       'appid': self.appid,
                       's_url': self.urlSuccess,
                   })
        # print('login_sig:', self.session.cookies['pt_login_sig'])

    def login(self):
        '''
        Check for verify code and log in.
        '''
        login_sig = self.session.cookies['pt_login_sig']
        g = self.fetch(self.urlCheck,
                       params={
                           'pt_tea': 1,
                           'uin': self.user,
                           'appid': self.appid,
                           'js_ver': 10143,
                           'js_type': 1,
                           'u1': self.urlSuccess,
                           'login_sig': login_sig,
                       }).text
        v = re.findall('\'(.*?)\'', g)
        vcode = v[1]
        uin = v[2]
        if v[0] == '1':  # verify code needed
            vcode = self.getVerifyCode(vcode)
        g = self.fetch(self.urlLogin,
                       params={
                           'u':
                           self.user,
                           'verifycode':
                           vcode,
                           'pt_vcode_v1':
                           0,
                           'pt_verifysession_v1':
                           self.session.cookies['ptvfsession'],
                           'p':
                           self.pwdencode(vcode, uin, self.pwd),
                           'pt_randsalt':
                           0,
                           'u1':
                           self.urlSuccess,
                           'ptredirect':
                           0,
                           'h':
                           1,
                           't':
                           1,
                           'g':
                           1,
                           'from_ui':
                           1,
                           'ptlang':
                           2052,
                           'action':
                           self.action,
                           'js_ver':
                           10143,
                           'js_type':
                           1,
                           'aid':
                           self.appid,
                           'daid':
                           5,
                           'login_sig':
                           login_sig,
                       }).text
        r = re.findall('\'(.*?)\'', g)
        if r[0] != '0':
            raise LogInError(r[4])
        self.nick = r[5]

    def fromhex(self, s):
        # Python 3: bytes.fromhex
        return bytes(bytearray.fromhex(s))

    pubKey = rsa.PublicKey(
        int(
            'F20CE00BAE5361F8FA3AE9CEFA495362'
            'FF7DA1BA628F64A347F0A8C012BF0B25'
            '4A30CD92ABFFE7A6EE0DC424CB6166F8'
            '819EFA5BCCB20EDFB4AD02E412CCF579'
            'B1CA711D55B8B0B3AEB60153D5E0693A'
            '2A86F3167D7847A0CB8B00004716A909'
            '5D9BADC977CBB804DBDCBA6029A97108'
            '69A453F27DFDDF83C016D928B3CBF4C7', 16), 3)

    def pwdencode(self, vcode, uin, pwd):
        '''
        Encode password with tea.
        '''
        # uin is the bytes of QQ number stored in unsigned long (8 bytes)
        salt = uin.replace(r'\x', '')
        h1 = hashlib.md5(pwd.encode()).digest()
        s2 = hashlib.md5(h1 + self.fromhex(salt)).hexdigest().upper()
        rsaH1 = binascii.b2a_hex(rsa.encrypt(h1, self.pubKey)).decode()
        rsaH1Len = hex(len(rsaH1) // 2)[2:]
        hexVcode = binascii.b2a_hex(vcode.upper().encode()).decode()
        vcodeLen = hex(len(hexVcode) // 2)[2:]
        l = len(vcodeLen)
        if l < 4:
            vcodeLen = '0' * (4 - l) + vcodeLen
        l = len(rsaH1Len)
        if l < 4:
            rsaH1Len = '0' * (4 - l) + rsaH1Len
        pwd1 = rsaH1Len + rsaH1 + salt + vcodeLen + hexVcode
        saltPwd = base64.b64encode(
            tea.encrypt(self.fromhex(pwd1),
                        self.fromhex(s2))).decode().replace('/', '-').replace(
                            '+', '*').replace('=', '_')
        return saltPwd

    def getVerifyCode(self, vcode):
        '''
        Get the verify code image and ask use for a verification.
        '''
        r = self.fetch(self.urlImage,
                       params={
                           'r': 0,
                           'appid': self.appid,
                           'uin': self.user,
                           'vc_type': vcode,
                       })
        tmp = tempfile.mkstemp(suffix='.jpg')
        os.write(tmp[0], r.content)
        os.close(tmp[0])
        os.startfile(tmp[1])
        vcode = input('Verify code: ')
        os.remove(tmp[1])
        return vcode

    def sayHi(self):
        print('Hi, %s!' % (self.nick or self.user))
Esempio n. 10
0
 def gen_key(rsa_n, rsa_e):
     n = int(binascii.b2a_hex(base64.b64decode(rsa_n)), 16)
     e = int(binascii.b2a_hex(base64.b64decode(rsa_e)), 16)
     return rsa.PublicKey(n, e)
Esempio n. 11
0
import socket
import rsa
from classes import clients

server_pubkey = rsa.PublicKey(
    int('''198710545728042830253499635501841987346
1541179669992532483914203150651172352438303321820385084467843592008121891579
5243744623899403024070535464953327207745707280816151149112673681159838326052
6120182724129912002381565130386206485103768727500904675351361585101139635132
2694293183381935261237401868155491912800800250116691185718942925849159449871
9439799387750137469926299277454098469247496858839507530776827365123736406053
0251116770748039430110821074732249014709370741208212747951559547340860480573
4379799091495243224771586683345998659539518564067592233261543537102023917893
9096433733507311626064586608627154087661325313'''.replace('\n', '')), 65537)

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 65438  # The port used by the server

# client_crypto = cryptography(server_pubkey = server_pubkey)
# client_socket = socket()

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    print('hello')
    client_socket = clients(conn=s, server_pubkey=server_pubkey)
    client_socket.send_session_key()
    # print(client_socket.base64_encode(client_socket.session_key), '\n\n')
    # msg = input('enter \n')
    # print('before from loop')
    #
    # # client_socket.send_file('test.txt')
Esempio n. 12
0
sessionKey = rsaInfo[4]

if updateType == 1:
    email = input('Email: ')
elif updateType == 2:
    email = currEmail
    if currEmail is None:
        print('current mail is None')
        exit()
else:
    print(f'Not support updateType: {updateType}')
    exit()
pw = ''
message = (chr(len(sessionKey)) + sessionKey + chr(len(email)) + email +
           chr(len(pw)) + pw).encode('utf-8')
pub_key = rsa.PublicKey(int(nvalue, 16), int(evalue, 16))
crypto = binascii.hexlify(rsa.encrypt(message, pub_key)).decode()

if updateType == 2:
    res = cl.removeIdentifier(session, keynm, crypto)
else:
    if currEmail is None:
        res = cl.setIdentifier(session, keynm, crypto)
    else:
        res = cl.updateIdentifier(session, keynm, crypto)
    print(res)
    responseType = res[2]
    confirmationVerifier = res[3]

    pincode = input('Pincode: ')
    res = cl.confirmIdentifier(session, pincode)
Esempio n. 13
0
 def encrypt(self, message):
     ee = int(self.e, 16)
     nn = int(self.n, 16)
     rsa_pubkey = rsa.PublicKey(e=ee, n=nn)
     crypto = self._encrypt(message.encode(), rsa_pubkey)
     return crypto.hex()
Esempio n. 14
0
# sinaSSOController.preloginCallBack({
# 	"retcode":0,
# 	"servertime":1369217685,
# 	"pcid":"yf-4d246eb08235f2151d0e8296b5352981d4d6",
# 	"nonce":"2HX83A",
# 	"pubkey":"EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D245A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD3993CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443",
# 	"rsakv":"1330428213","exectime":1})

username = raw_input('username:'******'password:'******'\t' + str(nonce) + '\n' + str(
    password)  #拼接明文js加密文件中得到
passwd = rsa.encrypt(message, key)  #加密
passwd = binascii.b2a_hex(passwd)  #将加密信息转换为16进制。

print username
print passwd


def login():
    loginurl = 'http://login.sina.com.cn/sso/login.php'
    # http://login.sina.com.cn/sso/login.php?
    # entry=weibo&
    # gateway=1&
    # from=&
Esempio n. 15
0
 def pubkey(self) -> rsa.PublicKey:
     return rsa.PublicKey(self.n, self.e)
Esempio n. 16
0
 def encrypt_passwd(self, pubkey, serverTime, nonce):
     rsaPublickey = int(pubkey, 16)
     key = rsa.PublicKey(rsaPublickey, 65537)
     message = str(serverTime) + '\t' + str(nonce) + \
         '\n' + str(self.password)
     self.encodedPassWord = binascii.b2a_hex(rsa.encrypt(message, key))
Esempio n. 17
0
import rsa
import json
import client
import sys
import random

#test keys are piped into the client test; each i is a key.
for i in sys.stdin:
    k = json.loads(i)
    pkey = rsa.PrivateKey(k["n"], k["e"], k["d"], k["p"], k["q"])
    key = rsa.PublicKey(k["n"], k["e"])
    inputs = [{"key": {"n": key.n, "e": key.e}}]
    transaction = client.create_transaction(
        inputs, 1, 1, [],
        1)  #using dummy arguments for n, v, outputs, and timeout
    blinds = client.create_transaction_blinds(transaction)
    sig = client.sign_blind(pkey, blinds[0]["blind"])  # blind signature
    csig = sig - 1  # corrupted signature.
    print("signature: " + str(sig))
    print(client.verify_blind_signature(
        transaction, key, blinds[0]["r"],
        sig))  #verifies that it accepts proper signatures.
    print(not client.verify_blind_signature(
        transaction, key, blinds[0]["r"],
        csig))  #verifies that it rejects improper signatures.
Esempio n. 18
0
    def login(self,
              _id,
              passwd,
              certificate=None,
              systemName=None,
              phoneName=None,
              keepLoggedIn=True):
        systemName = self.server.SYSTEM_NAME
        if self.server.EMAIL_REGEX.match(_id):
            self.provider = IdentityProvider.LINE  # LINE
        else:
            self.provider = IdentityProvider.NAVER_KR  # NAVER

        if phoneName is None:
            phoneName = self.server.APP_NAME
        self.server.setHeaders('X-Line-Application', phoneName)
        self._client = LineSession(
            self.server.LINE_HOST_DOMAIN, self.server.Headers,
            self.server.LINE_AUTH_QUERY_PATH).Talk(isopen=False)

        rsaKey = self._client.getRSAKeyInfo(self.provider)

        message = (chr(len(rsaKey.sessionKey)) + rsaKey.sessionKey +
                   chr(len(_id)) + _id + chr(len(passwd)) +
                   passwd).encode('utf-8')
        pub_key = rsa.PublicKey(int(rsaKey.nvalue, 16), int(rsaKey.evalue, 16))
        try:
            # Works with python 2.7
            crypto = rsa.encrypt(message, pub_key).encode('hex')
        except:
            # Works with python 3.x
            crypto = rsa.encrypt(message, pub_key).hex()

        try:
            with open(_id + '.crt', 'r') as f:
                self.certificate = f.read()
        except:
            if certificate is not None:
                self.certificate = certificate
                if os.path.exists(certificate):
                    with open(certificate, 'r') as f:
                        self.certificate = f.read()

        result = self._client.loginWithIdentityCredentialForCertificate(
            self.provider, rsaKey.keynm, crypto, keepLoggedIn,
            self.server.IP_ADDR, systemName, self.certificate)

        if result.type == LoginResultType.REQUIRE_DEVICE_CONFIRM:
            self.callback.PinVerified(result.pinCode)

            self.server.setHeaders('X-Line-Access', result.verifier)
            getAccessKey = self.server.getJson(self.server.parseUrl(
                self.server.LINE_CERTIFICATE_PATH),
                                               allowHeader=True)

            self._client = LineSession(
                self.server.LINE_HOST_DOMAIN, self.server.Headers,
                self.server.LINE_AUTH_QUERY_PATH).Talk(isopen=False)
            try:
                result = self._client.loginWithVerifierForCertificate(
                    getAccessKey['result']['verifier'])
            except:
                raise Exception("Login failed")

            if result.type == LoginResultType.SUCCESS:
                if result.certificate is not None:
                    with open(_id + '.crt', 'w') as f:
                        f.write(result.certificate)
                    self.certificate = result.certificate
                if result.authToken is not None:
                    self.tokenLogin(result.authToken, phoneName)
                else:
                    return False
            else:
                raise Exception("Login failed")

        elif result.type == LoginResultType.REQUIRE_QRCODE:
            self.qrLogin(keepLoggedIn, systemName, phoneName)
            pass

        elif result.type == LoginResultType.SUCCESS:
            self.certificate = result.certificate
            self.tokenLogin(result.authToken, phoneName)
Esempio n. 19
0
    def login(self, nick, pwd):
        prelogin_url = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=%s&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.15)&_=1400822309846' % nick
        loginfo = self.get_text(prelogin_url)
        ## following info will be used on login request as post datas
        servertime = re.findall('"servertime":(.*?),', loginfo)[0]
        pubkey = re.findall('"pubkey":"(.*?)",', loginfo)[0]
        rsakv = re.findall('"rsakv":"(.*?)",', loginfo)[0]
        nonce = re.findall('"nonce":"(.*?)",', loginfo)[0]

        su = base64.b64encode(
            bytes(urllib.request.quote(nick), encoding='utf-8'))
        rsaPublickey = int(pubkey, 16)
        key = rsa.PublicKey(rsaPublickey, 65537)

        message = bytes(str(servertime) + '\t' + str(nonce) + '\n' + str(pwd),
                        encoding='utf-8')
        sp = binascii.b2a_hex(rsa.encrypt(message, key))

        datas = {
            'entry':
            'weibo',
            'gateway':
            1,
            'from':
            '',
            'savestate':
            7,
            'useticket':
            1,
            'pagerefer':
            'http://login.sina.com.cn/sso/logout.php?entry=miniblog&r=http%3A%2F%2Fweibo.com%2Flogout.php%3Fbackurl%3D',
            'vsnf':
            1,
            'su':
            su,
            'service':
            'miniblog',
            'servertime':
            servertime,
            'nonce':
            nonce,
            'pwencode':
            'rsa2',
            'rsakv':
            rsakv,
            'sp':
            sp,
            'sr':
            '1680*1050',
            'encoding':
            'UTF-8',
            'prelt':
            961,
            'url':
            'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack'
        }
        res = self._session.post(
            'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)',
            data=datas)
        urll = re.findall("location.replace\(\'(.*?)\'\);", res.text)[0]
        self.get_text(urll)
Esempio n. 20
0
    def from_taobao(self, username, password):
        """淘宝帐号登录, username 为淘宝帐号, password为支付宝帐号
        注意不要和 alipay 帐号弄混了
        """

        captcha = ''
        url = 'https://passport.alipay.com/mini_login.htm?lang=&appName=xiami&appEntrance=taobao&cssLink=&styleType=vertical&bizParams=&notLoadSsoView=&notKeepLogin=&rnd=0.6477347570091512?lang=zh_cn&appName=xiami&appEntrance=taobao&cssLink=https%3A%2F%2Fh.alipayobjects.com%2Fstatic%2Fapplogin%2Fassets%2Flogin%2Fmini-login-form-min.css%3Fv%3D20140402&styleType=vertical&bizParams=&notLoadSsoView=true&notKeepLogin=true&rnd=0.9090916193090379'
        bs = BeautifulSoup(self._safe_get(url).content)

        check_url = 'https://passport.alipay.com/newlogin/account/check.do?fromSite=0'
        check_data = {
            'loginId': username,
            'appName': 'xiami',
            'appEntrance': 'taobao',
        }

        ret = self._safe_post(check_url, check_data)
        print ret.content

        rsa_n = int(bs.find('input', {
            "id": "fm-modulus"
        }).get('value'),
                    base=16)
        rsa_e = 65537

        public_key = rsa.PublicKey(rsa_n, rsa_e)
        encrypted_password = rsa.encrypt(password, public_key).encode('hex')

        while True:
            data = {
                'loginId': username,
                #'password': password,
                'password2': encrypted_password,
                'appName': 'xiami',
                'appEntrance': 'taobao',
                'hsid': bs.find('input', {'name': 'hsid'})['value'],
                'cid': bs.find('input', {'name': 'cid'})['value'],
                'rdsToken': bs.find('input', {'name': 'rdsToken'})['value'],
                'umidToken': bs.find('input', {'name': 'umidToken'})['value'],
                '_csrf_token': bs.find('input',
                                       {'name': '_csrf_token'})['value'],
                'checkCode': captcha
            }
            logger.debug('taobao post data' + str(data))

            ret = self._safe_post(
                'https://passport.alipay.com/newlogin/login.do?fromSite=0',
                headers={
                    'Referer': 'https://passport.alipay.com/mini_login.htm',
                    'User-agent': 'Mozilla/5.0'
                },
                data=data).content

            jdata = json.loads(ret)

            # 出错处理
            if jdata['content']['status'] == -1:
                logger.debug('error,' + str(jdata))
                if jdata['content'].get('data', {}).get('checkCodeLink'):
                    session_id = bs.find('input', {'name': 'cid'})['value']
                    captcha_url = jdata['content']['data']['checkCodeLink']
                    logger.debug('captcha url:' + captcha_url)
                    captcha = self.captcha_func(
                        self._safe_get(captcha_url,
                                       headers={
                                           'User-agent': 'Mozilla/5.0'
                                       }).content)
                    continue  # 重新提交一次
                else:
                    if jdata['content']['data'].get(
                            'titleMsg', ''
                    ) == u'\u9a8c\u8bc1\u7801\u9519\u8bef\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165':
                        print 'Wrong captcha'
                        captcha = ''
                        continue
                    raise Xiamiexp('unknown')

            # 登录成功, 将 st 传递给虾米
            st = jdata['content']['data']['st']
            logger.debug('st=' + st)

            ret = self._safe_get(
                'http://www.xiami.com/accounts/back?st=' + st,
                headers={
                    'Referer': 'https://passport.alipay.com/mini_login.htm',
                    'User-agent': 'Mozilla/5.0'
                })

            # 由此登录完成
            return
Esempio n. 21
0
def encrypt(message: str) -> str:
    pub_key = rsa.PublicKey(
        *map(int,
             readFile(os.path.join("server", "key.pub")).split()))
    hashed = str(rsa.encrypt(bytes(message, "utf-8"), pub_key).hex())
    return hashed
Esempio n. 22
0
    def serverThread(self, conn, addr):
        global messagesToSend
        global nodes
        global maxNodes
        global maxNodesSvr
        global numNodes
        global foundNodes
        global ourId
        global ourKey
        global initialisationDone
        global private_key
        global fernetKey
        global onionaddr
        global type
        debug("[I] (ServerThread): Received connection from: " + str(addr))
        conn.setblocking(0)
        randomwait = random.randint(1, serverRandomWait)
        start = time.time()
        received = b''
        counter = 1
        ip = addr[0]
        while (True):
            try:
                #time.sleep(0.05)
                ready = select.select([conn], [], [], 1.0)
                if ready[0]:
                    data = recvall(conn)
                    if len(data) == 0: continue
                    try:
                        dataDecoded = data.decode()
                    except:
                        debug("[E] Error decoding packet")
                    else:
                        if dataDecoded.startswith(
                                '§REQUEST-IDENTITY§') and dataDecoded.count(
                                    '§') == 2:
                            debug('[I] ' + addr[0] +
                                  ' is requesting an identity from us.')
                            id = genRandomString(16)
                            key = genRandomString(32)
                            msg = id + '-' + key
                            nodes[id] = key
                            if nodeIps.get(ip) != ip and type == "SERVER":
                                nodeIps[id] = ip
                                broadcastUpdate(id)
                            else:
                                nodeIps[id] = ip
                            f = open("ts_keys.txt", "a")
                            f.write(id + '§' + key + '\n')
                            f.close()
                            addToMsgsSend(ip, msg.encode(), "")
                        elif dataDecoded.startswith(
                                '§HELLO§') and dataDecoded.count('§') == 3:
                            processedData = remove_prefix(
                                dataDecoded, '§HELLO§')
                            ip = processedData.split('§')[0]
                            id = processedData.split('§')[1]
                            debug('[I] ' + 'Node, ' + id +
                                  ' said hello from ' + ip)
                            nodeIps[id] = ip
                            backupNodesToFile(id, ip, 'ts_ids.txt')
                        elif dataDecoded.startswith(
                                '§GIVE-SVR-VARS§') and dataDecoded.count(
                                    '§') == 2:
                            msg = '§HELLO-SERVER§' + str(
                                len(nodes)) + '§' + str(maxNodes)
                            addToMsgsSend(ip, msg.encode(), "")
                        elif dataDecoded.startswith(
                                '§HELLO-IP§') and dataDecoded.count('§') == 2:
                            ip = dataDecoded.split('§')[2]
                            debug('[I] ' + 'A node said hello from ' + ip)
                        elif dataDecoded.startswith(
                                '§HELLO-SERVER§') and dataDecoded.count(
                                    '§') == 3:
                            numNodes = int(
                                remove_prefix(dataDecoded,
                                              '§HELLO-SERVER§').split('§')[0])
                            maxNodesSvr = int(
                                remove_prefix(dataDecoded,
                                              '§HELLO-SERVER§').split('§')[1])
                            initialisationDone = True
                        elif dataDecoded.startswith(
                                '§DO-YOU-KNOW§') and dataDecoded.count(
                                    '§') == 2:
                            nodeId = remove_prefix(dataDecoded,
                                                   '§DO-YOU-KNOW§')
                            if nodeId in list(nodeIps.keys()):
                                msg = '§FOUND-THEM§' + nodeIps[
                                    nodeId] + '§' + nodeId
                            else:
                                msg = '§COULDNT-FIND-NODE§'
                            addToMsgsSend(ip, msg.encode(), "")
                        elif dataDecoded.startswith(
                                '§FOUND-THEM§') and dataDecoded.count(
                                    '§') == 3:
                            foundNodes[remove_prefix(
                                dataDecoded,
                                '§FOUND-THEM§').split('§')[1]] = remove_prefix(
                                    dataDecoded, '§FOUND-THEM§').split('§')[0]
                        elif dataDecoded.startswith('§REQUEST-CLUSTER-NODES§'
                                                    ) and dataDecoded.count(
                                                        '§') == 3:
                            debug('[I] ' + ip +
                                  ' is requesting sacrfices to connect to.')
                            clusterDepth = math.floor(len(nodes) / maxNodes)
                            randomNodes = getRandomNodes(
                                dataDecoded.split('§')[2],
                                list(nodeIps.keys()).copy(), clusterDepth)
                            msg = '§NODES§' + randomNodes
                            addToMsgsSend(ip, msg.encode(), "")
                        elif dataDecoded.count('§') == 0 and dataDecoded.count(
                                '-') == 1:
                            ourId = dataDecoded.split('-')[0]
                            ourKey = dataDecoded.split('-')[1]
                            debug('[I] ' +
                                  "We have received an idenity from " + ip +
                                  " id:" + dataDecoded.split('-')[0] +
                                  " key:" + dataDecoded.split('-')[1])
                        elif dataDecoded.startswith('§NODES§'):
                            processed = remove_prefix(dataDecoded, '§NODES§')
                            receivedNodes = list(
                                filter(
                                    None,
                                    processed.split('§§')[0].split('-') +
                                    processed.split('§§')[1].split('-')))
                            for x in receivedNodes:  #X Gon' Give It to Ya
                                nodeIps[x.split('§')[0]] = x.split('§')[1]
                            debug('[I] ' + "We have received " +
                                  str(len(receivedNodes)) + " nodes from " +
                                  addr[0])
                        elif dataDecoded.startswith('§GIVE-FERNET-KEY§'):
                            rqstmsg = '§HELLO§' + onionaddr + '§' + ourId
                            addToMsgsSend(ip, rqstmsg.encode(), "")
                            fernetKey = Fernet.generate_key()
                            fernetKeys[id] = fernetKey
                            pub_key = remove_prefix(
                                dataDecoded, '§GIVE-FERNET-KEY§').split(" ")
                            pub_key_2 = rsa.PublicKey(n=int(pub_key[0]),
                                                      e=int(pub_key[1]))
                            msgAppend = '§HERE-FERNET-KEY§'
                            msg = msgAppend.encode() + base64.b64encode(
                                rsa.encrypt(fernetKey, pub_key_2))
                            addToMsgsSend(ip, msg, "")
                        elif dataDecoded.startswith('§HERE-FERNET-KEY§'):
                            msg = remove_prefix(dataDecoded,
                                                '§HERE-FERNET-KEY§').encode()
                            fernetKey = rsa.decrypt(base64.b64decode(msg),
                                                    private_key)
                            fernetKeys[id] = fernetKey
                        elif dataDecoded.startswith('§MSG§'):
                            msg = remove_prefix(dataDecoded, '§MSG§')
                            debug('[I] ' + ip + ' ' + msg)
                            addToMsgsRecv(ip, msg, id)
                        else:
                            debug("[I] <RECEIVED> " + dataDecoded)
                        messages.append(dataDecoded)

            except:
                conn.close()
                debug('[I] exiting...')
                raise
Esempio n. 23
0
    def loginWithCredential(self, _id, passwd, certificate=None, systemName=None, appName=None, keepLoggedIn=True):
        if systemName is None:
            systemName=self.server.SYSTEM_NAME
        if self.server.EMAIL_REGEX.match(_id):
            self.provider = IdentityProvider.LINE       # LINE
        else:
            self.provider = IdentityProvider.NAVER_KR   # NAVER
        
        if appName is None:
            appName=self.server.APP_NAME
        self.server.setHeaders('X-Line-Application', appName)
        self.tauth = Session(self.server.LINE_HOST_DOMAIN, self.server.Headers, self.server.LINE_AUTH_QUERY_PATH).Talk(isopen=False)

        rsaKey = self.tauth.getRSAKeyInfo(self.provider)
        
        message = (chr(len(rsaKey.sessionKey)) + rsaKey.sessionKey +
                   chr(len(_id)) + _id +
                   chr(len(passwd)) + passwd).encode('utf-8')
        pub_key = rsa.PublicKey(int(rsaKey.nvalue, 16), int(rsaKey.evalue, 16))
        crypto = rsa.encrypt(message, pub_key).hex()

        try:
            with open(_id + '.crt', 'r') as f:
                self.certificate = f.read()
        except:
            if certificate is not None:
                self.certificate = certificate
                if os.path.exists(certificate):
                    with open(certificate, 'r') as f:
                        self.certificate = f.read()

        self.auth = Session(self.server.LINE_HOST_DOMAIN, self.server.Headers, self.server.LINE_LOGIN_QUERY_PATH).Auth(isopen=False)

        lReq = self.__loginRequest('0', {
            'identityProvider': self.provider,
            'identifier': rsaKey.keynm,
            'password': crypto,
            'keepLoggedIn': keepLoggedIn,
            'accessLocation': self.server.IP_ADDR,
            'systemName': systemName,
            'certificate': self.certificate,
            'e2eeVersion': 0
        })

        result = self.auth.loginZ(lReq)
        
        if result.type == LoginResultType.REQUIRE_DEVICE_CONFIRM:
            self.callback.PinVerified(result.pinCode)

            self.server.setHeaders('X-Line-Access', result.verifier)
            getAccessKey = self.server.getJson(self.server.parseUrl(self.server.LINE_CERTIFICATE_PATH), allowHeader=True)

            self.auth = Session(self.server.LINE_HOST_DOMAIN, self.server.Headers, self.server.LINE_LOGIN_QUERY_PATH).Auth(isopen=False)

            try:
                lReq = self.__loginRequest('1', {
                    'keepLoggedIn': keepLoggedIn,
                    'verifier': getAccessKey['result']['verifier'],
                    'e2eeVersion': 0
                })
                result = self.auth.loginZ(lReq)
            except:
                raise Exception('Login Gagal')
            
            if result.type == LoginResultType.SUCCESS:
                if result.certificate is not None:
                    with open(_id + '.crt', 'w') as f:
                        f.write(result.certificate)
                    self.certificate = result.certificate
                if result.authToken is not None:
                    self.loginWithAuthToken(result.authToken, appName)
                else:
                    return False
            else:
                raise Exception('Login Gagal')

        elif result.type == LoginResultType.REQUIRE_QRCODE:
            self.loginWithQrCode(keepLoggedIn, systemName, appName)
            pass

        elif result.type == LoginResultType.SUCCESS:
            self.certificate = result.certificate
            self.loginWithAuthToken(result.authToken, appName)
Esempio n. 24
0
print("[+] Client Running ")
HOST = "127.0.0.1"
PORT = 8888
SECMODE = True

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
except ConnectionError:
    print('Could Not Connect !')
    exit(-1)

if SECMODE:
    pubkey = s.recv(2000)
    n = int(pubkey.decode())
    pubKey = rsa.PublicKey(n, 65537)
    print("Recieved Public Key ", pubkey)
    key = os.urandom(32)
    print("Session key generated ", key)
    encrypted_aes_key = rsa.encrypt(key, pubKey)
    print("Encrypted session key ", encrypted_aes_key)
    s.send(encrypted_aes_key)
    hashed = hashlib.sha256(key).digest()
    aes = pyaes.AESModeOfOperationCBC(hashed)


def process_bytes(bytess):
    ret = []
    while (len(bytess) >= 16):
        byts = bytess[:16]
        ret.append(byts)
Esempio n. 25
0
# Echo client program
import socket
import rsa

flag = True
serv_key = rsa.PublicKey(0, 0)
HOST = 'awsomkiller'  # The remote host
PORT = 50000  # The same port as used by the server
msg = input("Enter command (type exit to exit):")
byte = msg.encode('utf-8')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'requestkey')
    recv = s.recv(1024)
    serv_key = serv_key.load_pkcs1(recv)
    while flag:
        crypto = rsa.encrypt(byte, serv_key)
        s.sendall(crypto)
        data = s.recv(1024)
        output = data.decode('utf-8')
        print(output)
        msg = input("Enter command (type exit to exit) :")
        if msg == 'exit':
            flag = False
        byte = msg.encode('utf-8')
Esempio n. 26
0
import os, pickle, re, sys, rsa
from common.safeprint import safeprint
from common.call import parse
from multiprocessing import Lock
from hashlib import sha256

global bountyList
global bountyLock
global bountyPath
global masterKey
bountyList = []
bountyLock = Lock()
bounty_path = "data" + os.sep + "bounties.pickle"
masterKey = rsa.PublicKey(
    729718364227516960054295457142870147346925650464049779453646035926050199850326176647776838438938636661228002448973439854960184665555127389717151244506525402822373346832616397761206559623788599190346863336276264188776227828388404545963626831368271897836511731886293682431585966696566956586753957061875750759629551953550884681595197232292996000727346222730268449333005244786147077213736904023547731667408727418270821683767049274149406495083497549800959104387705136505347356831591749348784075618969053560235935338903984498115314670847476855038220451066460680035126053662454299081605363723838286302366301689234068690059316763799353143310559458946931318030844074363736788753178540199530225135107033856254305990087025967311915085112106420563306477842216888317797721574213850513617438213884040008525804176775715666690615899232712962058014027424402924843894781126276571499753462902008866715676378206701092204594546847042695125234724069900669714879723998617459025957963035684337989448663829900190832766576886449445998282639604992499686311883781123909372514474812566745325833006488779304055744191085394500902876859106482982701389204359219619381519269665200901406370105464312892270576240630264902441599619105421899943737252817890677315597882826571452667291297867328746814757255859312415632041433394104078891786311847142328363538513641680341734265250695496776566453276314580141676284207452110911626332891796798261026918947965108108877705758484536741616285552644326769470282221294071586139149996954364049943466039880711404230731628646248873232006643911012626023072154931894232739379505522865390152470432852547479160421591889324386660716759305915846468178029427406274264127584562536435501990522185363177223199949369223173966625384842438760255385301454341488784995219962112304732703967034969073210830294157329183542340361222144325778056660904508019431390791813146428095240192923570820580206747811269863474545538133775066351370475810177599879939522958590455452068291841209413729663053749796655380139821219686135783575616500844500412856724119371178526348549811013160430296131484346160922951511938309653435559070497873479498675961624001852506934102504791910222791868089298784254619281037009019775386472113074556466631655138811963898397216625947305254734110750776827226524243761296420962180234223676323640815767978717570666035083384226389557220885498260773635973720746044553716885329739097031530119234094297080532925101344078010970180292718887769653856948048674677603855338372966228989,
    65537)


def getUTC():
    from calendar import timegm
    from time import gmtime
    return timegm(gmtime())


class Bounty(object):
    """An object representation of a Bounty
    Parts:
    ip         -- The ip address of the requesting node
    btc        -- The Bitcoin address of the requesting party
    reward     -- The reward amount in satoshis to be given over 24 hours
                   (x | x == 0 or 1440 <= x <= 100000000) (1440 is 1 satoshi/minute)
Esempio n. 27
0
import rsa

n = 66473473500165594946611690873482355823120606837537154371392262259669981906291
e = 65537
PUBKEY = rsa.PublicKey(n, e)

def encrypt(s, pubkey):
	return rsa.encrypt( s, pubkey )

if __name__ == '__main__':
	with open('flag.txt', 'r') as fp:
		flag = fp.read()
	
	with open('flag.enc', 'w') as fp:
		fp.write( encrypt(flag, PUBKEY) )
Esempio n. 28
0
def sina_login(username, password):
    """
    it will return a json like this
    {'crossDomainUrlList': ['https://passport.weibo.com/wbsso/login?ticket=xxxxxxxxxxx', 'https://passport.97973.com/sso/crossdomai
    n?action=login&savestate=xxxxxx', 'https://passport.weibo.cn/sso/crossdomain?action=login&savestate=1'], 'retcode': '0', 'nick': 'your nick name', 'uid': 'your uid'}
    retcode: 0 means login success
    :param username: your username/phone/email
    :param password: your password
    :return:sina login json
    """
    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
        "Accept":
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Referer": "http://my.sina.com.cn/profile/logined",
        # "Accept-Encoding":"gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        # "Cookie": "U_TRS1=00000084.9bed62e5.5b72e391.3af21d2e; SCF=AjEDrkrhvxII4wJgdIV9siNQUgJlzg1gCS6LX_Ez6o0W1cSlWagP_ThVB_NwZOFToQvMbCX9hsIs2AxCepx3Sl4.; SINAGLOBAL=172.16.118.83_1534345349.885837; Apache=172.16.118.83_1534345349.885840; SSO-DBL=1d143a736fdf93d35dc1b24d4482f559; U_TRS2=00000019.45af8203.5b7454e9.728b1791; UOR=my.sina.com.cn,www.sina.com.cn,; ULV=1534350579211:1:1:1:172.16.118.83_1534345349.885840:; SGUID=1534350580654_19785330; SUBP=0033WrSXqPxfM72wWs9jqgMF55529P9D9WWKg4cDuqqTVV3F8DJe0slF5JpV2sSQ9g8Xeg4rBh2ceE4odcXt; lxlrttp=1532434326; SUB=_2AkMsKNvLdcPxrAVQnfodxG3iZIlH-jyf_bI9An7tJhMyAhh87gcGqSVutBF-XLPEJgbxOuOj0nCYCFiZeP8D0XI0"
    }

    q = {
        "entry": "account",
        "_": int(time() * 1000),
        "callback": "pluginSSOController.preloginCallBack",
        "su": b64encode(username.encode("utf-8")),
        "rsakt": "mod",
        "checkpin": "1",
        "client": "ssologin.js(v1.4.19)",
    }
    eq = parse.urlencode(q).encode("utf-8")
    u = request.Request("https://login.sina.com.cn/sso/prelogin.php?" +
                        eq.decode("utf-8"),
                        headers=headers,
                        method="GET")
    r = request.urlopen(u)
    rb = r.read()
    b = json.loads(rb.decode("utf-8")[37:-1])
    pkey = rsa.PublicKey(int(b['pubkey'], 16), 65537)
    msg = str(b['servertime']) + "\t" + b["nonce"] + "\n" + password
    rmsg = rsa.encrypt(msg.encode("utf-8"), pkey)
    sp = binascii.b2a_hex(rmsg)
    data = {
        "entry": "account",
        "gateway": "1",
        "from": "",
        "savestate": "30",
        "qrcode_flag": "true",
        "useticket": "0",
        "pagerefer": "http://my.sina.com.cn/profile/logined",
        "vsnf": "1",
        "su": b64encode(username.encode("utf-8")),
        "sp": sp,
        "service": "sso",
        "servertime": b["servertime"],
        "nonce": b["nonce"],
        "pwencode": "rsa2",
        "rsakv": b["rsakv"],
        "sr": "1366*768",
        "encoding": "UTF-8",
        "cdult": "3",
        "domain": "sina.com.cn",
        "prelt": "68",
        "returntype": "TEXT",
    }
    edata = parse.urlencode(data).encode("utf-8")
    u = request.Request(
        "https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.19)&_="
        + str(time() * 1000),
        data=edata,
        headers=headers,
        method="POST")
    r = request.urlopen(u)
    dr = r.read().decode("utf-8")
    jr = json.loads(dr)
    return jr
Esempio n. 29
0
def rsa_encrypt(s, pubkey_str):
    key = _str2key(pubkey_str)
    modulus = int(key[0], 16)
    exponent = int(key[1], 16)
    pubkey = rsa.PublicKey(modulus, exponent)
    return base64.b64encode(rsa.encrypt(s.encode(), pubkey)).decode()
Esempio n. 30
0
	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