Python XOR Encryption program sometimes doesn't work - python

I am trying to make a simple xor encryption program in python and what I have now is working almost fine, only sometimes it doesn't and I just can't figure out why. For example, if I input 'hello' and the key '1234' it will encrypt it to YW_X^ and if I then decrypt this with the same key it will print 'hello'. But if I change the key to 'qwer' the encrypted message is something like '^Y^R ^^^^' and if I try to decrypt it, 'heERQWERoi' comes out.
This is the code:
from itertools import cycle, izip
choice = int(raw_input('Press 1 to encrypt, 2 to decrypt. '))
if choice == 1:
message = raw_input('Enter message to be encrypted: ')
privatekey = raw_input('Enter a private key: ')
encrypted_message = ''.join(chr(ord(c)^ord(k)) for c,k in izip(message, cycle(privatekey)))
print 'Encrypted message:'
print encrypted_message
elif choice == 2:
todecrypt = raw_input('Enter a message to be decrypted: ')
otherprivatekey = raw_input('Enter the private key: ')
decrypted_message = ''.join(chr(ord(c)^ord(k)) for c,k in izip(todecrypt, cycle(otherprivatekey)))
print 'Decrypted message:'
print decrypted_message
I have no idea what is wrong with it so I would really appreciate some help, thank you!

It's probably working fine, but you are getting characters which you may not be able to re-input into your terminal directly as they don't correspond to the ordinarily inputtable ASCII characters. In particular, with the key qwer, the values of ord become [25, 18, 9, 30, 30], which you may have a hard time inputting (cf. this table).
The similar problem will not occur if you use 1234 as a key as in that case the values are [89, 87, 95, 88, 94] which correspond to "normal" characters.

Your script is printing non-printing characters, which sometimes can't be copy/pasted. You could encode the ciphertext into a format that uses only the characters abcdef0123456789, which lets you display it without issue:
print encrypted_message.encode('hex')
You can then decode it when the user types it in once more:
todecrypt = raw_input('Enter a message to be decrypted: ').decode('hex')

Related

Why does map function return None?

