def encrypt(self): msg = Message() msg.TimeStamp = str(now_sec()) msg.Nonce = randstr() msg.Encrypt = self._encrypt() msg.MsgSignature = self._sign_msg(msg.TimeStamp, msg.Nonce, msg.Encrypt) return msg
def test_create_tag(self): print("Testing create tag") auth = common.make_user(GATEWAY_URL, common.generate_user()) form = common.make_form(GATEWAY_URL, auth, common.generate_form()) common.post_form_user(GATEWAY_URL, form["id"], common.generate_response()) resp = common.get_responses_params(GATEWAY_URL, auth, {"formID": form["id"]})[0] common.make_tag(GATEWAY_URL, auth, resp["id"], common.randstr(5, 10))
def get_pay_sign(prepay_id): sign_items = { 'nonceStr': randstr(), 'timeStamp': str(now_sec()), 'package': 'prepay_id=' + prepay_id, 'signType': 'MD5', 'appId': APP_ID } sign_items['paySign'] = Signer.signstr(sign_items) return sign_items
def _encrypt(self): text = self.xml() text = bytes(randstr(16), 'utf-8') + struct.pack( "I", socket.htonl(len(text))) + text + bytes(APP_ID, 'utf-8') text = PKCS7Encoder().encode(text) key = base64.b64decode(ENCODING_AES_KEY) cryptor = AES.new(key, AES.MODE_CBC, key[:16]) cipher = cryptor.encrypt(text) return base64.b64encode(cipher)
def get_enc(): with open('data/20.txt', 'r') as f: data = f.read().split() data = [a.decode('base64') for a in data] key = randstr(16) nonce = randint(0, 2**64 - 1) enc = [AES_CTR(a, key, nonce) for a in data] return enc
def _send_redpack(service, openid, user_pay_id, money): money = strategy.get_strategy().pay(openid, money) redpack = Message() redpack.nonce_str = randstr() redpack.mch_billno = build_mch_billno() redpack.mch_id = app.config['MCH_ID'] redpack.wxappid = app.config['APP_ID'] redpack.send_name = app.config['MCH_NAME'] redpack.re_openid = openid redpack.total_amount = money redpack.total_num = 1 redpack.wishing = app.config['REDPACK_WISHING'] redpack.client_ip = app.config['LOCAL_IP'] redpack.act_name = app.config['REDPACK_ACTIVE_NAME'] redpack.remark = app.config['REDPACK_REMARK'] redpack.sign() # FIXME: 若在发出红包之后,向微信确认之前出现异常,微信会重复发送此事件,导致重复给用户发红包 result = weixin.send_redpack(redpack) sys_pay = dict(openid=openid, money=money, billno=redpack.mch_billno, user_pay_id=user_pay_id, state='SENDED', type='RETURN') service.save_sys_pay(sys_pay) # todo: 给用户发红包失败后应有应对措施 if result.return_code == FAIL: app.logger.error( 'communication error while send redpack to user: %s, billno: %s, reason: %s', openid, redpack.mch_billno, result.return_msg) sys_pay['state'] = FAIL sys_pay['error_msg'] = result.return_msg service.update_sys_pay(sys_pay) return if result.result_code == FAIL: app.logger.error( 'send redpack to user: %s failed, billno: %s, reason: %s-%s', openid, redpack.mch_billno, result.err_code, result.err_code_des) sys_pay['state'] = FAIL sys_pay['error_msg'] = '{}-{}'.format(result.err_code, result.err_code_des) service.update_sys_pay(sys_pay) return app.logger.info('send redpack to user: %s success, billno: %s', openid, redpack.mch_billno) sys_pay['state'] = SUCCESS sys_pay['wx_billno'] = result.send_listid service.update_sys_pay(sys_pay)
def post(self): pdict = self.request.POST action = pdict.get("action", "") if action == "new": try: Category.new(pdict.get("category.url", randstr()), pdict.get("category.title"), pdict.get("category.discription") ) Category.refresh_total() except Rollback, ex: self.jsonout(ex) else: self.jsonout("ok")
def _build_order(openid, money, remote_addr): order = Message() order.appid = app.config['APP_ID'] order.nonce_str = randstr() order.mch_id = app.config['MCH_ID'] order.body = 'game-tax' order.out_trade_no = _timestamp_str() order.total_fee = money order.spbill_create_ip = remote_addr order.notify_url = app.config['RESTFUL_ROOT'] + '/pay/notify' order.trade_type = 'JSAPI' order.openid = openid order.sign() return order
def encryption_oracle(): data = (""" MDAwMDAwTm93IHRoYXQgdGhlIHBhcnR5IGlzIGp1bXBpbmc= MDAwMDAxV2l0aCB0aGUgYmFzcyBraWNrZWQgaW4gYW5kIHRoZSBWZWdhJ3MgYXJlIHB1bXBpbic= MDAwMDAyUXVpY2sgdG8gdGhlIHBvaW50LCB0byB0aGUgcG9pbnQsIG5vIGZha2luZw== MDAwMDAzQ29va2luZyBNQydzIGxpa2UgYSBwb3VuZCBvZiBiYWNvbg== MDAwMDA0QnVybmluZyAnZW0sIGlmIHlvdSBhaW4ndCBxdWljayBhbmQgbmltYmxl MDAwMDA1SSBnbyBjcmF6eSB3aGVuIEkgaGVhciBhIGN5bWJhbA== MDAwMDA2QW5kIGEgaGlnaCBoYXQgd2l0aCBhIHNvdXBlZCB1cCB0ZW1wbw== MDAwMDA3SSdtIG9uIGEgcm9sbCwgaXQncyB0aW1lIHRvIGdvIHNvbG8= MDAwMDA4b2xsaW4nIGluIG15IGZpdmUgcG9pbnQgb2g= MDAwMDA5aXRoIG15IHJhZy10b3AgZG93biBzbyBteSBoYWlyIGNhbiBibG93 """).split() iv = randstr(16) data = choice(data).decode('base64') return (iv, AES_CBC_encrypt(pad(data), oracle_key, iv))
def get_jsapi_sign(url): if _jsapi_ticket['ticket'] is None or _jsapi_ticket[ 'timestamp'] + 7000 <= now_sec(): access_token = get_access_token() _jsapi_ticket['ticket'] = json.loads( HTTP.get(WX_URL_GET_JSAPI_TICKET, access_token=access_token, type='jsapi'))['ticket'] _jsapi_ticket['timestamp'] = now_sec() noncestr = randstr() timestamp = now_sec() sign = _build_jsapi_sign(_jsapi_ticket['ticket'], noncestr, timestamp, url) return { 'noncestr': noncestr, 'sign': sign, 'timestamp': timestamp, 'appid': APP_ID }
def get_user_share_qrcode(): openid = session.get('openid') if not openid: return redirect(weixin_oauth2_url()) user = g.service.find_user(openid) rsp = dict(ret=SUCCESS, msg='ok') if not user['share_qrcode']: qr_file = randstr() auth_url = weixin.oauth2_url( app.config['RESTFUL_ROOT'] + '/auth/redirect', user['id']) short_url = weixin.url_to_short(auth_url) make_qrcode(short_url['short_url'], '%s/%s.png' % (app.config['QRCODE_HOME'], qr_file)) user['share_qrcode'] = qr_file + '.png' g.service.update_user(user) rsp['qrcode'] = user['share_qrcode'] app.logger.debug("user: %s, get qrcode return: %s", openid, rsp) return json_dumps(rsp)
U28gZGFyaW5nIGFuZCBzd2VldCBoaXMgdGhvdWdodC4= VGhpcyBvdGhlciBtYW4gSSBoYWQgZHJlYW1lZA== QSBkcnVua2VuLCB2YWluLWdsb3Jpb3VzIGxvdXQu SGUgaGFkIGRvbmUgbW9zdCBiaXR0ZXIgd3Jvbmc= VG8gc29tZSB3aG8gYXJlIG5lYXIgbXkgaGVhcnQs WWV0IEkgbnVtYmVyIGhpbSBpbiB0aGUgc29uZzs= SGUsIHRvbywgaGFzIHJlc2lnbmVkIGhpcyBwYXJ0 SW4gdGhlIGNhc3VhbCBjb21lZHk7 SGUsIHRvbywgaGFzIGJlZW4gY2hhbmdlZCBpbiBoaXMgdHVybiw= VHJhbnNmb3JtZWQgdXR0ZXJseTo= QSB0ZXJyaWJsZSBiZWF1dHkgaXMgYm9ybi4= '''.split() data = [a.decode('base64') for a in data] key = randstr(16) nonce = randint(0, 2**64 - 1) enc = [AES_CTR(a, key, nonce) for a in data] print enc print print "I am too lazy to solve this by hand, but if you want to do so, above are the encrypted texts." print "Here are some ideas for solving:" print " 1. Pair them off" print " 2. XOR them" print " 3. Check for frequencies" print " 4. Check for bigrams" print " 5. Check for trigrams" print " 6. ???" print " 7. Profit!"
from common import randstr def parse(data): data = data.split('&') data = [x.split('=') for x in data] ret = {k: v for k, v in data} return ret # Oracles oracle_key = randstr(16) def profile_for(email): from common import AES_ECB_encrypt, pad email = email.replace('=', '').replace('&', '') profile = 'email=' + email + '&uid=10&role=user' return AES_ECB_encrypt(pad(profile), oracle_key) def user_profile(enc): from common import AES_ECB_decrypt, unpad return parse(unpad(AES_ECB_decrypt(enc, oracle_key))) # Attack def main():
from common import randstr, AES_CBC_encrypt, AES_CBC_decrypt, pad, xor_str oracle_key = randstr(16) oracle_iv = randstr(16) def encryption_oracle(data): data = data.replace(';', '').replace('=', '') data = "comment1=cooking%20MCs;userdata=" + data data = data + ";comment2=%20like%20a%20pound%20of%20bacon" data = pad(data) return AES_CBC_encrypt(data, oracle_key, oracle_iv) def decryption_oracle(data): dec = AES_CBC_decrypt(data, oracle_key, oracle_iv) return ';admin=true;' in dec def main(): prefix_only = encryption_oracle("") value = encryption_oracle("A" * (16 * 3)) for i in range(0, len(prefix_only), 16): if prefix_only[i:i + 16] != value[i:i + 16]: attack = value[:i] attack += xor_str(value[i:i + 16], xor_str(';admin=true;xxxx', 'A' * 16)) attack += value[i + 16:] break if decryption_oracle(attack): print "[+] Admin access granted"
from common import AES_ECB_decrypt, AES_CTR, randstr from random import randint def get_data(): with open('data/25.txt', 'r') as f: data = f.read().decode('base64') key = "YELLOW SUBMARINE" return AES_ECB_decrypt(data, key) KEY, NONCE = randstr(16), randint(0, 1 << 64 - 1) print "[+] Using KEY, NONCE = %s, 0x%x" % (repr(KEY), NONCE) ciphertext = AES_CTR(get_data(), KEY, NONCE) def edit_api(offset, newtext): # ciphertext, key are taken from # global variables, and ciphertext is # edited directly global ciphertext assert (offset >= 0) assert (offset + len(newtext) <= len(ciphertext)) dec = AES_CTR(ciphertext, KEY, NONCE) mod = dec[:offset] + newtext + dec[offset + len(newtext):] ciphertext = AES_CTR(mod, KEY, NONCE) def break_ctr(edit): from common import xor_str enc = ciphertext[:] edit(0, '\x00' * len(enc))
from common import AES_ECB_encrypt, pad, randstr from random import randint oracle_key = randstr(16) random_prefix = randstr(randint(3, 255)) def ecb_oracle(data): data += (""" Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg YnkK """.decode('base64')) data = random_prefix + data data = pad(data) return AES_ECB_encrypt(data, oracle_key) def get_block_size(oracle): i = 0 prev_len = len(oracle('')) while True: i += 1 new_len = len(oracle('A' * i)) if new_len > prev_len: return new_len - prev_len def get_hidden_data_len(oracle): prev = len(oracle(''))