def clientUDP(): HOST = '127.0.0.1' PORT = 5000 udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) dest = (HOST, PORT) print 'Para sair use CTRL+X\n' ##abro o arquivo com a chave arq = open('chavesSafirePub.txt','r') ##carrego a chave txt = '' for linha in arq: txt = txt + linha arq.close() #decodifico para o formato expoente e modulo pub = rsa.PublicKey.load_pkcs1(txt, format='PEM') msg = raw_input() #cifro a msg msgc = rsa.encrypt(msg,pub) while msg <> '\x18': msgc = rsa.encrypt(msg,pub) udp.sendto(msgc, dest) udp.close()
def keys(this): public_name = 'public.txt' private_name = 'private.txt' try: with open(public_name,'r') as f: pubkey = rsa.PublicKey.load_pkcs1(f.read()) with open(private_name,'r') as f: privkey = rsa.PrivateKey.load_pkcs1(f.read()) except: print 'generic keys...' pubkey, privkey = rsa.newkeys(2048, poolsize=2) #2 core with open(public_name,'w') as f: f.write(pubkey.save_pkcs1()) with open(private_name,'w') as f: f.write(privkey.save_pkcs1()) this.pubkey = pubkey this.privkey = privkey # поток выполнил полезную работу, теперь страдаем фигнёй # test 1 text1 =''.join(random.choice(string.ascii_uppercase +\ string.ascii_lowercase + string.digits) for x in range(16)) text2 = rsa.encrypt(text1, this.static_public_key) text3 = rsa.decrypt(text2, this.static_private_key) if text1 != text3: print 'FATAL ERROR: fail test 1' # test 2 text1 =''.join(random.choice(string.ascii_uppercase +\ string.ascii_lowercase + string.digits) for x in range(16)) text2 = rsa.encrypt(text1, pubkey) text3 = rsa.decrypt(text2, privkey) if text1 != text3: print 'ERROR: fail test 2'
def s_encrypt_response(auth_token, key, token, profile): payload = bytearray() append_packet(payload, bnum, 1, 1) shared_secret = '' # generate shared secret while len(shared_secret) < 16: rand_byte = random.randrange(0, 255) shared_secret += chr(rand_byte) # Store the shared secret. environment_info['secret_iv'] = shared_secret # auth with Mojang servers authenticate_client(auth_token, profile, key, shared_secret) # some RSA cypto mumbo jumbo pub = rsa.PublicKey.load_pkcs1_openssl_der(key) shared_ctext = rsa.encrypt(shared_secret, pub) token_ctext = rsa.encrypt(token, pub) append_packet(payload, varint, len(shared_ctext)) append_packet(payload, byte_array, shared_ctext) append_packet(payload, varint, len(token_ctext)) append_packet(payload, byte_array, token_ctext) return payload
def keys(this): name = 'keys.txt' #TODO зашифровать файл try: with open(name,'r') as f: data = f.read() pubkey = rsa.PublicKey.load_pkcs1(data) privkey = rsa.PrivateKey.load_pkcs1(data) except: print 'generic keys...' pubkey, privkey = rsa.newkeys(2048, poolsize=2) #2 core with open(name,'w') as f: f.write(pubkey.save_pkcs1()) f.write(privkey.save_pkcs1()) this.pubkey = pubkey this.privkey = privkey # поток выполнил полезную работу, теперь страдаем фигнёй # TODO chmod +r name # test 1 text1 =''.join(random.choice(string.ascii_uppercase +\ string.ascii_lowercase + string.digits) for x in range(16)) text2 = rsa.encrypt(text1, this.static_public_key) text3 = rsa.decrypt(text2, this.static_private_key) if text1 != text3: printf ('FATAL ERROR: fail test 1','red') # test 2 text1 =''.join(random.choice(string.ascii_uppercase +\ string.ascii_lowercase + string.digits) for x in range(16)) text2 = rsa.encrypt(text1, pubkey) text3 = rsa.decrypt(text2, privkey) if text1 != text3: printf ('ERROR: fail test 2','red')
def encrypt(self): cpb = self.pass_book.copy() self.pass_book = {} for key in cpb: if cpb[key] != (self.pub_key, self.priv_key): key_code = rsa.encrypt(key.encode('utf8'), self.pub_key) self.pass_book[key_code] = rsa.encrypt(cpb[key].encode('utf8'), self.pub_key) else: self.pass_book[key] = cpb[key] del cpb
def test_encrypt(self): with mock.patch("__builtin__.open") as opener: opener.side_effect = self.opener_fxn rsa.encrypt(["", "pub", "in", "enc1"]) self.files["in"][0].seek(0) rsa.encrypt(["", "priv", "in", "enc2"]) enc1 = cPickle.loads(self.files["enc1"][0].getvalue()) enc2 = cPickle.loads(self.files["enc2"][0].getvalue()) good = cPickle.loads(self.files["good"][0].getvalue()) self.assertEquals(enc1, good) self.assertEquals(enc2, good)
def encrypt(data, urlsafe=False): try: pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(RSA_1024_PUB_PEM) #pubkey = rsa.PrivateKey.load_pkcs1(RSA_1024_PUB_PEM) if urlsafe: return base64.urlsafe_b64encode(rsa.encrypt(data, pubkey)) else: return base64.b64encode(rsa.encrypt(data, pubkey)) except Exception as e: print 'encrypt error' print e return None
def GetCookie(self): main_url = self.main_url image_url = self.image_url login_url = self.login_url #path = self.base+self.filename header = self.header response,content = h.request(main_url,headers = header) set_cookie = response['set-cookie'] cookie = set_cookie.replace(' Path=/,','').replace('; path=/','') print(cookie) #print content father = re.findall("doSubmit.+'",content) key = father[0].split("'")[1] #print key header['Cookie'] = cookie header['Cache-Control'] = 'max-age=0' response1,content1 = h.request(image_url,headers = header) im = Image.open(StringIO(content1)) #im.save(path,'JPEG') #return cookie randnum = self.ImageToCode(im) print randnum if randnum and len(randnum) == 4: imageensure = self.image_url+'?randString='+str(randnum) header = self.header header['Cookie'] = cookie response,content = h.request(imageensure,headers = header) if content == 'false': return 'Identifying code distinguished fail!' else: rsapubkey = int(key,16) pubkey = rsa.PublicKey(rsapubkey,65537) uname = binascii.b2a_hex(rsa.encrypt(self.uname,pubkey)) passwd = binascii.b2a_hex(rsa.encrypt(self.passwd,pubkey)) header = self.header header['Cookie'] = cookie data = {'loginId':self.uname, \ '_loginId':uname, \ 'upassword':self.passwd, \ '_upassword':passwd, \ 'randnumber':randnum} header['Cache-Control'] = 'max-age=0' header['Content-Type'] = 'application/x-www-form-urlencode' header['Referer'] = 'http://curriculum.hust.edu.cn/Main_index.jsp' data = urllib.urlencode(data) response,content = h.request(login_url,'POST',data,headers = header) print response print content
def get_pwd(password, servertime, nonce, pubkey): rsaPublickey = int(pubkey, 16) key = rsa.PublicKey(rsaPublickey, 65537) # 创建公钥 message = str(servertime) + "\t" + str(nonce) + "\n" + str(password) # 拼接明文加密文件中得到 passwd = rsa.encrypt(message, key) # 加密 passwd = binascii.b2a_hex(passwd) # 将加密信息转换为16进制。 return passwd
def get_pwd_rsa(pwd, servertime, nonce): weibo_rsa_n = 'EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D245A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD3993CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443' weibo_rsa_e = 65537 message = str(servertime) + '\t' + str(nonce) + '\n' + str(pwd) key = rsa.PublicKey(int(weibo_rsa_n, 16), weibo_rsa_e) encropy_pwd = rsa.encrypt(message, key) return binascii.b2a_hex(encropy_pwd)
def enc_rsa(self, data): N = 0xAF0DDDB4DE63C066808F08B441349AC0D34C57C499B89B2640FD357E5F4783BFA7B808AF199D48A37C67155D77F063DDC356EBF15157D97F5EB601EDC5A104FFFCC8895CF9E46A40304AE1C6E44D0BCC2359221D28F757F859FECCF07C13377EEC2BF6AC2CDD3D13078AB6DA289A236342599F07FFC1D3EF377D3181CE24C719 E = 3 pub_key = rsa.PublicKey(N, E) return rsa.encrypt(data, pub_key)
def __get_spwd(self): rsaPublickey = int(self.pubkey, 16) key = rsa.PublicKey(rsaPublickey, 65537) #创建公钥 message = self.servertime + '\t' + self.nonce + '\n' + self.password #拼接明文js加密文件中得到 passwd = rsa.encrypt(message, key) #加密 passwd = binascii.b2a_hex(passwd) #将加密信息转换为16进制。 return passwd
def getEncryption(self): puk = rsa.PublicKey(int( 'F20CE00BAE5361F8FA3AE9CEFA495362' 'FF7DA1BA628F64A347F0A8C012BF0B25' '4A30CD92ABFFE7A6EE0DC424CB6166F8' '819EFA5BCCB20EDFB4AD02E412CCF579' 'B1CA711D55B8B0B3AEB60153D5E0693A' '2A86F3167D7847A0CB8B00004716A909' '5D9BADC977CBB804DBDCBA6029A97108' '69A453F27DFDDF83C016D928B3CBF4C7', 16 ), 3) e = int(self.qq).to_bytes(8, 'big') o = hashlib.md5(self.pwd.encode()) r = bytes.fromhex(o.hexdigest()) p = hashlib.md5(r + e).hexdigest() a = binascii.b2a_hex(rsa.encrypt(r, puk)).decode() s = hex(len(a) // 2)[2:] l = binascii.hexlify(self.vcode.upper().encode()).decode() c = hex(len(l) // 2)[2:] c = '0' * (4 - len(c)) + c s = '0' * (4 - len(s)) + s salt = s + a + binascii.hexlify(e).decode() + c + l return base64.b64encode( tea.encrypt(bytes.fromhex(salt), bytes.fromhex(p)) ).decode().replace('/', '-').replace('+', '*').replace('=', '_')
def get_pwd(self, password, servertime, nonce, pubkey): rsaPublickey = int(pubkey, 16) key = rsa.PublicKey(rsaPublickey, 65537) message = str(servertime) + '\t' + str(nonce) + '\n' + str(password) passwd = rsa.encrypt(message, key) passwd = binascii.b2a_hex(passwd) return passwd
def getTEAPass(q, p, v): #RSA 公钥 pubkey = "F20CE00BAE5361F8FA3AE9CEFA495362FF7DA1BA628F64A347F0A8C012BF0B254A30CD92ABFFE7A6EE0DC424CB6166F8819EFA5BCCB20EDFB4AD02E412CCF579B1CA711D55B8B0B3AEB60153D5E0693A2A86F3167D7847A0CB8B00004716A9095D9BADC977CBB804DBDCBA6029A9710869A453F27DFDDF83C016D928B3CBF4C7" rsaPublickey = int(pubkey, 16) key = rsa.PublicKey(rsaPublickey, 3) #MD5 密码 p = md5.new(p).digest() #TEA 的KEY m = md5.new(p + ("%0.16X" % q).decode('hex')).digest() #RSA的加密结果 n = rsa.encrypt(p, key) #RSA 结果的长度 d = ("%0.4X" % len(n)).decode('hex') #RSA 加密结果 d += n #salt d += ("%0.16X" % q).decode('hex') #验证码长度 d += ("%0.4X" % len(v)).decode('hex') #验证码 d += v.upper() #TEA 加密并Base64编码 r = base64.b64encode(encrypt(d, m)) #对特殊字符进行替换 return r.replace('/', '-').replace('+', '*').replace('=', '_')
def encodePassword(pwd, time, nonce, pubkey): ''' ctxt = PyV8.JSContext() ctxt.enter() func = ctxt.eval(""" (function(password,servertime,nonce){ var o=8; var n=0; var hex_sha1=function(s){return A(p(z(s),s.length*o))}; var p=function(x,f){x[f>>5]|=0x80<<(24-f%32);x[((f+64>>9)<<4)+15]=f;var w=Array(80);var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;var e=-1009589776;for(var i=0;i<x.length;i+=16){var g=a;var h=b;var k=c;var l=d;var m=e;for(var j=0;j<80;j++){if(j<16)w[j]=x[i+j];else w[j]=v(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);var t=u(u(v(a,5),q(j,b,c,d)),u(u(e,w[j]),r(j)));e=d;d=c;c=v(b,30);b=a;a=t}a=u(a,g);b=u(b,h);c=u(c,k);d=u(d,l);e=u(e,m)}return Array(a,b,c,d,e)}; var q=function(t,b,c,d){if(t<20)return(b&c)|((~b)&d);if(t<40)return b^c^d;if(t<60)return(b&c)|(b&d)|(c&d);return b^c^d}; var r=function(t){return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514}; var u=function(x,y){var a=(x&0xFFFF)+(y&0xFFFF);var b=(x>>16)+(y>>16)+(a>>16);return(b<<16)|(a&0xFFFF)}; var v=function(a,b){return(a<<b)|(a>>>(32-b))}; var z=function(a){var b=Array();var c=(1<<o)-1;for(var i=0;i<a.length*o;i+=o)b[i>>5]|=(a.charCodeAt(i/o)&c)<<(24-i%32);return b}; var A=function(a){var b=n?"0123456789ABCDEF":"0123456789abcdef";var c="";for(var i=0;i<a.length*4;i++){c+=b.charAt((a[i>>2]>>((3-i%4)*8+4))&0xF)+b.charAt((a[i>>2]>>((3-i%4)*8))&0xF)}return c}; return hex_sha1(""+hex_sha1(hex_sha1(password))+servertime+nonce); }) """) return func(pwd,time,nonce) ''' rsaPublickey = int(pubkey, 16) key = rsa.PublicKey(rsaPublickey, 65537) message = str(time) + "\t" + str(nonce) + "\n" + str(pwd) passwd = rsa.encrypt(message, key) return binascii.b2a_hex(passwd)
def main(): (publicKey, privateKey) = rsa.newkeys(1024) pub = publicKey.save_pkcs1() pubfile = open("public.pem", "w+") pubfile.write(pub) pubfile.close() pri = privateKey.save_pkcs1() prifile = open("private.pem", "w+") prifile.write(pri) prifile.close() prifile = open("private.pem", "r") p = prifile.read() privateKey = rsa.PrivateKey.load_pkcs1(p) prifile.close() pubfile = open("public.pem", "r") p = pubfile.read() publicKey = rsa.PublicKey.load_pkcs1(p) pubfile.close() message = "lalalalal" secret = rsa.encrypt(message, publicKey) non_secret = rsa.decrypt(secret, privateKey) print non_secret signature = rsa.sign(message, privateKey, "SHA-1") rsa.verify("lalalalal", signature, publicKey)
def get_pwd(pwd): rsaPublicKey = int(pubkey, 16) key = rsa.PublicKey(rsaPublicKey, 65537) message = str(st) + '\t' + str(non) + '\n' + str(pwd) pwd_1 = rsa.encrypt(message, key) pwd_2 = binascii.b2a_hex(pwd_1) return pwd_2
def handleLogin(sock, listOfAccounts): status = False userAccount = getAccountInfo(sock); returnStatus = FAIL userKey = "" anyUserPubKey = "" print "User at socket {0} is trying to log in".format(sock) for user in listOfAccounts: status, userKey = user.verifyAccount(userAccount) anyUserPubKey = user.getPubKey() if status: user.setSocket(sock) onlineUsers[sock] = user break if userKey != "": break # When fail to verify a user, use any user's key to send back if userKey == "": userKey = anyUserPubKey if status: print "Successfully logged in" returnStatus = OK else: print "Failed to log in" returnStatus = rsa.encrypt(returnStatus, userKey) sock.send(returnStatus)
def DSSE_enc(file_path): with open(file_path) as inputfile: content = inputfile.read() # print 'content: ', content # content = content[:245] with open('public.pem') as publickfile: p = publickfile.read() pubkey = rsa.PublicKey.load_pkcs1(p) with open('private.pem') as privatefile: p = privatefile.read() privkey = rsa.PrivateKey.load_pkcs1(p) crypto = '' # print '========start=========' while content: message = content[:245] content = content[245:] enc_message = rsa.encrypt(message, pubkey) crypto += enc_message # print '-----------------message: -------------\n', message # print '-----------------content: -------------\n', content # print '-----------------enc_message: ---------\n', enc_message # print '-----------------crypto: --------------\n', crypto # crypto = rsa.encrypt(content, pubkey) # print 'crypto: ', crypto with open(file_path + '.enc', 'w+') as outputfile: outputfile.write(crypto) outputfile.close()
def login(self): """Login to LINE server.""" if self.provider == CurveThrift.Provider.LINE: # LINE j = self._get_json(self.LINE_SESSION_LINE_URL) else: # NAVER j = self._get_json(self.LINE_SESSION_NAVER_URL) session_key = j['session_key'] message = (chr(len(session_key)) + session_key + chr(len(self.id)) + self.id + chr(len(self.password)) + self.password).encode('utf-8') keyname, n, e = j['rsa_key'].split(",") pub_key = rsa.PublicKey(int(n,16), int(e,16)) crypto = rsa.encrypt(message, pub_key).encode('hex') self.transport = THttpClient.THttpClient(self.LINE_HTTP_URL) self.transport.setCustomHeaders(self._headers) self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self._client = CurveThrift.Client(self.protocol) msg = self._client.loginWithIdentityCredentialForCertificate( self.id, self.password, keyname, crypto, True, self.ip, self.com_name, self.provider, "") self._headers['X-Line-Access'] = msg.verifier self._pinCode = msg.pinCode print "Enter PinCode '%s' to your mobile phone in 2 minutes"\ % self._pinCode raise Exception("Code is removed because of the request of LINE corporation")
def enc_rsa(self, data): N = 0xaf0dddb4de63c066808f08b441349ac0d34c57c499b89b2640fd357e5f4783bfa7b808af199d48a37c67155d77f063ddc356ebf15157d97f5eb601edc5a104fffcc8895cf9e46a40304ae1c6e44d0bcc2359221d28f757f859feccf07c13377eec2bf6ac2cdd3d13078ab6da289a236342599f07ffc1d3ef377d3181ce24c719 E = 3 pub_key = rsa.PublicKey(N, E) return rsa.encrypt(data, pub_key)
def encryptpwd(passwd,token): password = token['hash'] + passwd pub_key = token['key'] pub_key = rsa.PublicKey.load_pkcs1_openssl_pem(pub_key) message = rsa.encrypt(str(password),pub_key) message = binascii.b2a_base64(message) return message
def main(): server_info = { "errno": 0, "pubkey_n": "117031647389468154238294760221768669666720727567321559438674532881383123833991837204444674701824886690302799348724838187836113927017307648768874827857745750096232380907604343230843940979123293616378389630394012315456891843867983730497700603209106315098130010818372297137065561806160237509869074384439104806477", "pubkey_e": "65537", "t": 1474101614 } server_pubkey = rsa.PublicKey( long(server_info['pubkey_n']), long(server_info['pubkey_e']) ) print 'pubkey_n:', pubkey.n print 'pubkey_e:', pubkey.e print 'http://127.0.0.1:5000/getTaskToken?pubkey_n=%s&pubkey_e=%s' % (pubkey.n, pubkey.e) task_token = "lwXLvE2nWtouITCyZ+G4LUWNezydEQClU3aUYqKprmdmCk18hjjk9ZbcDM3/+WoodE8oESPvuShavdzoB6tkXl6L2IWV1Ljj1QoQ4qkbrqasz1HTeiBCsoeFhVywNlVFcP5vBTzQvnbFAJEKwWHQTjw3csv6VQ8A5lLPPzIL4AY=" task_id = rsa.decrypt(base64.b64decode(task_token), privkey) print '\n','task_token:', task_token print 'task_id:', task_id data_json = json.dumps({ 'id': task_id, 't': int(time.time()), 'k': 'key cannot too long, less than 64 charts, use key to AES or DES.', }) data_crypt = base64.urlsafe_b64encode( rsa.encrypt(data_json, server_pubkey) ) print 'http://127.0.0.1:5000/sendData?data=%s' % (data_crypt)
def get_pwd(self): rsaPublickey = int(self.pubkey,16) key = rsa.PublicKey(rsaPublickey,65537) message = str(self.servertime) + '\t' + str(self.nonce) + '\n' + str(self.passwd) self.passwd = rsa.encrypt(message,key) self.passwd = binascii.b2a_hex(self.passwd) return self.passwd
def get_pwd_rsa(self, pwd, servertime, nonce): """ Get rsa2 encrypted password, using RSA module from https://pypi.python.org/pypi/rsa/3.1.1, documents can be accessed at http://stuvel.eu/files/python-rsa-doc/index.html """ # n, n parameter of RSA public key, which is published by WEIBO.COM #hardcoded here but you can also find it from values return from prelogin status above #import pdb;pdb.set_trace() weibo_rsa_n = 'EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D245A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD3993CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443' #e, exponent parameter of RSA public key, WEIBO uses 0x10001, which is 65537 in Decimal weibo_rsa_e = 65537 message = str(servertime) + '\t' + str(nonce) + '\n' + str(pwd) #construct WEIBO RSA Publickey using n and e above, note that n is a hex string key = rsa.PublicKey(int(weibo_rsa_n, 16), weibo_rsa_e) #get encrypted password if six.PY3: message = message.encode() encropy_pwd = rsa.encrypt(message, key) #trun back encrypted password binaries to hex string sp = binascii.b2a_hex(encropy_pwd) if six.PY3: sp = sp.decode('utf-8') return sp
def getPassword(self, password, servertime, nonce, pubkey): rsaPublickey = int(pubkey, 16) key = rsa.PublicKey(rsaPublickey, 65537) #创建公钥 message = str(servertime) + '\t' + str(nonce) + '\n' + str(password) #拼接明文js加密文件中得到 passwd = rsa.encrypt(message.encode('utf-8'), key) #加密 passwd = binascii.b2a_hex(passwd) #将加密信息转换为16进制。 return passwd
def __encrypt_password(self, password, server_time, nonce): rsa_public_key = int(self.PUBKEY, 16) key = rsa.PublicKey(rsa_public_key, 65537) message = str(server_time) + '\t' + str(nonce) + '\n' + str(password) message_bytes = message.encode('utf-8') passwd = rsa.encrypt(message_bytes, key) return binascii.b2a_hex(passwd).decode('utf-8')
def generate_form_data(nonce, pubkey, servertime, rsakv, username, password): rsa_public_key = int(pubkey, 16) key = rsa.PublicKey(rsa_public_key, 65537) message = str(servertime) + '\t' + str(nonce) + '\n' + str(password) passwd = rsa.encrypt(message, key) passwd = binascii.b2a_hex(passwd) username = urllib2.quote(username) username = base64.encodestring(username) form_data = { 'entry': 'weibo', 'gateway': '1', 'from': '', 'savestate': '7', 'useticket': '1', 'pagerefer': 'http://weibo.com/', 'vsnf': '1', 'su': username, 'service': 'miniblog', 'servertime': servertime, 'nonce': nonce, 'pwencode': 'rsa2', 'rsakv': rsakv, 'sp': passwd, 'sr': '1366*768', 'encoding': 'UTF-8', 'prelt': '115', 'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack', 'returntype': 'META' } form_data = urllib.urlencode(form_data) return form_data
def encrypt_pwd(self, pwd, servertime, nonce, pubkey): rsaPublickey = int(pubkey, 16) key = rsa.PublicKey(rsaPublickey, 65537) #创建公钥 message = str(servertime) + '\t' + str(nonce) + '\n' + str(pwd) #拼接明文 js加密文件中得到 passwd = rsa.encrypt(message, key) #加密 passwd = binascii.b2a_hex(passwd) #将加密信息转换为16进制 return passwd
def login(self): """Login to LINE server.""" if self.provider == CurveThrift.Provider.LINE: # LINE j = self._get_json(self.LINE_SESSION_LINE_URL) else: # NAVER j = self._get_json(self.LINE_SESSION_NAVER_URL) session_key = j['session_key'] message = (chr(len(session_key)) + session_key + chr(len(self.id)) + self.id + chr(len(self.password)) + self.password).encode('utf-8') keyname, n, e = j['rsa_key'].split(",") pub_key = rsa.PublicKey(int(n, 16), int(e, 16)) crypto = rsa.encrypt(message, pub_key).encode('hex') self.transport = THttpClient.THttpClient(self.LINE_HTTP_URL) self.transport.setCustomHeaders(self._headers) self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self._client = CurveThrift.Client(self.protocol) try: with open(self.CERT_FILE, 'r') as f: self.certificate = f.read() f.close() except: self.certificate = "" msg = self._client.loginWithIdentityCredentialForCertificate( self.id, self.password, keyname, crypto, True, self.ip, self.com_name, self.provider, self.certificate) if msg.type == 1: self.certificate = msg.certificate self.authToken = self._headers['X-Line-Access'] = msg.authToken elif msg.type == 2: msg = "require QR code" self.raise_error(msg) elif msg.type == 3: self._headers['X-Line-Access'] = msg.verifier self._pinCode = msg.pinCode print "Enter PinCode '%s' to your mobile phone in 2 minutes"\ % self._pinCode j = self.get_json(self.LINE_CERTIFICATE_URL) self.verifier = j['result']['verifier'] msg = self._client.loginWithVerifierForCertificate(self.verifier) if msg.type == 1: if msg.certificate is not None: with open(self.CERT_FILE, 'w') as f: f.write(msg.certificate) self.certificate = msg.certificate if msg.authToken is not None: self.authToken = self._headers[ 'X-Line-Access'] = msg.authToken return True else: return False else: msg = "Require device confirm" self.raise_error(msg) #raise Exception("Code is removed because of the request of LINE corporation") else: self.authToken = self._headers['X-Line-Access'] = msg.authToken return True
def cifra_message(text, pub_key): return rsa.encrypt(text, rsa.PublicKey.load_pkcs1(pub_key, format='PEM'))
def login(): deftext = '' infodef = '' su = base64.encodestring(usname.replace("@", "%40")).rstrip() header = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0' } url = 'https://login.sina.com.cn/sso/prelogin.php?entry=sso&callback=sinaSSOController.preloginCallBack&su=' + su + '&rsakt=mod&client=ssologin.js(v1.4.15)&_=1536325253756' try: rest = requests.get(url, headers=header).text restjson = json.loads(re.search(r'\((.*?)\)', rest).group(1)) pubkey = 'EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D245A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD3993CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443' nonce = restjson['nonce'] servertime = restjson['servertime'] rsaPublickey = int(pubkey, 16) key = rsa.PublicKey(rsaPublickey, 65537) # 创建公钥 message = str(servertime) + '\t' + str(nonce) + '\n' + str( password.strip()) # 拼接明文加密文件中得到 passwd = rsa.encrypt(message, key) # 加密 passwd = binascii.b2a_hex(passwd) # 将加密信息转换为16进制。 postdata = { 'entry': 'sso', 'gateway': '1', 'from': 'null', 'savestate': '30', 'useticket': '0', 'pagerefer': 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)', 'vsnf': '1', 'su': su, 'service': 'sso', 'servertime': servertime, 'nonce': nonce, 'pwencode': 'rsa2', 'rsakv': '1330428213', 'sp': passwd, 'sr': '1440*900', 'encoding': 'UTF-8', 'cdult': '3', 'domain': 'sina.com.cn', 'prelt': '22', 'returntype': 'TEXT' } #{"retcode":"0","uid":"6017844516","nick":"豆包子_k","crossDomainUrlList":["https:\/\/passport.weibo.com\/wbsso\/login?ticket=ST-NjAxNzg0NDUxNg%3D%3D-1536344036-gz-710A27FF5345A1CB32DA5340593053FB-1&ssosavestate=1567880036","https:\/\/passport.weibo.cn\/sso\/crossdomain?action=login&savestate=1"]} rest2 = requests.post( 'https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)&_=1536329319672', data=postdata, headers=header) #rest2= rest2.text.encode('utf-8').decode("'unicode_escape'") rest3 = json.loads(rest2.text) if rest3['retcode'] == '0': #rurl=re.search(r'(https\:.*?)"',rest2).group(1).replace("\\","") rurl = rest3['crossDomainUrlList'][0] cookies = requests.get(rurl).cookies.get_dict() cookiest = {} cookiest['cookie'] = cookies cookiest['emailphone'] = usname.strip() cookiest['psd'] = password.strip() cookiest['uid'] = rest3['uid'] cookiest['nick'] = rest3['nick'] strcookie = json.dumps(cookiest).replace('\'', '"') with open('cookie.txt', 'a+') as f: f.write(strcookie + '\n') infodef = "ok!!!" else: deftext = usname + '----' + password + '\n' infodef = rest2.text except Exception as e: infodef = e deftext = usname + '----' + password + '\n' if deftext.strip(): with open('det.txt', 'a+') as df: df.write(deftext) return infodef
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()
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
import rsa text = 'Welcome to RSA' # 生成密钥对 pubkey, prikey = rsa.newkeys(1024) # 加密:使用公钥 result = rsa.encrypt(text.encode(), pubkey) print('加密后的数据:',result) # 解密:使用私钥 print('解密后的数据:',rsa.decrypt(result, prikey))