I'm trying to code another encrypter, I'm having problems with the decoding process.
I've read a lot of StackOverflow's questions about this argument, I alredy know that someone is going to mark this question as a duplicate but I'm writing this because I can't find a solution to my problem.
The encode function gives me this string
4697625275273471234347364527724769
That is the encoded message (it says 'Hello world!') and I have the 'Key' (randomly generated every time I start the program), that cointains the combiantions of numbers needed to decode the message.
Here is the key
12040512030417060213060413030716060915090216080313040713060215090916020217020419040215050918070812050414030615020715020512061602071404091407041805160407170516030919090718050315070618020719070218050812030317020918060815070817020816040318080414060914060414050419030818030513020419030517040912040218020918030616050313050413040319070618020617060518060314090616070612080615060613020912040413070619070918050217040512070813020816020513090812090218080715020317050217050313070419020717090712060814020816030518040317030616050915020215030516050518080314040619060815030816020613040518080817060913070312080316050717020714070212090915090812090517030916060218091905051608071904041303021209031606081707051209081908041302051808021602081202041508031708041204031608041504031708051307051908081405091809051207091408061805061806021306061902021805041706081902061303031606051803091309061202031504061702021206091402091604041906041709091609061506081908091707021604061604081309051508091905041903031903071202021705061409091205091803071409041505071204061709041909091209061409051309041707031207041709061704021804051907071703031707091605081907051506041308051305071407031708031607021902051802051705041209071909081709051804041804091403021503031507071208051307021507041806051404031904031903061208041607031204071609091904091809031807031206041308091907041908031809071704031807071909021209041509071304041804071309071707061603081305051606031304021208071908021407081803021807021406071808051602041502061903091205051508051206031803081802021503061602031403081403091909061409081703021606071504051609041409031504021308021509051905031206071605021206051507021408021402061907031502041705091504081308081207051902091704061603071503041202061605061303091507091408041906091608061609081504041706071205021405021603041303041305031607081403051703041406061304081306071308061307081602091207061203091403071503091202051607041308071506021407071803031305021309031805091203061906051406031304061704071207071706031508061206021709021404051403041508071704041203071403031306081705051709081708061706041207031909031309091507031708021404041704081702031404071307071203051409071
it's a bit long.
And now that I have the parameters you need to put them in the decoder
input_text = input('Encrypted MSG\n> ')
key = input('Key\n> ')
alphabet = list(" qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890èéòç#à°#ù§[]+*,;.:-_<>£$₽%&()=?ì^/|!ėëęēêĖËĘĒÉÈÊūûüúŪÛÜÚÙīïįíìîĪÏĮÍÌκōøõœöôóŌØÕŒÖÓÒãåāáâäæÃÅĀªÀÁÂÄÆßẞÇñÑ¥¢∆¶×÷π√•`~©®™✓йцукенгшщзхфывапролджэячсмитьбюЙЦУКЕНГШЩЗХФЫВАПРОЛДЖЭЯЧСМИТЬБЮ⌂☻‼‰╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤▬╥╙╘╒╓╫╪┘┌¤█▄▌▐▀αΣσ░▒▓│┤╡╢╖╕╣║╗╝¿þ¼½¾ⁿ⌠⌡≤≥±≡∩∞ΘΩð«»⌐¬¨↨↑↓→←↔₧☼♥♦♣♠♂♀♪◘○◙►◄▲▼Þ‘’“”„☭卐")
key = key.replace('0', '')
key = key.replace('1', ' ')
key = key.split()
key.insert(0,'1')
charmap = zip(key, alphabet)
_map = dict(charmap)
output_text = ''.join(str(_map.get(c)) for c in input_text)
print(f'Output\n> {output_text}')
The output [ACTUAL]
Encrypted MSG
> 4697625275273471234347364527724769
Key
> 12040512030417060213060413030716060915090216080313040713060215090916020217020419040215050918070812050414030615020715020512061602071404091407041805160407170516030919090718050315070618020719070218050812030317020918060815070817020816040318080414060914060414050419030818030513020419030517040912040218020918030616050313050413040319070618020617060518060314090616070612080615060613020912040413070619070918050217040512070813020816020513090812090218080715020317050217050313070419020717090712060814020816030518040317030616050915020215030516050518080314040619060815030816020613040518080817060913070312080316050717020714070212090915090812090517030916060218091905051608071904041303021209031606081707051209081908041302051808021602081202041508031708041204031608041504031708051307051908081405091809051207091408061805061806021306061902021805041706081902061303031606051803091309061202031504061702021206091402091604041906041709091609061506081908091707021604061604081309051508091905041903031903071202021705061409091205091803071409041505071204061709041909091209061409051309041707031207041709061704021804051907071703031707091605081907051506041308051305071407031708031607021902051802051705041209071909081709051804041804091403021503031507071208051307021507041806051404031904031903061208041607031204071609091904091809031807031206041308091907041908031809071704031807071909021209041509071304041804071309071707061603081305051606031304021208071908021407081803021807021406071808051602041502061903091205051508051206031803081802021503061602031403081403091909061409081703021606071504051609041409031504021308021509051905031206071605021206051507021408021402061907031502041705091504081308081207051902091704061603071503041202061605061303091507091408041906091608061609081504041706071205021405021603041303041305031607081403051703041406061304081306071308061307081602091207061203091403071503091202051607041308071506021407071803031305021309031805091203061906051406031304061704071207071706031508061206021709021404051403041508071704041203071403031306081705051709081708061706041207031909031309091507031708021404041704081702031404071307071203051409071
Output
> NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNoneNone
The output [EXPECTED]
Encrypted MSG
> 4697625275273471234347364527724769
Key
> 12040512030417060213060413030716060915090216080313040713060215090916020217020419040215050918070812050414030615020715020512061602071404091407041805160407170516030919090718050315070618020719070218050812030317020918060815070817020816040318080414060914060414050419030818030513020419030517040912040218020918030616050313050413040319070618020617060518060314090616070612080615060613020912040413070619070918050217040512070813020816020513090812090218080715020317050217050313070419020717090712060814020816030518040317030616050915020215030516050518080314040619060815030816020613040518080817060913070312080316050717020714070212090915090812090517030916060218091905051608071904041303021209031606081707051209081908041302051808021602081202041508031708041204031608041504031708051307051908081405091809051207091408061805061806021306061902021805041706081902061303031606051803091309061202031504061702021206091402091604041906041709091609061506081908091707021604061604081309051508091905041903031903071202021705061409091205091803071409041505071204061709041909091209061409051309041707031207041709061704021804051907071703031707091605081907051506041308051305071407031708031607021902051802051705041209071909081709051804041804091403021503031507071208051307021507041806051404031904031903061208041607031204071609091904091809031807031206041308091907041908031809071704031807071909021209041509071304041804071309071707061603081305051606031304021208071908021407081803021807021406071808051602041502061903091205051508051206031803081802021503061602031403081403091909061409081703021606071504051609041409031504021308021509051905031206071605021206051507021408021402061907031502041705091504081308081207051902091704061603071503041202061605061303091507091408041906091608061609081504041706071205021405021603041303041305031607081403051703041406061304081306071308061307081602091207061203091403071503091202051607041308071506021407071803031305021309031805091203061906051406031304061704071207071706031508061206021709021404051403041508071704041203071403031306081705051709081708061706041207031909031309091507031708021404041704081702031404071307071203051409071
Output
> Hello world!
The debug that I made with Visual Studio Code show that the problem is the map function
Can you help me please?
Thanks
You read one by one digit on the Encrypted message.
So if you have a 4 on your encrypted message to find 4 on the map you need to have 141 on your key due to the processing you do on your key.
In your exemple you dont have 141 on your generated key thats why you get None.
I change the key to use
12141512030417060213060413030716060915090216080313040713060215090916020217020419040215050918070812050414030615020715020512061602071404091407041805160407170516030919090718050315070618020719070218050812030317020918060815070817020816040318080414060914060414050419030818030513020419030517040912040218020918030616050313050413040319070618020617060518060314090616070612080615060613020912040413070619070918050217040512070813020816020513090812090218080715020317050217050313070419020717090712060814020816030518040317030616050915020215030516050518080314040619060815030816020613040518080817060913070312080316050717020714070212090915090812090517030916060218091905051608071904041303021209031606081707051209081908041302051808021602081202041508031708041204031608041504031708051307051908081405091809051207091408061805061806021306061902021805041706081902061303031606051803091309061202031504061702021206091402091604041906041709091609061506081908091707021604061604081309051508091905041903031903071202021705061409091205091803071409041505071204061709041909091209061409051309041707031207041709061704021804051907071703031707091605081907051506041308051305071407031708031607021902051802051705041209071909081709051804041804091403021503031507071208051307021507041806051404031904031903061208041607031204071609091904091809031807031206041308091907041908031809071704031807071909021209041509071304041804071309071707061603081305051606031304021208071908021407081803021807021406071808051602041502061903091205051508051206031803081802021503061602031403081403091909061409081703021606071504051609041409031504021308021509051905031206071605021206051507021408021402061907031502041705091504081308081207051902091704061603071503041202061605061303091507091408041906091608061609081504041706071205021405021603041303041305031607081403051703041406061304081306071308061307081602091207061203091403071503091202051607041308071506021407071803031305021309031805091203061906051406031304061704071207071706031508061206021709021404051403041508071704041203071403031306081705051709081708061706041207031909031309091507031708021404041704081702031404071307071203051409071
It finds w for 4 which is the result intended.
Best regards

