Itarate password combinations to find key for string - python

I´m having problems to brute force the key for a string encrypted with RC4/ARC4.
This is the encrypted string:
E7Ev08_MEojYBixHRKTKQnRSC4hkriZ7XPsy3p4xAHUPj41Dlzu9
And the string is also hashed with base64, so complete encoded string is:
RTdFdjA4X01Fb2pZQml4SFJLVEtRblJTQzRoa3JpWjdYUHN5M3A0eEFIVVBqNDFEbHp1OQ==
#-*- coding: utf-8 -*-
import threading
import sys
import time
import re
import itertools
from itertools import product
from Crypto.Cipher import ARC4
import base64
def special_match(strg):
try:
strg.decode('utf-8')
except UnicodeDecodeError:
pass
else:
print('\nkey found at %s, key: %s' % (time.ctime(), rc4_key))
try:
f=open('key.txt','ab')
f.write('Key (%s): %s\n' % (time.ctime(), rc4_key))
f.write('Decrypted string: ' + strg + '\n')
f.close()
except Exception as e:
print('ERROR WRITING KEY TO FILE: ' + str(e))
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
end_chars = chars[::-1][0:7]
encoded_string = 'RTdFdjA4X01Fb2pZQml4SFJLVEtRblJTQzRoa3JpWjdYUHN5M3A0eEFIVVBqNDFEbHp1OQ=='
spinner = itertools.cycle(['-', '/', '|', '\\'])
while 1:
try:
# Iteration processess of possibel keys
for length in range(7,8): # only do length of 7
for attempt in itertools.permutations(chars, length):
rc4_key = ''.join(attempt) # This key is unknown, we are looking for it..
Ckey = ARC4.new(rc4_key)
decoded = Ckey.decrypt(encoded_string.decode('base64'))
special_match(decoded)
sys.stdout.write(spinner.next()) # write the next character
sys.stdout.flush() # flush stdout buffer (actual character display)
sys.stdout.write('\b') # erase the last written char
# Exit the script when we have done all password-combination-iterations
if (rc4_key == end_chars):
print('iteration of combinations done! No key found.. :(\n' + time.ctime())
exit()
except KeyboardInterrupt:
print('\nKeybord interrupt, exiting gracefully anyway on %s at %s' % (rc4_key, time.ctime()))
sys.exit()
I´m using http://crypo.bz.ms/secure-rc4-online to encrypt the string and https://www.base64encode.org to encode it with UTF-8.
Question
Why doesn't my script work to find the key?
(Im not receiving any error message, it is more of a general question if I have missed something in my code, or approach of the problem.)
plaintext: This is something that I have encrypted, key: ABCFMSG

Alright, it seems that crypo.bz uses a realy weird system. Basically they have a really weird encoding which causes discrepancies if you simply use their characters.
For example encoding 'a' with key 'A' should produce a character with value 163.
In hex A3. In crypo.bz we get 'oc' instead.
So you have two possibilities. Either do some ciphertext analysis or use another site. I recommend this one as they tell you in what they encode the result:
http://www.fyneworks.com/encryption/RC4-Encryption/index.asp
Take the hex and convert it to string, the you should be able to decipher it
Your code seems to be working by the way ;)
Tell me if you have additional questions
EDIT: did some additional analysis, and it is really, really weird.
in crypo.bz IF the algorithm is correct 163 is oc
160 is nc
but 161 is mc ??
If anyone figures this out please tell me!
EDITEDIT:
here is the encrypted, but not encoded string '#ÔèïH§¢6pbpÊ]õªœIôŒ>Yœ5îfäGuæxÖa…ë6°'
Your program takes like half a second to find the key ;)

Related

python writing current window to file and encoding file

