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
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
encropy_pwd = rsa.encrypt(message, key)
#trun back encrypted password binaries to hex string
return binascii.b2a_hex(encropy_pwd)
python类encrypt()的实例源码
def encrypt_password(p, st, nonce, pk, rsakv):
"""
Encrypting the password using rsa algorithm.
p: password
st: server time
nonce: random value
pk: public key
rsakv: rsa key value
"""
pk = '0x' + pk
pk = int(pk, 16)
msg = str(st) + '\t' + str(nonce) + '\n' + p
key = rsa.PublicKey(pk, 65537)
psw = rsa.encrypt(msg.encode("utf-8"), key)
psw = binascii.b2a_hex(psw)
return decode(psw)
def getPublicKey():
login_public_key_url = 'https://lantouzi.com/api/uc/get_key?%s' % time.time()
# ?????
headers = {'Referer': 'https://lantouzi.com/login'}
data = session.get(login_public_key_url, headers=headers).content.decode('utf-8')
# print(data)
# data = "{'data': {'encrypt': {'field_name': '_encrypt_code', 'public_key': '-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDidnLFl8ivfrAtKz9YX0Qi1V4b\nq/x4lHDjswf9AQS8hzfxsbzzDaDa07V7N6PvibJYqbhrj14Pi2fGC7CED5MzQ1r6\nvwmT+wJeBC//8PVxZXo/h15g2QzfYkyp4z+IlJZYqHfYGZXu9HTsFDZhfQE8LEz3\nkbAfyb2sLcfGimQWRwIDAQAB\n-----END PUBLIC KEY-----\n', 'field_value': '480b74ab3a165ef8bf2685a0d56f6b7a'}}, 'code': 1, 'message': ''}"
try:
data = json.loads(data)
if data['code'] == 1:
return data['data']['encrypt']
return False
except:
return False
# ?????
def encrypt(data):
# load?????
with open('api_pub.key') as publickfile:
p = publickfile.read()
pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(p)
# ?????
n = int(math.ceil(len(data) * 1.0 / 117))
ret = ''
for i in range(n):
gzdata = data[i * 117:(i + 1) * 117]
ret += rsa.encrypt(gzdata, pubkey)
# print ret
return ret
# ??gzip
def prelogin(self):
data = {'username': self.username,
'token': self.token,
'functionName': 'preLogin',
'uuid': UUID,
'request': {'osVersion': 'windows', 'deviceType': 'pc', 'clientVersion': '1.0'},
}
headers = {'UUID': UUID, 'account_type': ACCOUNT_TYPE,
'Content-Type': 'data/gzencode and rsa public encrypt;charset=UTF-8'
}
# ??
post_data = gzencode(json.dumps(data))
# ??
post_data = encrypt(post_data)
resp = requests.post(LOGIN_URL, data=post_data, headers=headers)
ret = json.loads(gzdecode(resp.content[8:]))
print 'prelogin:', ret
def dologin(self):
data = {'username': self.username,
'token': self.token,
'functionName': 'doLogin',
'uuid': UUID,
'request': {'password': self.password}
}
headers = {'UUID': UUID, 'account_type': ACCOUNT_TYPE,
'Content-Type': 'data/gzencode and rsa public encrypt;charset=UTF-8'
}
# ??
post_data = gzencode(json.dumps(data))
# ??
post_data = encrypt(post_data)
# post
resp = requests.post(LOGIN_URL, data=post_data, headers=headers)
ret = json.loads(gzdecode(resp.content[8:]))
if ret['retcode'] == 0:
print u'dologin:', ret['retmsg']
print ret['ucid']
print ret['st']
return ret
def dologout(self):
data = {'username': self.username,
'token': self.token,
'functionName': 'doLogout',
'uuid': UUID,
'request': {'ucid': self.ucid, 'st': self.st, }
}
headers = {'UUID': UUID, 'account_type': ACCOUNT_TYPE,
'Content-Type': 'data/gzencode and rsa public encrypt;charset=UTF-8'
}
# ??
post_data = gzencode(json.dumps(data))
# ??
post_data = encrypt(post_data)
# post
resp = requests.post(LOGIN_URL, data=post_data, headers=headers)
ret = json.loads(gzdecode(resp.content[8:]))
print 'logout:', ret['retmsg']
def encrypt_assistant():
fname = input("Bitte gebe den Pfad der zu verschlüsselnden Datei an: ")
f = open(fname, "rb")
content = f.read()
f.close()
print("Datei eingelesen.")
names = pubkr.gets()
print("Namen: " + ' '.join(names))
name = input("Bitte wähle einen aus: ")
while not name in names:
if name == "": return
print("Dieser Name existiert nicht.")
print("Namen: " + ' '.join(names))
name = input("Bitte wähle einen anderen aus: ")
print("Verschlüssele (dauert einen Moment)")
crypt = rsa.encrypt(content, pubkr.get(name))
crypt = str(base64.b64encode(bytes(crypt, "utf-8")), "utf-8")
crypt = insert_newlines(crypt, 60)
crypt = armor("RSPLUS OUTPUT", name, crypt)
f = open(fname + ".crypt", "w")
f.write(crypt)
f.close()
print("Die verschlüsselte Version der Datei können sie unter " + fname + ".crypt finden. Sie können diese Datei an den Empfänger versenden.")
def encrypt_assistant():
fname = input("Bitte gebe den Pfad der zu verschlüsselnden Datei an: ")
f = open(fname, "rb")
content = f.read()
f.close()
print("Datei eingelesen.")
names = pubkr.gets()
print("Namen: " + ' '.join(names))
name = input("Bitte wähle einen aus: ")
while not name in names:
if name == "": return
print("Dieser Name existiert nicht.")
print("Namen: " + ' '.join(names))
name = input("Bitte wähle einen anderen aus: ")
print("Verschlüssele (dauert einen Moment)")
crypt = rsa.encrypt(content, pubkr.get(name))
crypt = str(base64.b64encode(bytes(crypt, "utf-8")), "utf-8")
crypt = insert_newlines(crypt, 60)
crypt = armor("RSPLUS OUTPUT", name, crypt)
f = open(fname + ".crypt", "w")
f.write(crypt)
f.close()
print("Die verschlüsselte Version der Datei können sie unter " + fname + ".crypt finden. Sie können diese Datei an den Empfänger versenden.")
def get(self):
# checks if the user can create a new package entry
# if so, returns a new secret
# user then must post the signed package to this endpoint
if not ENGINE.check_package(request.form['owner'], request.form['package']):
# try to pull the users public key
query = ENGINE.get_key(request.form['owner'])
# in doing so, check if the user exists
if query == None:
return error_payload('Owner does not exist.')
# construct the user's public key
user_public_key = rsa.PublicKey(int(query[0]), int(query[1]))
# create a new secret
secret = random_string(53)
# sign and store it in the db so no plain text instance exists in the universe
server_signed_secret = str(rsa.encrypt(secret.encode('utf8'), KEY[0]))
query = ENGINE.set_secret(request.form['owner'], server_signed_secret)
# sign and send secret to user
user_signed_secret = rsa.encrypt(secret.encode('utf8'), user_public_key)
return success_payload(str(user_signed_secret), 'Package available to register.')
else:
return error_payload('Package already exists.')
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)
def perform_operation(self, indata, pub_key, cli_args=None):
'''Encrypts files.'''
return rsa.encrypt(indata, pub_key)
def perform_operation(self, indata, pub_key, cli_args=None):
"""Encrypts files."""
return rsa.encrypt(indata, pub_key)
def perform_operation(self, indata, pub_key, cli_args=None):
'''Encrypts files.'''
return rsa.encrypt(indata, pub_key)
def encrypt(fingerprint, data):
"""
Encrypts the given data known the fingerprint to be used
in the way Telegram requires us to do so (sha1(data) + data + padding)
:param fingerprint: the fingerprint of the RSA key.
:param data: the data to be encrypted.
:return:
the cipher text, or None if no key matching this fingerprint is found.
"""
global _server_keys
key = _server_keys.get(fingerprint, None)
if not key:
return None
# len(sha1.digest) is always 20, so we're left with 255 - 20 - x padding
to_encrypt = sha1(data).digest() + data + os.urandom(235 - len(data))
# rsa module rsa.encrypt adds 11 bits for padding which we don't want
# rsa module uses rsa.transform.bytes2int(to_encrypt), easier way:
payload = int.from_bytes(to_encrypt, 'big')
encrypted = rsa.core.encrypt_int(payload, key.e, key.n)
# rsa module uses transform.int2bytes(encrypted, keylength), easier:
block = encrypted.to_bytes(256, 'big')
return block
# Add default keys
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
weibo_rsa_n = ('EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090'
'CB2D245A87AC253062882729293E5506350508E7F9AA'
'3BB77F4333231490F915F6D63C55FE2F08A49B353F44'
'4AD3993CACC02DB784ABBB8E42A9B1BBFFFB38BE18D7'
'8E87A0E41B9B8F73A928EE0CCEE1F6739884B9777E4F'
'E9E88A1BBE495927AC4A799B3181D6442443')
# 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 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 perform_operation(self, indata, pub_key, cli_args=None):
"""Encrypts files."""
return rsa.encrypt(indata, pub_key)
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', '')
userencode.py 文件源码
项目:SinaMicroblog_Creeper-Spider_VerificationCode
作者: somethingx64
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def get_pwd(password, servertime, nonce, pubkey):
rsaPublickey = int(pubkey, 16)
key = rsa.PublicKey(rsaPublickey,65537)#create public key
message = str(servertime) + '\t' + str(nonce) + '\n' + str(password)#create clear text
passwd = rsa.encrypt(message, key)#cipher text
passwd = binascii.b2a_hex(passwd)#convert the cipher text into hexadecimal
return passwd
def perform_operation(self, indata, pub_key, cli_args=None):
"""Encrypts files."""
return rsa.encrypt(indata, pub_key)
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/p/1005052679342531/home?from=page_100505&mod=TAB&pids=plc_main',
'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
# ====================?????cookie====================
def rsaEncrypt(password):
url = 'http://passport.bilibili.com/login?act=getkey'
try:
getKeyRes = session.get(url)
token = json.loads(getKeyRes.content.decode('utf-8'))
pw = str(token['hash'] + password).encode('utf-8')
key = token['key']
key = rsa.PublicKey.load_pkcs1_openssl_pem(key)
pw = rsa.encrypt(pw, key)
password = binascii.b2a_base64(pw)
return password
except:
return False
def perform_operation(self, indata, pub_key, cli_args=None):
"""Encrypts files."""
return rsa.encrypt(indata, pub_key)
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')
def get_passwd(self, pubkey, servertime, nonce):
import rsa
rsaPublickey = int(pubkey, 16)
key = rsa.PublicKey(rsaPublickey, 65537) #????
message = str(servertime) + '\t' + str(nonce) + '\n' + str(self.password) #????js???????
passwd = rsa.encrypt(message, key) #??
passwd = binascii.b2a_hex(passwd) #????????16???
return passwd
def get_passwd(self, pubkey, servertime, nonce):
import rsa
rsaPublickey = int(pubkey, 16)
key = rsa.PublicKey(rsaPublickey, 65537) # ????
message = str(servertime) + '\t' + str(nonce) + '\n' + \
str(self.password) # ????js???????
passwd = rsa.encrypt(message, key) # ??
passwd = binascii.b2a_hex(passwd) # ????????16???
return passwd
def upstream_recv(self, data):
try:
cleartext=data.peek()
tosend=b""
i=0
packed_size=struct.pack("<I", len(cleartext))
tosend=packed_size+cleartext
tosend+=b"\x00"*(BLOCK_SIZE - (len(tosend)%BLOCK_SIZE))
data.drain(len(cleartext))
self.downstream.write(self.enc_cipher.encrypt(tosend))
except Exception as e:
logging.debug(e)
def on_connect(self):
pk = rsa.PublicKey.load_pkcs1(self.pubkey)
if Random:
self.aes_key = Random.new().read(self.key_size)
else:
self.aes_key = os.urandom(self.key_size)
if AES is not None:
self.enc_cipher = AES.new(self.aes_key, AES.MODE_CBC, self._iv_enc)
else:
self.enc_cipher = pyaes.AESModeOfOperationCBC(self.aes_key, iv = self._iv_enc)
self.downstream.write(rsa.encrypt(self.aes_key, pk))
self.downstream.write(self._iv_enc)
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')