How to decrypt Cisco Passwords type 7 using Python?

I'm trying to crack some cisco type 7 passwords, and so far, I did good realising the decryption algorithm described in the following exploit:
http://pen-testing.sans.org/resources/papers/gcih/cisco-ios-type-7-password-vulnerability-100566
#Cisco password 7 constant is : "tfd;kfoA,.iyewrkldJKD", len = 21
CONSTANT = "tfd;kfoA,.iyewrkldJKD"
encoded_password = input('Enter a type-7 CISCO password: ').strip()
salt = int(encoded_password[:2], 16)
salt_ascii = ord(CONSTANT[salt - 1])
decoded = ''
i = 2
while i< len(encoded_password):
encoded_char_int= int(encoded_password[i:i+2], 16)
decoded+= '%c'%(salt_ascii ^ encoded_char_int)
salt+=1
if salt == 22:
salt = 1
salt_ascii = ord(CONSTANT[salt - 1])
i+=2
print(decoded)
It is stated that passwords type 7 have a common salt constant that loop through which is :
CONSTANT = "tfd;kfoA,.iyewrkldJKD"
I successfully cracked passwords like: 0702385c4f1a0a1218000f5f527f
which is : mypassword365
However mypassword3651 could not get decrypted for a reason, that the password is long enough in a way that salt reaches the end of "tfd;kfoA,.iyewrkldJKD", and then I don't know what to do, do I have to loop through it again ?
I tried looping though again, but decryption is falty,
if salt == 22:
salt = 1
#mypasswordH
I tied getting to first position like the following :
salt = int(encoded_password[:2], 16)
first_pos = salt
.
.
.
.
if salt == 22:
salt = first_pos
None of the above trials were successful,
So my problem here is really with the decryption mechanism, in a simpler way, when the two first digits of the encrypted password are characters in the beggining of "tfd;kfoA,.iyewrkldJKD" eg t or f or d, there is no problem (the password is generally less than 21 chars and the program works), however if the 2 first digits are character are in the end of "tfd;kfoA,.iyewrkldJKD" like d or J or K or D, I run out of salts and the password gets decrypted partially, first half correct, and second false.
Any ideas ?
Thanks

