def initvars(): global Logueado Logueado = False config = ConfigParser() config.read("conf/config.ini") tipo = config.get('CUENTA', 'Tipo') ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==') xorps = XOR.new(str(ps)) global Tipo Tipo = xorps.decrypt(b64decode(str(tipo))) webserver = config.get('WEB', 'srv') ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==') xorps = XOR.new(str(ps)) global WEBServer WEBServer = xorps.decrypt(b64decode(str(webserver))) print WEBServer global DatosUsuario DatosUsuario = {} global DictSenales DictSenales = {} global BD BD = BasedeDatos() BD.Conectar() global DictColaResultados DictColaResultados = {} t = threading.Thread(target=GetIps) t.start()
def encrypt_url(path, dl_filename=None): """ Call this within your client app to generate a URL to query the Cryptostream WSGI app server with. path: (str) The URL path to the internal-flagged location on the Nginx server that the files will be served from via X-Accel-Redirect. dl_filename: (str/None) If specified, the file that the user downloads will be named according to the value, instead of from the name on the filesystem. """ # Encrypt the path and the timestamp. path = XOR.new(KEY).encrypt(path) ts = XOR.new(KEY).encrypt(time.time().__str__()) # Encode path/ts to base 64. path = base64.b64encode(path) ts = base64.b64encode(ts) # This dict will get urlencoded as GET keywords. value_dict = {"path": path, "ts": ts} # Check for download filename override. if dl_filename: value_dict["dl_filename"] = dl_filename return urllib.urlencode(value_dict)
def xor_encode_dict(dictionary): """ Кодирует словарь алгоритмом XOR """ result = {} for key, val in dictionary.iteritems(): key = base64.encodestring(XOR.new(settings.XOR_KEY).encrypt(key)) val = base64.encodestring(XOR.new(settings.XOR_KEY).encrypt(val)) result[key] = val return result
def _getMAC(self, mac, key): modName = self.macMap[mac] if not modName: return None mod = __import__(modName, {}, {}, '') if not hasattr(mod, 'digest_size'): ds = len(mod.new().digest()) else: ds = mod.digest_size key = key[: ds]+'\x00'*(64-ds) i = XOR.new('\x36').encrypt(key) o = XOR.new('\x5c').encrypt(key) return mod, i,o, ds
def app(environ, start_response): """ WSGI app method. You'll want to point your WSGI server at this method. """ data = environ["PATH_INFO"] # GET querystring. qs = urlparse.parse_qs(environ["QUERY_STRING"]) # Decode from base64. try: path = base64.b64decode(qs["path"][0]) ts = base64.b64decode(qs["ts"][0]) except: return render_error_page(environ, start_response) # Decrypt using XOR. try: path = XOR.new(KEY).decrypt(path) ts = datetime.datetime.fromtimestamp(float(XOR.new(KEY).decrypt(ts))) except: return render_error_page(environ, start_response) # Determine what the file will be named for the user's browser. if qs.has_key("dl_filename"): # Filename was passed as a GET keyword. dl_filename = qs["dl_filename"][0] else: # No filename specified, use the name on the filesystem. dl_filename = os.path.basename(path) dbg = path now = datetime.datetime.now() if (now - ts) > LINK_EXPIRE_TDELTA: # Expired, show vague error page. return render_error_page(environ, start_response) else: # Everything is good, serve the file through X-Accel-Redirect. status = "200 OK" response_headers = [ ("X-Accel-Redirect", path), ("Content-Disposition", "attachment; filename=%s" % dl_filename), ] start_response(status, response_headers) # This needs to be an empty string or we'll get premature socket # closing errors. The body is ignored by Nginx, and the connection is # closed before this returned value can be read, causing the error. return ""
def encrypt(self, key, plaintext): (input_whitening_key, output_whitening_key) = self.build_whitening_keys(key) input_whitener = XOR.new(str(input_whitening_key)).encrypt output_whitener = XOR.new(str(output_whitening_key)).encrypt ciphertext = bytearray(len(plaintext)) if (len(plaintext) % 8): raise Exception("plaintext length must be a multiple of 8") des = DES.new(str(key[0:8]), DES.MODE_CBC, str(bytearray(8))).encrypt for i in range(len(plaintext)/8): ciphertext[i*8:i*8+8] = bytearray(output_whitener(des(input_whitener(str(plaintext[i*8:i*8+8]))))) des = DES.new(str(key[0:8]), DES.MODE_CBC, str(bytearray(8))).encrypt return ciphertext
def createciphermsgs_xor(jt65msgcount, stegmsg, key, verbose=False): # Performs the actual XOR cipher ciphermsgs = [] # Can we fit your hidden message? if jt65msgcount * 8 < len(stegmsg): print( "Length of hidden message exceeds capacity of number of valid JT65 messages provided") sys.exit(0) originallength = len(stegmsg) while len(stegmsg) % 8: stegmsg += chr(random.randint(0, 255)) cryptobj = XOR.new(key) cipherdata = cryptobj.encrypt(stegmsg) cipherlist = list(bytearray(cipherdata)) # Is the total length too big to fit into our max number of packets? if len(cipherlist) > MAX_MULTI_PACKET_STEG_BYTES_XOR: print("Length of hidden message exceeds capacity of multi-packet steg") sys.exit(0) totalpackets = len(cipherlist) / 8 if verbose: print "Cipher list: " + str(cipherlist) createciphermsgs_packer_xor( totalpackets, originallength, ciphermsgs, cipherlist, verbose) return ciphermsgs
def token_json(self, uuid): crypt = XOR.new(self.password) str = "%s\n%s " % ( int(time.mktime(datetime.now().timetuple())), uuid) # I hate obfuscation. Its all I've got token = crypt.encrypt(str) return dict(token=urllib.quote(token), prefered_protocol=self.smolt_protocol)
def decrypt_chunk(secret, fpath, queue): """ @type secret: str @type fpath: str @type queue: multiprocessing.Queue """ chunk_file = open(fpath.strip()) chunk_pos_len = int(chunk_file.readline()) chunk_pos = int(chunk_file.read(chunk_pos_len)) initialization_vector_len = int(chunk_file.readline()) initialization_vector = chunk_file.read(initialization_vector_len) data_hash_len = int(chunk_file.readline()) data_hash = chunk_file.read(data_hash_len) enc_data_len = int(chunk_file.readline()) enc_data = chunk_file.read(enc_data_len) if 16 != len(initialization_vector): raise Exception("initialization_vector len is not 16") #cipher = AES.new(secret, AES.MODE_CFB, IV=initialization_vector) cipher = XOR.new(secret) dec_data = cipher.decrypt(enc_data) calculated_hash = make_checksum(dec_data) if data_hash != calculated_hash: raise EncryptionHashMismatch("decrypt_file -> the decryption went wrong, hash didn't match") if queue.qsize() > 20: time.sleep(0.5) queue.put((chunk_pos, dec_data)) return True
def encrypt_chunk(secret, fpath, chunksize, initialization_vector): """ @param secret: pkdf2 secre @type secret: str @type fpath: str @type chunksize: tuple """ try: f = open(fpath) f.seek(chunksize[0]) chunk = f.read(chunksize[1]) #cipher = AES.new(secret, AES.MODE_CFB, IV=initialization_vector) cipher = XOR.new(secret) data_hash = make_checksum(chunk) enc_data = cipher.encrypt(chunk) ntf = get_named_temporary_file(auto_delete=False) chunk_seek = str(chunksize[0]) ntf.write(str(len(chunk_seek)) + "\n") ntf.write(chunk_seek) ntf.write(str(len(initialization_vector)) + "\n") ntf.write(initialization_vector) ntf.write(str(len(data_hash)) + "\n") ntf.write(data_hash) ntf.write(str(len(enc_data)) + "\n") ntf.write(enc_data) return ntf.name except Exception, e: raise e
def xor_decrypt(raw): if cipher[0] is None: if len(raw) < AES.block_size: return None, 0 cipher[0] = XOR.new(raw[: AES.block_size]) return None, AES.block_size return cipher[0].decrypt(raw), len(raw)
def get_key(request): if (request.method != 'POST'): return err_GE002() form = GetKeyForm(request.POST) if (not form.is_valid()): return err_GE031(form) #dbkey = get_user_key(request, ss=form.cleaned_data['secret']) db_secret = request.device_assn.db_secret xor = XOR.new(base64.b64decode(form.cleaned_data['secret'])) db_key = xor.encrypt(base64.b64decode(db_secret)) if (not request.device_assn.verify_db_key(db_key)): return err_GE022() # Okay, we need to test the validity of this key before we return it. # Otherwise, we could return an invalid key. response = { 'data': { 'key':base64.b64encode(db_key), # 'gcm_project_id': settings.GCM_PROJECT_ID }, 'warnings':{} } return HttpResponse(content=json.dumps(response), mimetype='application/json')
def _xor(self, a, b): """Performs XOR on two strings a and b""" if len(a) != len(b): raise "ERROR: Strings are of different size! %s %s" % (len(a), len(b)) xor = XOR.new(a) return xor.encrypt(b)
def __init__(self): self.resultado = None #Buscando el archivo INI para saber el String de Conexion config = ConfigParser() config.read("conf/config.ini") self.conexioncifrada = config.get('BASE DE DATOS', 'conexion') PASSWORD = XOR.new(base64.b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) self.conexion = PASSWORD.decrypt(base64.b64decode(str(self.conexioncifrada)))
def xorEncrypt(request): plain_text = request.POST["message"] output = u"Klartext:\n%s\n\n" %(plain_text) key = hashlib.sha256(request.POST["key"]).digest() output += u"Schlüssel: %s\n\n"%(request.POST["key"]) output += u"XOR-verschlüsselt:\n" xorObject = XOR.new(key) cypher = number.bytes_to_long(xorObject.encrypt(plain_text)) return ( output, cypher )
def __init__(self): self.resultado = None #Buscando el archivo INI para saber el String de Conexion config = ConfigParser() config.read("Conect.dat") self.conexioncifrada = config.get('DB', 'StringDB') PASSWORD = XOR.new(base64.b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) self.conexion = PASSWORD.decrypt(base64.b64decode(str(self.conexioncifrada))) self.conexion = 'Driver={SQL Server Native Client 11.0};Server=AXNER-HP\JERMSOFT;Database=365DB_2;Uid=sa;Pwd=jerm'
def fixkey(key): half1= key[:16] half2= key[16:] encryptor = XOR.new(half2) newkey= encryptor.encrypt(half1) return newkey
def _getMAC(self, mac, key): """ Gets a 4-tuple representing the message authentication code. (<hash module>, <inner hash value>, <outer hash value>, <digest size>) @param mac: a key mapping into macMap @type mac: C{str} @param key: the MAC key. @type key: C{str} """ mod = self.macMap[mac] if not mod: return (None, '', '', 0) ds = mod().digest_size key = key[:ds] + '\x00' * (64 - ds) i = XOR.new('\x36').encrypt(key) o = XOR.new('\x5c').encrypt(key) return mod, i, o, ds
def check_admin_token(self, token, uuid): print "TOKEN CHECK" token = urllib.unquote(token) crypt = XOR.new(self.password) token_plain = crypt.decrypt(token).split('\n') if uuid[:7] == token_plain[0]: print 'GOT GOOD TOKEN!' return token else: raise ValueError("Critical: %s not a valid token for UUID" % token)
def ConvertirDatos(stringbd,lic,cualmodo,dondebd): print 'Convirtiendo Datos' if dondebd == '1': stringbd = stringbd.replace('NOMBREPC',str(gethostname())) elif dondebd == '2': print 'Indique la direccion donde se encuentra la Base de Datos' direccionremota = raw_input('Indique una direccion IP o un DNS para la conexion a Base de Datos: ') stringbd = stringbd.replace('NOMBREPC','mc24.no-ip.net') stringbd = stringbd.replace('NOMBREBD','365DB') stringbd = stringbd.replace('USUARIOBD','sa') stringbd = stringbd.replace('PASSWORDBD','jerm') deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) stringbd = b64encode(deco.encrypt(str(stringbd))) deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) lic = b64encode(deco.encrypt(str(lic))) deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) cualmodo = b64encode(deco.encrypt(str(cualmodo))) print 'Datos Convertidos' CrearArchivo(stringbd,lic,cualmodo)
def check_token(self, token, uuid): token = urllib.unquote(token) crypt = XOR.new(self.password) token_plain = crypt.decrypt(token).split('\n') token_time = int(token_plain[0]) token_uuid = token_plain[1] current_time = int(time.mktime(datetime.now().timetuple())) if current_time - token_time > 60: raise ValueError("Critical [20]: Invalid Token - Likely A timeout, please try again.") if uuid.strip() != token_uuid.strip(): raise ValueError("Critical [s]: Invalid Token - Likely A timeout, please try again.")
def RKXencrypt(): plainText="Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal" key = "ICE" cipherText = "" for x in range(0,len(plainText)): cipherText += util.b16encode(XOR.XORCipher.encrypt(XOR.new(key[x % 3]), plainText[x])) print cipherText if cipherText == "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f".upper(): print "Test Passed"
def decryption(): print "Your key: " key = raw_input() print "Your encrypted password/message: " pw = raw_input() c = XOR.new(key) dpw = c.decrypt(base64.b64decode(pw)) print "Your decrypted password/message is: " + dpw print "Would you like to go again? (y/n)" an = raw_input() if an == 'y' or an == "Y": main()
def encryption(): print "Your key: (Remember this!) " key = raw_input() print "Your password/message: " pw = raw_input() c = XOR.new(key) epw = base64.b64encode(c.encrypt(pw)) print "Your encrypted password/message is: " + epw print "Would you like to go again? (y/n)" an = raw_input() if an == 'y' or an == "Y": main()
def gen_xor_encrypt(): init = [False] key = Random.new().read(AES.block_size) cipher = XOR.new(key) def xor_encrypt(raw): if init[0] is False: init[0] = True return key + cipher.encrypt(raw) return cipher.encrypt(raw) return xor_encrypt
def __init__(self): #Buscando el archivo INI para saber la configuracion del formato de numeros self.config = ConfigParser() self.config.read("conf/config.ini") self.numsenc = self.config.get('MODEMS', 'nums') self.Cipher = XOR.new(base64.b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) self.nums = self.Cipher.decrypt(base64.b64decode(str(self.numsenc))) self.nums = self.nums.split(",") self.dictnums = {} letra = 0 for n in self.nums: self.dictnums[str(string.lowercase[letra])]=n letra = letra + 1
def xor_in_pi(text_bin): flen = int(os.stat('pi.bin')[stat.ST_SIZE]) max_start = flen - len(text_bin) some_pi = get_some_pi(max_start, qcrypt.normalize(text_bin)) xor = XOR.new(some_pi) ciphertext = xor.encrypt(text_bin) if debug: print '\n------xor_in_pi------' print qcrypt.normalize(text_bin) print qcrypt.normalize(some_pi) print qcrypt.normalize(ciphertext) print '------xor_in_pi------\n' return ciphertext
def admin_token_json(self, uuid): from hardware.model import * crypt = XOR.new(self.password) try: host_object = session.query(Host).filter_by(uuid=uuid).one() except: pass #raise ValueError("Critical: UUID Not Found - %s" % uuid) str = "%s" % (uuid[:7]) # I hate obfuscation. Its all I've got token = crypt.encrypt(str) return dict(token=urllib.quote(token), prefered_protocol=self.smolt_protocol)
def LicCheckRemote(): config = ConfigParser() config.read("conf/config.ini") LicCif = config.get('CUENTA', 'Lic') contrasena = base64.b64decode('MjAxMDE3MzMtOTYwOTkyNg==') PASSWORD = XOR.new(str(contrasena)) try: #Por si da algun error en la decodificacion LicDecif = PASSWORD.decrypt(base64.b64decode(str(LicCif))) except: LicDecif = None if str(xxmx) == str(LicDecif): return True else: return False
def initiate_session(self): # Perform the initial connection handshake for agreeing on a shared secret ### TODO: Your code here! # This can be broken into code run just on the server or just on the client if self.server or self.client: my_public_key, my_private_key = create_dh_key() # Send them our public key self.send(bytes(str(my_public_key), "ascii")) # Receive their public key their_public_key = int(self.recv()) # Obtain our shared secret shared_hash = calculate_dh_secret(their_public_key, my_private_key) print("Shared hash: {}".format(shared_hash)) # Default XOR algorithm can only take a key of length 32 self.cipher = XOR.new(shared_hash[:4])
def xorCoder(string, key): cipher = XOR.new(key) return cipher.encrypt(string)
def encrypt(plaintext, key=secret_key): cipher = XOR.new(key) return base64.b64encode(cipher.encrypt(plaintext))
def encrypt(raw, passwd): cipher = XOR.new(passwd) enc = cipher.encrypt(raw) return enc
def encrypt(text): key = XOR.new('01101001') return binascii.hexlify(key.encrypt(text))
def encrypt_message(message, receiver): cipher = XOR.new(receiver) return base64.b64encode(cipher.encrypt(message))
def decrypt(self, ciphertext): ciphertext = ciphertext.decode('utf-8') keyCipher = 'notsosecretkey' cipher = XOR.new(keyCipher) return cipher.decrypt(base64.b64decode(ciphertext))
def ConvertirDatos(stringbd, lic, cualmodo, dondebd): print 'Convirtiendo Datos' if dondebd == '1': stringbd = stringbd.replace('NOMBREPC', str(gethostname())) elif dondebd == '2': print 'Indique la direccion donde se encuentra la Base de Datos' direccionremota = raw_input( 'Indique una direccion IP o un DNS para la conexion a Base de Datos: ' ) stringbd = stringbd.replace('NOMBREPC', direccionremota) while True: print 'Indique si programara Modems' print '1 - SI' print '2 - NO' simodem = raw_input('Indique: ') numerosvalidos = [] if simodem == '1': progmodem = 1 break elif simodem == '2': progmodem = 2 break else: print 'La opcion no es valida' if progmodem == 1: while True: print 'Indique un identificador de numeros validos' num = raw_input('Indique: ') numerosvalidos.append(num) print 'Desea Programar otro identificador?' print '1 - SI' print '2 - NO' otroident = raw_input('Indique: ') if otroident == '1': pass elif otroident == '2': progotroiden = 2 break else: print 'La opcion no es valida' while True: print 'Indique el largo de los numeros telefonicos en digitos' lennums = raw_input('Indique: ') if lennums.isdigit(): break else: print 'Debe indicar un numero para el largo' print 'Programe el servidor Web' print 'Indique la direccion, recuerde tomar en cuenta colocar el puerto en caso de no ser el 80' while True: direccionweb = raw_input('Indique: ') print 'Indico la direccion: ' + str(direccionweb) print 'Desea Mantenerla?' print '1 - SI' print '2 - NO' respweb = raw_input('Indique: ') if respweb == '1': break elif respweb == '2': pass else: print 'La opcion no es valida' numpruebarapida = [] while True: print 'Indique un numero para prueba rapida de SMS' numrapid = raw_input('Indique: ') if numrapid.isdigit(): numpruebarapida.append(numrapid) else: print 'Indique un numero valido' print 'Desea agregar otro numero?' print '1 - SI' print '2 - NO' respmasnum = raw_input('Indique: ') if respmasnum == '1': pass elif respmasnum == '2': break else: print 'Indique una respuesta valida' numvalid = str(lennums) for num in numerosvalidos: numvalid = numvalid + ',' + num numsrapida = '' for numpruba in numpruebarapida: if numsrapida == '': numsrapida = numsrapida + '' + numpruba else: numsrapida = numsrapida + ',' + numpruba stringbd = stringbd.replace('NOMBREBD', 'Soluciones-SMSSecure') stringbd = stringbd.replace('USUARIOBD', 'sa') stringbd = stringbd.replace('PASSWORDBD', 'jerm') deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) stringbd = b64encode(deco.encrypt(str(stringbd))) deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) lic = b64encode(deco.encrypt(str(lic))) deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) cualmodo = b64encode(deco.encrypt(str(cualmodo))) deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) numerosvalidos = b64encode(deco.encrypt(str(numvalid))) deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) lennums = b64encode(deco.encrypt(str(lennums))) deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) numpruebarapida = b64encode(deco.encrypt(str(numsrapida))) deco = XOR.new(b64decode('MjAxMDE3MzMtOTYwOTkyNg==')) direccionweb = b64encode(deco.encrypt(str(direccionweb))) print 'Datos Convertidos' CrearArchivo(stringbd, lic, cualmodo, numerosvalidos, numpruebarapida, direccionweb)
def decrypt(key, ciphertext): cipher = XOR.new(key) return cipher.decrypt(base64.b64decode(ciphertext)).decode('utf-8')
def _cipher(): return XOR.new(settings.SECRET_KEY[:16])
def get_user_key(request, ss=None): """ Crypto join local 'key' and remote cookie or 'ss' to form strengthened password """ remote = b64decode(ss or request.COOKIES['ss']) local = b64decode(request.session['key']) return XOR.new(remote).decrypt(local)
def split_user_key(password): """ Helper to crypto split a password """ remote = os.urandom(32) local = XOR.new(remote).encrypt(strengthen_key(password)) return b64encode(remote), b64encode(local)
def decrypt(secret_key, ciphertext): cipher = XOR.new(secret_key) return cipher.decrypt(base64.b64decode(ciphertext))
def encrypt(key, plaintext): cipher = XOR.new(key) return base64.b64encode(cipher.encrypt(plaintext))
def decrypt_XOR(enckey, data): cipher = XOR.new(enckey) return cipher.decrypt(data)
from Crypto.Cipher import XOR import base64 key = "AutomateAllTheThings" encrypted = "ORoMDUBQRFNxVV9iUFFlXF9DMhFzJBU9JhQOADQLChEtHyIgPhY2OxcS" cipher = XOR.new(key) cipher.decrypt(base64.b64decode(encrypted)) API_TOKEN = cipher.decrypt(base64.b64decode(encrypted)) DEFAULT_REPLY = "Sorry but I didn't understand you"
def decrypt(ciphertext): cipher = XOR.new(password_key) return cipher.decrypt(base64.b64decode(ciphertext)).decode()
def XORDecrypt(data): key = XOR.new('01101001') return key.decrypt(binascii.unhexlify(data))
def decrypt(ciphertext, key=secret_key): cipher = XOR.new(key) return cipher.decrypt(base64.b64decode(ciphertext))
def send_file(file_name, addr, crypt, key): """ Основная функция клиента, отправка некоего файла на сервер :param file_name: имя отправляемого файла :param addr: адрес сервера :param crypt: статус шифрования :param key: ключ для XOR-шифрования :return: """ s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) s.settimeout(0.5) cipher = XOR.new(key) client_id = 1 num = 0 message = file_name.encode() if crypt: message += ' 1'.encode() else: message += ' 0'.encode() # Первый отправляемый пакет содержит имя файла и статус использования шифрования packet = create_packet(client_id, num, message) logging.info('Sending filename to server') if send_packet(s, packet, 'opened', addr): logging.info('Filename was sent to server') else: logging.error('Server is not available') print('Server is not available') return num += 1 logging.info('Sending of file started') # Получение размера файла для отображения прогресса отправления file_size = os.path.getsize(file_name) f = open(file_name, 'rb') message = f.read(SIZE - 28) all_len = 0 num_data_sent = 0 # В цикле файл читается и отправляется пакетами, попутно выводится прогресс отправки файла while message: all_len += len(message) logging.debug('Sending packet {}'.format(num)) if crypt: message = cipher.encrypt(message) packet = create_packet(client_id, num, message) if send_packet(s, packet, 'correct', addr): logging.debug('Packet {} was sent successful'.format(num)) else: logging.error('Server is not available') print('Server is not available') return num_data_sent += len(message) message = f.read(SIZE) progress = num_data_sent / file_size * 100 print('Sending progress: ' + "%.2f" % progress + '%') # Так как поле номера пакета 16-битное, а приложение может взаимодействовать с файлами, размер которых # превышает 10ГБ, номер пакета обнуляется, когда доходит до максимально-возможного 16-битного числа if num + 1 < 0xffff: num += 1 else: num = 0 # В конце отправляется пустой пакет, сигнализирующий о завершении передачи logging.debug('Sending last packet') packet = create_packet(client_id, num, b'') if send_packet(s, packet, '', addr): logging.info('File was sent to server successfully') else: logging.error('Server is not available') print('Server is not available') return
key = b'-8B key-' plaintext = b'We are no longer the knights who say ni!' nonce = Random.new().read(pycrypto_des.block_size/2) ctr = Counter.new(pycrypto_des.block_size*8/2, prefix=nonce) # ruleid:insecure-cipher-algorithm-des cipher = pycrypto_des.new(key, pycrypto_des.MODE_CTR, counter=ctr) msg = nonce + cipher.encrypt(plaintext) nonce = Random.new().read(pycryptodomex_des.block_size/2) ctr = Counter.new(pycryptodomex_des.block_size*8/2, prefix=nonce) # ruleid:insecure-cipher-algorithm-des cipher = pycryptodomex_des.new(key, pycryptodomex_des.MODE_CTR, counter=ctr) msg = nonce + cipher.encrypt(plaintext) key = b'Super secret key' plaintext = b'Encrypt me' # ruleid:insecure-cipher-algorithm-xor cipher = pycrypto_xor.new(key) msg = cipher.encrypt(plaintext) # ruleid:insecure-cipher-algorithm-xor cipher = pycryptodomex_xor.new(key) msg = cipher.encrypt(plaintext) key = b'Sixteen byte key' # ok cipher = AES.new(key, AES.MODE_EAX, nonce=nonce) plaintext = cipher.decrypt(ciphertext) try: cipher.verify(tag) print("The message is authentic:", plaintext) except ValueError: print("Key incorrect or message corrupted")
def decrypt_message(encrypted_message, receiver): cipher = XOR.new(receiver) return cipher.decrypt(base64.b64decode(encrypted_message))
def listen(key): """ Функция, в которой сервер проводит все время работы, в ней происходит обмен пакетами с клиентами :param key: ключ для XOR-шифрования :return: - """ s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) s.bind(('', PORT)) logging.info('Start working') cipher = XOR.new(key) # Открывается файл, в который будет вноситься вся информация о полученных файлах # connects - словарь вида # {адрес : (открытый файл, номер текущего пакета, информация о посылке, статус шифрования)} info = open('work_history.txt', 'a') connects = {} while True: data, address = s.recvfrom(60000) # Сервер обрабатывает только запросы if struct.unpack('b', data[20:21])[0] != ECHO_REQUEST: continue address = (socket.gethostbyname(address[0]), PORT) logging.info('Received packet from {} '.format(address[0])) packet_num = struct.unpack('H', data[26:28])[0] # Проверка корректности данных, оповещение клиента в случае некорректности if not check_correct(data): logging.debug('Corrupted data in packet') print('Data corrupted') s.sendto(create_packet(0, packet_num, 'corrupted'.encode()), address) continue # Если нет такого IP-адреса в словаре, значит не было приема данных от этого клиента if address[0] not in connects.keys(): # Пустой пакет клиент присылает последним сообщением, если при этом его не оказалось в текущих # коннектах, значит он отправлял этот пакет не один раз, выждав таймаут или получив некорректный ответ if len(data) == 28: s.sendto(create_packet(0, packet_num, b''), address) continue # Иначе создается новый файл под новое соединение, генерируется имя для этого файла # В about_file пишется информация о новом клиенте, чтобы в случае успешного сеанса записать в файл отчета file_name, crypt = (data[28:len(data)]).decode().split(' ') crypt = int(crypt) uniq_name = give_unique_name(file_name) about_file = '\nFile: {}\nSaved as: {}\nReceived from: {}\nTime: {}\n'.format( file_name, uniq_name, address[0], datetime.datetime.now()) logging.info( 'New client. Opening new file {} for acceptance'.format( uniq_name)) connects[address[0]] = [ open(uniq_name, 'wb'), 0, about_file, crypt ] # Даем права доступа другим пользователям к получаемому файлу os.chmod(uniq_name, 0o777) s.sendto(create_packet(0, packet_num, 'opened'.encode()), address) # Ловится всегда следующий пакет elif packet_num == connects[address[0]][1] + 1 or connects[ address[0]][1] + 1 == 0xffff and packet_num == 0: # Пустой пакет от клиента означает завершение передачи. Связи обрываются, информация пишется в файл отчета. if len(data) == 28: logging.info('Received end of file. Closing file') s.sendto(create_packet(0, packet_num, b''), address) item = connects.pop(address[0]) item[0].close() print( '\nNew file received.\nInformation, that will be written in work_history.txt:{}' .format(item[2])) info.write(item[2]) # Иначе просто обновляется счетчик пакетов, дописывается принимаемый файл else: logging.debug('Correct data in packet') connects[address[0]][1] = packet_num message = data[28:len(data)] if connects[address[0]][3]: message = cipher.decrypt(message) connects[address[0]][0].write(message) packet = create_packet(0, packet_num, 'correct'.encode()) s.sendto(packet, address) # Клиент может прислать один и тот же пакет несколько раз, если до него не дошел или дошел некорректно # ответ сервера о получении пакета, в таком случае отправляется сообщение "again" elif packet_num == connects[address[0]][1]: logging.debug('again') s.sendto(create_packet(0, packet_num, 'again'.encode()), address)
def decrypt_plaq(key, ciphertext): cipher = XOR.new(key) return cipher.decrypt(base64.b64decode(ciphertext))
def encrypt(self, msg): keyCipher = 'notsosecretkey' cipher = XOR.new(keyCipher) return base64.b64encode(cipher.encrypt(msg))
def encrypt(plaintext): cipher = XOR.new(password_key) return base64.b64encode(cipher.encrypt(plaintext)).decode()
def decrypt_XOR(enckey, data): cipher = XOR.new(enckey) # set the cipher return cipher.decrypt(data) # decrpyt the data
def _xor(self, a, b): if len(a) != len(b): raise "ERROR: Strings are of different size! %s %s" % (len(a), len(b)) xor = XOR.new(a) return xor.encrypt(b)
def encrypt(key, plaintext): #last_el = int(plaintext[plaintext.rfind('_')+1:]) #encoded_last = base62.encode(last_el) #plaintext = plaintext[:plaintext.rfind('_') cipher = XOR.new(key) return base64.b64encode(cipher.encrypt(plaintext)).decode('utf-8')
def XOREncrypt(data): key = XOR.new('01101001') return binascii.hexlify(key.encrypt(data))
def decrypt(raw, passwd): cipher = XOR.new(passwd) dec = cipher.decrypt(raw) return dec