I am trying to write the current window to a file. Problem with the code is that it must use an encoding (utf-8) otherwise if a window gets openened like outlook with windowname: Inbox - Outlook ‎- Mail it gives the following error:
UnicodeEncodeError: 'charmap' codec can't encode character '\u200e' in
position 16: character maps to
But when using the utf-8 encoded file, it can not be encoded into base64, this gives the following error(of course):
ValueError: string argument should contain only ASCII characters
Is there a way to encode or encrypt this file(I've used rot-13 which worked and md5 but this didnt work well with reading and decrypting). Or to make the output of q = w.GetWindowText (w.GetForegroundWindow()) not in 'utf-8'.
code:
import win32gui
import time
import psutil
import win32process
i = 0
while i <= 1:
time.sleep(2)
w=win32gui
q = w.GetWindowText (w.GetForegroundWindow())
q =str(q)
print(q)
pid = win32process.GetWindowThreadProcessId(w.GetForegroundWindow())
print(psutil.Process(pid[-1]).name())
with open("lolp.txt",'w',encoding='utf-8')as f:
f.write(q)
As far as I can tell you need to remove non-ascii symols from q. It can be done in many ways. For example:
import win32gui
q = win32gui.GetWindowText(win32gui.GetForegroundWindow())
def remove_non_ascii(char):
return 32 <= ord(char) <= 126
q = filter(remove_non_ascii, q)
print("".join(list(q)))
Here are another solutions: How can I remove non-ASCII characters but leave periods and spaces?

Base64 encoding of password string in python

I came across following code to decode a password string, for example my password string is 'samplepassword', i can encode this using base64 algorithm and i got the below encoded value. I just used https://io/Utils/Base64/ to find encoded value.
"c2FtcGxlcGFzc3dvcmQ="
Below code hides the exact password of mine which is 'samplepassword', but anyone using the encodedvalue can easily find the original password using the same https://io/Utils/Base64/.
I'm confused in understanding what security base64 module providing, and Please suggest some best practices to hide the password in the python code.
def decode(encoded_value):
try:
import base64
try:
decoded_value = base64.b64decode(encoded_value).decode('ascii')
return decoded_value
except TypeError as e:
raise TypeError("Attempted to decode {value} once. Illegal Value. ".format(value=encoded_value))
except ImportError:
raise ImportError("Base64 import failed")
print(decode('c2FtcGxlcGFzc3dvcmQ='))

Brute-force cracking SHA-512 passwords in unix password file

I have a school assignment which consists of me having to crack a unix password file, the passwords were created using SHA-512,
I'm using python3, to write my password cracking script, which goes through a password file, adds the salt and compares each password until the hash is found.
Here is my code:
#!/usr/bin/env python3
import crypt
passFile = open('passwords.txt', 'r')
salt_MD5 = []
hash_MD5 = []
salt_SHA512 = []
hash_SHA512 = []
for line in passFile:
if "$6$" in line:
temp1 = line.split(":")
temp1 = temp1[1]
salt_SHA512.append(temp1[:11])
hash_SHA512.append(temp1)
if "$1$" in line:
temp1 = line.split(":")
temp1 = temp1[1]
salt_MD5.append(temp1[:11])
hash_MD5.append(temp1)
print(salt_MD5, hash_MD5)
print(salt_SHA512, hash_SHA512)
crackStation = open('1000000passwords.txt', 'r')
print("Searching for the password...")
counter = 0
for index in crackStation:
counter += 1
hashed_value_1 = crypt.crypt(index, salt_MD5[0])
hashed_value_2 = crypt.crypt(index, salt_MD5[1])
hashed_value512_1 = crypt.crypt(index, salt_SHA512[0])
hashed_value512_2 = crypt.crypt(index, salt_SHA512[1])
if counter % 50000 == 0:
print("Counter is at: " + str(counter) + " Left to iterate = " + str(1000000-counter))
# if hashed_value_1 == hash_MD5[0]:
# password_1 = index
# print("User one has been cracked password is: " + password_1)
# if hashed_value_2 == hash_MD5[1]:
# password_2 = index
# print("User two has been cracked password is: " + password_2)
if hashed_value512_1 == hash_SHA512[0]:
password_3 = index
print("User one has been cracked using password: " + password_3)
if hashed_value512_2 == hash_SHA512[1]:
password_4 = index
print("User one has been cracked using password: " + password_4)
print("Search Complete.")
try:
print(password_1, password_2, password_3, password_4)
except Exception as e:
print("Oh shit something went wrong :s" + e)
Please disregard the MD5, salt and hash, as that I will deal with later (professor claimed that some of the passwords in the file would be crackable and a fellow student confirmed that he was able to crack both the SHA-512 passwords therefore I commented the MD5 out for the sake of speed)
I'm curious to see WHAT type of encoding I should be using to read from the password file, So far I've tried 'mac_roman', to iterate through the dictionary file, and now I just didn't set an encoding, I'm assuming the default should be UTF-8, but I honestly don't know how to check to confirm.
If anyone has any suggestions on what I can do to get this working I'd really appreciate it!
(I'm attempting the default encoding right now, by not initializing one
crackStation = open('1000000passwords.txt', 'r')
)
If in the case that, that does in fact work I will let you know!
Additonal question:
Could someone tell me what the encoding would be for this password file,
adamkaplan:$6$S4Y0gQuy$QRkLo5t/6KONMAiQY9DIAPojv0Q8CBvDtNqe02sfR7rnEdw.QgSm0LU/JRcIc/Arn/PpK3lxroc19bVQDwUGQ/:17786:0:99999:7:::
cardib:$6$t84.Fvbo$8lKHpxBDnjoHhnFS3.A4ezNZmKfy5MLbe7UGZoOnWgz55j0g5TBx5LOQAujDiqkUuE50EACOZsydlBZgy5jkw/:17786:0:99999:7:::
the password hash isn't BASE64, and the reason I'm asking is because when I use different encodings within a dictionary file each encoding gives a different hash, so that's what is throwing me off, the fact that if I use UTF-8, I will receive a different hash verses latin-1
So what encoding would linux password file be using by default.
If I create a new linux account through the terminal and set a password and go back inside my password file I will have a newly made hash for that new usernames password, and the encoding that was used within that hashing algorithm is what I Would need, or atleast that's what I image would need in order to crack the password.
Hope that isn't too confusing :s
I'm curious to see WHAT type of encoding I should be using to read from the password file
You should be using the encoding that the file is encoded in.
Unfortunately, it is impossible in general to tell the encoding of a file from just the file, you need some additional out-of-band information such as a header in the file telling you the encoding, the transmission format telling you the encoding … or just asking the author of the file.
However, since the passwords in the encrypted database are most likely treated as octet streams, it might make sense to treat the password dictionary the same way.
I honestly don't know how to check to confirm.
Use iconv. It'll fail when trying to convert a file containing malformed characters.
Here are some test files:
printf 'ascii only\n' > ascii_only.txt
printf 'utf-8 \342\230\272\n' > utf8.txt
printf 'latin1. pi\361ata.\n' > latin1.txt
Here are some examples:
$ iconv -f utf-8 -t utf-8 < utf8.txt > /dev/null && echo "ok"
ok
$ iconv -f ascii -t utf-8 < utf8.txt > /dev/null && echo "ok"
iconv: illegal input sequence at position 6
$ iconv -f utf-8 -t utf-8 < latin1.txt > /dev/null && echo "ok"
iconv: illegal input sequence at position 10
You can try ASCII, UTF-8 and Latin1 (in that order), and use whichever encoding iconv accepts first.
Even if this wasn't a school assignment, you could realistically expect most passwords to be ASCII.
The solution that worked out for me, the reason I wasn't able to crack the passwords were because I failed to strip the new lines from the dictionary words,
simply doing a
line = line.rstrip()
solved my problem, I didn't need to do any type of encoding or anything to have the file work.

Issues when decrypting data received from GET python

I am developing a new payment_acquirer module for Odoo, and since last week, I am always getting an error when I try to decrypt data that I received through the server.
When I copy the data in an another python file to test, it seems to be working perfectly with the same data, but when I do it in my controller, it returns an error.
This is the code inside my controller :
#http.route('/payment/ariarynet/result', type='http', auth="none", methods=['POST', 'GET'], csrf=False)
def ariarynet_result(self, **post):
""" Handle Ariary.net response and redirect to form_validate"""
_logger.info('Beginning Ariary.net form_feedback with post data %s', pprint.pformat(post)) # debug
key = bytes("477c3551da64136491eff1cb6ab27be35093b2512eb78f2c8d"[:24])
params = dict(post)
raw = b"%s"%post.get('idpanier')
decode = raw.encode('utf8')
idpanier = main.Utils().decrypt(key,decode) #it return an error
When executed, I have the following error:
raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.")
ValueError: Invalid data length, data must be a multiple of 8 bytes
I am using pyDes module to crypt and decrypt data.
This is the test that is working :
def test_bytes(self):
key = bytes("477c3551da64136491eff1cb6ab27be35093b2512eb78f2c8d"[:24])
expect = "12177"
raw = "%8E%16%B8n%A6%1F%2Fj" #this is the data that I copied from the url
text = urllib.unquote(raw)
byteArray = bytes(text)
print Utils().decrypt(key, text)
self.assertEqual(expect,Utils().decrypt(key, text), "%s est diférent de %s" % (expect, Utils().decrypt(key, text)) )
I really need your help to figure out what am I doing wrong.
Update:
I think that the probleme have to do with the character encoding, because when I am trying to compare the data I get with the excpected one, I don't get the same thing:
param = post.get('idpanier')
text = (param.encode('utf8'))
print "utf8 encode %s, hex encoded text %s" % (text, text.encode('hex'))
print "utf8 encode %s, hex encoded text %s" % ("b4227475d651420b".decode('hex'), "b4227475d651420b") #excpected behavior
Here is the output:
utf8 encode �"tu�QB
, hex encoded text efbfbd227475efbfbd51420b
utf8 encode �"tu�QB
, hex encoded text b4227475d651420b
The solution I found : instead of retriving parameters with post.get(), I have manage to get the real parameters data through the incoming url directly, where parameters encoding is not changed yet.
query = parse_qs("http://url?%s"%request.httprequest.query_string) #append the query string to a dummy url to get a well formed url
param = query.get('idpanier')
After that, everything worked fine.

How can I understand this python error message?

Hi can you help me decode this message and what to do:
main.py", line 1278, in post
message.body = "%s %s/%s/%s" % (msg, host, ad.key().id(), slugify(ad.title.encode('utf-8')))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
Thanks
UPDATE having tried removing the encode call it appears to work:
class Recommend(webapp.RequestHandler):
def post(self, key):
ad= db.get(db.Key(key))
email = self.request.POST['tip_email']
host = os.environ.get("HTTP_HOST", os.environ["SERVER_NAME"])
senderemail = users.get_current_user().email() if users.get_current_user() else 'info#monton.cl' if host.endswith('.cl') else 'info#monton.com.mx' if host.endswith('.mx') else 'info#montao.com.br' if host.endswith('.br') else 'admin#koolbusiness.com'
message = mail.EmailMessage(sender=senderemail, subject="%s recommends %s" % (self.request.POST['tip_name'], ad.title) )
message.to = email
message.body = "%s %s/%s/%s" % (self.request.POST['tip_msg'],host,ad.key().id(),slugify(ad.title))
message.send()
matched_images=ad.matched_images
count = matched_images.count()
if ad.text:
p = re.compile(r'(www[^ ]*|http://[^ ]*)')
text = p.sub(r'\1',ad.text.replace('http://',''))
else:
text = None
self.response.out.write("Message sent<br>")
path = os.path.join(os.path.dirname(__file__), 'market', 'market_ad_detail.html')
self.response.out.write(template.render(path, {'user_url':users.create_logout_url(self.request.uri) if users.get_current_user() else users.create_login_url(self.request.uri),
'user':users.get_current_user(), 'ad.user':ad.user,'count':count, 'ad':ad, 'matched_images': matched_images,}))
The problem here is your underlying model (message.body) only wants ASCII text but you're trying to give it a string encoded in unicode.
But since you've got a normal ascii string here, you can just make python print out the '?' character when you've got a non-ascii-printing string.
"UNICODE STRING".encode('ascii','replace').decode('ascii')
So like from your example above:
message.body = "%s %s/%s/%s" % \
(msgencode('ascii','replace').decode('ascii'),
hostencode('ascii','replace').decode('ascii'),
ad.key().id()encode('ascii','replace').decode('ascii'),
slugify(ad.title)encode('ascii','replace').decode('ascii'))
Or just encode/decode on the variable that has the unicode character.
But this isn't an optimal solution. The best idea is to make message.body a unicode string. Being that doesn't seem feasible (I'm not familiar with GAE), you can use this to at least not have errors.
You've got a Unicode character in a place that you're not supposed to. Most often I find this error is having MS Word-style slanted quotes.
One of these fields has some characters that cannot be encoded. If you switch to python 3 (it has better unicode support), or you change the encoding of the entire script the problem should stop, about the best way to change the encoding in 2.x is using the encoding comment line. If you see http://evanjones.ca/python-utf8.html you will see more of an explanation of using python with utf-8 support the best suggestion is add # -*- coding: utf-8 -*- to the top of your script. And handle scripts like this
s = "hello normal string"
u = unicode( s, "utf-8" )
backToBytes = u.encode( "utf-8" )
I had a similar problem when using Django norel and Google App Engine.
The problem was at the folder containing the application. Probably isn't this the problem described in this question, but, maybe helps someone don't waste time like me.
Try first change you application folder maybe to /home/ and try to run again, if doesn't works, try something more.

Categories

Resources