How to 'encrypt' a file

Just trimmed this down big time
I have an overall assignment that must read a file, encrypt it and then write the encrypted data to a new file.
what i've tried is this:
filename=input("Enter file name:")
fr=open(filename)
keep_going=0
data = fr.readline()
fw=open('encrypted_file.txt', 'w')
for x in range(len(data)):
fw.write(data[x])
fw.close()
fr.close()
If your goal is just to exchange the letters in a string with others that you specify, then the solution is the following:
decrypted = 'abcdefghijklmnopqrstuvwxyz' #normal alphabet
encrypted = 'MNBVCXZLKJHGFDSAPOIUYTREWQ' #your "crypted" alphabet
#Encription
text = 'cryptme' #the string to be crypted
encrypted_text = ''
for letter in text:
encrypted_text += encrypted[decrypted.find(letter)]
print encrypted_text
#will print BOWAUFC
#Decription
text = encrypted_text #"BOWAUFC" in this example
decrypted_text = ''
for letter in text:
decrypted_text += decrypted[encrypted.find(letter)]
print decrypted_text
#will print cryptme
Note that your "crypted alphabet" do not convert any white space or any symbols but the lowercase letters, if you have other symbols in your text you have to include them as well.
However, this is not the proper way to encrypt anything! As suggested by others already, look up for a proper encryption algorithm.
I would suggest you look into Simple Crypt, this all depends on the level of security you want.
If I understand your question enough, Simple Crypt should do the job that you need.
https://pypi.python.org/pypi/simple-crypt
Here's a very simple implementation of the Vigenère Cipher I made:
from string import ascii_uppercase as alphabet
val = {}
for x in xrange(len(alphabet)):
val[alphabet[x]] = x
val[x] = alphabet[x]
encrypt = lambda a, b: ''.join(val[(val[a[i]]+val[b[i%len(b)]])%26] for i in xrange(len(a)))
decrypt = lambda a, b: ''.join(val[(val[a[i]]-val[b[i%len(b)]])%26] for i in xrange(len(a)))
Where a is the message and b is the key (I know it's written a bit tersely, but it was for a code golf competition). There are plenty of ciphers out there; you don't have to use this one, and probably shouldn't. It is just meant to get you thinking about possible ways to go about doing this. A very simple cipher that I think is good for your purposes is the Caesar Cipher.
One other thing that I'd like to point out is that your code doesn't look to modular -- one of your teacher's requirements -- right now. I'd recommend breaking it down to a function to open a file, a function to perform the actual **cryption, and a "main" function to take the user's input and call the other functions.
Best of luck to you!

There appears to be a bug in my XOR encryption program written in python

I have been trying to write a simple encryption program in Python, and when I try to execute the code on Linux, it is not printing anything. Could someone please tell me why?
#!/usr/bin/env python2
import binascii
def encrypt():
text = raw_input("Please input your information to encrypt: ")
for i in text:
#Convert text into a binary sequence
i = bin(int(binascii.hexlify(i),16))
key = raw_input("Please input your key for decryption: ")
for j in key:
#Convert key into a binary sequence
j = bin(int(binascii.hexlify(j),16))
#This is only here for developmental purposes
print key
print text
Edit
I did what one of the users said, but my code still does not seem to be converting my plain text into binary like I want it too.
#!/usr/bin/env python2
def encrypt():
text = raw_input("Please input your information to encrypt: ")
for i in text:
#Convert text into a binary sequence
i = bin(ord(i))
key = raw_input("Please input your key for decryption: ")
for j in key:
#Convert key into a binary sequence
j = bin(ord(j))
#This is only here for developmental purposes
print key
print text
encrypt()
There are a number of major problems with your program:
You are defining a function called encrypt(), but never calling it.
Neither of your loops actually modifies the string. They modify loop variables, which are not the same thing!
int(binascii.hexlify(x), 16) is an overcomplicated way of writing ord(x).
bin() does not do what you are hoping for here.
Nothing is actually being XORed here. Your program is unfinished.
I think this is what you're trying to do
def encrypt():
cleartext = raw_input("Please input your information to encrypt: ")
ciphertext = []
for char in cleartext:
ciphertext.append(bin(ord(char))[2:])
ciphertext = ''.join(ciphertext)
key = raw_input("Please input your key for decryption: ")
decryptionKey = []
for char in key:
decryptionKey.append(bin(ord(char))[2:])
decryptionKey = ''.join(decryptionKey)
print "The key is '%s'" %decryptionKey
print "The encrypted text is '%s'" %ciphertext

How do I make this only print the last value?

I have the fallowing code to encrypt a massage:
massage= raw_input("Enter message to be encrypted: ")
spec = chr(0b1010101)
key = ord(spec)
encrypt = ""
for i in range(0, len(massage)):
encrypt = encrypt + chr(ord(massage[i]) ^ key)
print encrypt
say I give "yo yo" to it
it will give me :
,
,:
,:u
,:u,
,:u,:
I only need the final answer which is the ,:u,:
what do i have to do?
Put the print statement outside the loop.
Since the print statement is inside, it is running once per iteration. If it is outside, then it will only do it one time-- once it has finished.
for i in range(0, len(massage)):
encrypt = encrypt + chr(ord(massage[i]) ^ key)
print encrypt
Move the print statement outside the for loop. To do that you need to unindent the print statement.
unindent the call to print. This will take it out of the for loop and only print its value when the loop is finished.
On a slightly different note, you might want to work on your acceptance rate if you want people to put time and effort into answering your questions. You've asked 8 questions so far and you haven't accepted an answer to any of them. (Click the arrow next to an answer to accept it)
message= raw_input("Enter message to be encrypted: ")
spec = chr(0b1010101)
key = ord(spec)
encrypt = ""
for i in range(0, len(message)):
encrypt = encrypt + chr(ord(message[i]) ^ key)
print encrypt
Using a generator:
message= raw_input("Enter message to be encrypted: ")
key=0b1010101
print ''.join(chr(key^ord(c)) for c in message)

Categories