This is a simple encryption code that I've come up with. It uses a single character key.
ar = input('please input string to be de/encrypted:')
key = input('please input single character key:')
def encrypt1(key,ar):
i = 0
while i < len(ar):
br = chr(ord(ar[i])^ord(key))
i = i+1
print(br)
encrypt1(key,ar)
print('Input string = ' + ar+'\n'+'key = '+key)
If I input "CMPUT" for the string to be encrypted and 'a' as the key I will get this printed output:
"
,
1
4
5
Which is the correct encryption (according to my assignment example). Now I just have to get those outputs into a single string and print them in the shell like such:
>>>decrypted string: ",145
I've looked through google and old questions on this website but I've still come up empty. I would appreciate your help.
Check out this code, I believe this is what you need (I changed print(br) line):
ar = input('please input string to be de/encrypted:')
key = input('please input single character key:')
def encrypt1(key,ar):
i = 0
while i < len(ar):
br = chr(ord(ar[i])^ord(key))
i = i+1
print(br, end='')
encrypt1(key,ar)
print('\nInput string = ' + ar+'\n'+'key = '+key)
Most obvious way for a beginner would be to simply accumulate to a string
def encrypt1(key,ar):
i = 0
result = ""
while i < len(ar):
br = chr(ord(ar[i])^ord(key))
i = i+1
result += br
return result
Usually you would just write it using a generator expression
def encrypt1(key,ar):
return ''.join(chr(ord(i) ^ ord(key)) for i in ar)
Related
I’m using Python IDE 3. My goal is this: If I have a string of text, ‘ABCDEFGHIJKL’, I want to sort it into groups, like three groups (‘ADGJ’,’BEHK’,’CFIL’). I require input for this, but the prompts aren’t showing up and I can’t type in input. Here’s my code:
#data
code_text = input('Text: ').lower()
code_skip = int(input('Shift length: '))
code_list = []
#function
def countSkip(text, shift, listt):
i = 0
group = 1
if group <= shift:
for e in text:
#make sure the set starts at the right place
if e.index()+1 < group:
pass
elif shift != 0:
if i = shift:
listt.append(e)
i = 0
i += 1
else:
listt.append(e)
group += 1
Calling the function
countSkip(code_text, code_shift, code_list)
There's a few things stopping your code from working that people have pointed out in the comments. Instead of trying to dissect your code and get that to work, I wrote a much more concise function that will get you the results you're after
def text_splitter(input_text, set_length):
num_sets = int(len(input_text)/set_length)
split_text = ["".join([input_text[(n * num_sets) + m] for n in range(set_length)]) for m in range(num_sets)]
return split_text
text_to_split = input('Text: ').lower()
len_set = int(input('Set Length: '))
text_list = text_splitter(text_to_split, len_set)
Sorry I was struggling to name the variables in an effective manner but the function above uses a list expression to get you the results you need. Keep in mind that if you use say a 7 letter string and ask for sets of length 2, the last letter won't be appended. However this shouldn't be too hard to check and correct. For example you could add this code to the function or around the initial input for the set length:
while len(input_text) % set_length != 0:
set_length = int(input("The text is length " + str(len(input_text)) + " please enter a different set length: "))
So I am doing a project where I try to guess the key of a message that has been changed. The message was converted from character to ascii number had the key added onto the ascii number and then converted back to character. I am struggling to figure out how to get a if statement that would return something if there is an intersection between the message and a word bank. It never returns the correct thing. Thoughts?
import re
from list_maker import *
message = input("what is your code? ")
list_broken = [ord(i) for i in message]
key = 27
num = 26
for l in list_broken:
key -= 1
list_decoded = [chr(i - key) for i in list_broken]
final = ''.join(list_decoded)
word_list = re.sub("[^\w]", " ", final).split()
S1 = set(word_list)
S2 = set(set_of_words)
i = 0
for e in S1:
if e in S2:
break
print(word_list)
print(key)
Sets have an intersection operator just for this.
S1&S2 returns the set of elements in both given sets.
So for your case, you can just check:
if S1&S2:
...
My code is about creating a password using the first character/digit of every word/number as a character in a sentence/phrase and printing it just as so.
Example: Stop and smell the 350 "roses". -> Sast3r. (Ignoring
quotations using r instead)
This would be very easy using lists, but you cannot use them in this assignment for my code. So, I don't know what to do now after what I have done so far
Function:
def create_password(phrase):
q = "'" # quotations
dq = '"' # double quotes
password = phrase[0]
for i in phrase:
x = phrase.find(" ")
if i.isalnum:
password += phrase[x + 1]
elif x == q or x == dq:
password += phrase[x + 2]
return password
Main:
# Imports
from credentials import create_password
# Inputs
phrase = str(input("Enter a sentence or phrase: "))
# Outputs
password = create_password(phrase)
print(password)
I think it is more straightforward to walk through the entire phrase without worrying about splitting on spaces. Instead keep track of whether or not you've just seen a space. You only want to add the character after just seeing a space.
def create_password(phrase):
q = "'" # quotations
dq = '"' # double quotes
#Initialize the password to be an empty string
password = ""
#We are at the start of a new word (want to add first index to password)
new_word = True
#Walk through every character in the phrase
for char in phrase:
#We only want to add char to password if the following is all true:
#(1) It's a letter or number
#(2) It's at the start of a new word
#(3) It's not a single quote
#(4) It's not a double quote
if char.isalnum and new_word:
if char != q and char != dq:
password += char
new_word = False #<-- After adding char, we are not at a new word
#If we see a space then we are going to be at a new word
elif char == " ":
new_word = True
return password
p = create_password('Stop and smell the 350 "roses"')
print(p)
Output:
Sast3r
You're definitely on the right track! Using the str.find() method is definitely the way to go!
However, you need to understand what the str.find() method does. Look at the signature:
str.find(sub [,start [,end) -> int
# sub -> character to find
# start -> where the function should start looking in the string
# end -> where the function should stop looking
# Returns a number, which is the place it found the character.
# If it didn't find anything, then return -1.
Without telling the function where to start, it will always find the first occurrence of the character in the string. It won't know that you're going through each character of the string.
So let's change it up a little bit:
for char_index in xrange(len(phrase)):
# Tell the method to look after char_index: we've already looked before this!
x = phrase.find(' ', char_index) index
if phrase[x+1].isalnum(): # It's a function, notice the brackets?
password += phrase[x + 1]
elif phrase[x+2] == q or phrase[x+2] == dq:
password += phrase[x + 2]
Hopefully, this should get your desired password.
Give priority to the use of built-in function, for example, every time you find the location of space, then why not directly in accordance with the space for spilt function, so that the string directly to the character list, each element is a word, and then remove each element in the list.
def create_password(phrase):
password = ''
phrase_list = phrase.split(' ')
print (phrase_list)
for i in phrase_list:
print (i[0])
password += i[0]
return password
if __name__ == '__main__':
# Inputs
phrase = str(input("Enter a sentence or phrase: "))
# Outputs
password = create_password(phrase)
print(password)
Try taking the first character in the string, and then every character that follows a space. It looks like you have the right idea.
I am currently working on a python project to take a string of text, encrypt the text by adding a keyword to it and then outputting the result. I currently have all the features of this program operational except converting the numerical value back into text.
For example, the raw text will be converted into a numerical value, for instance [a, b, c] will become [1, 2, 3].
Currently I have no ideas of how to correct this issue and would welcome any help, my current code is as follows:
def encryption():
print("You have chosen Encryption")
outputkeyword = []
output = []
input = raw_input('Enter Text: ')
input = input.lower()
for character in input:
number = ord(character) - 96
output.append(number)
input = raw_input('Enter Keyword: ')
input = input.lower()
for characterkeyword in input:
numberkeyword = ord(characterkeyword) - 96
outputkeyword.append(numberkeyword)
first = output
second = outputkeyword
print("The following is for debugging only")
print output
print outputkeyword
outputfinal = [x + y for x, y in zip(first, second)]
print outputfinal
def decryption():
print("You have chosen Decryption")
outputkeyword = []
output = []
input = raw_input('Enter Text: ')
input = input.lower()
for character in input:
number = ord(character) - 96
output.append(number)
input = raw_input('Enter Keyword: ')
input = input.lower()
for characterkeyword in input:
numberkeyword = ord(characterkeyword) - 96
outputkeyword.append(numberkeyword)
first = output
second = outputkeyword
print("The following is for debuging only")
print output
print outputkeyword
outputfinal = [y - x for x, y in zip(second, first)]
print outputfinal
mode = raw_input("Encrypt 'e' or Decrypt 'd' ")
if mode == "e":
encryption()
elif mode == "d":
decryption()
else:
print("Enter a valid option")
mode = raw_input("Encrypt 'e' or Decrypt 'd' ")
if mode == "e":
encryption()
elif mode == "d":
decryption()
Although Your Question is not quite clear I wrote a script which do encryption using Dictionary
plaintext = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') #Alphabet String for Input
Etext = list('1A2B3C4D5E6F7G8H90IJKLMNOP') """Here is string combination of numbers and alphabets you can replace it with any kinda format and your dictionary will be build with respect to the alphabet sting"""
def messageEnc(text,plain, encryp):
dictionary = dict(zip(plain, encryp))
newmessage = ''
for char in text:
try:
newmessage = newmessage + dictionary[char.upper()]
except:
newmessage += ''
print(text,'has been encryptd to:',newmessage)
def messageDec(text,encryp, plain):
dictionary = dict(zip(encryp,plain))
newmessage = ''
for char in text:
try:
newmessage = newmessage + dictionary[char.upper()]
except:
newmessage += ''
print(text,'has been Decrypted to:',newmessage)
while True:
print("""
Simple Dictionary Encryption :
Press 1 to Encrypt
Press 2 to Decrypt
""")
try:
choose = int(input())
except:
print("Press Either 1 or 2")
continue
if choose == 1:
text = str(input("enter something: "))
messageEnc(text,plaintext,Etext)
continue
else:
text = str(input("enter something: "))
messageDec(text,Etext,plaintext)
Suppose you've got a list of numbers like a = [1, 2, 3] and an alphabet: alpha = "abcdef". Then you convert this as follows:
def NumToStr(numbers, alpha):
ret = ""
for num in numbers:
try:
ret += alpha[num-1]
except:
# handle error
pass
return ret
Going by your question , you want to convert number back to text.
You can have two list declared for both the number and alphabet, such as:
num=[1,2,3....26]
alpa=['a','b','c'....'z']
and after that find the index/position from the num list and find the alphabet for that index in alpa list.
A couple of things. The first is to convert the coded values back to characters you can use the chr(i) command. Just remember to ad the 96 back on.
for code in outputfinal:
print chr(code + 96),
I tried 'aaa' as my plaintext and 'bbb' as my keyword and this printed 'ccc' which is what I think you are trying to do.
Another thing. The zip command iterates over two lists but (in my playing) only until one of the lists runs out of members. If your plaintext is 10 characters and your keyword is only 5 then only the first 5 characters of your plaintext get encrypted. You will need to expand or inflate your key to the length of your plaintext message. I played with something like this:
plaintext = ['h','e','l','l','o',' ','w','o','r','l','d']
keyword = ['f','r','e','d']
index = len(keyword) # point to the end of the key word
keyLength = len(keyword)
while index < len(plaintext): # while there are still letters in the plain text
keyword.append(keyword[index - keyLength]) # expand the key
index += 1
print keyword
for a,b in zip(plaintext, keyword):
print a, b
I hope this helps. Please let me know if I have misunderstood.
I am currently trying to produce a program that allows me to encrypt and decrypt a words using a keyword, I have been told to use alphabetic value to do add from another words alphabetic value I know that I need to use ord or chr but I am not very confident in using this as I'm a beginner at programming, however I have no idea how to do this and would much appreciate, if someone could explain this to me with some examples.
s = "foo!#bar"
enc_key = "key"
# get sum of ord's of letters in key modulo 256
sm_ords= sum(map(ord,enc_key)) % 256
# add sum of ord's in encryption letter in key to ord of each char in s and use chr to create a new char
enc = "".join(chr((sm_ords + ord(ch))) for ch in s)
# reverse the encryption using - ord
dec = "".join(chr((ord(ch) - sm_ords)) for ch in enc)
print(enc)
print(dec)
¯¸¸jl«ª»
foo!#bar
This code encrypts / decrypts a string by adding the value of each of the keyword letters to each character in the string to be encrypted.
def encryptfunction():
result = ""
addedup = 0
for letter in wordtoencrypt:
for letter2 in keyword:
addedup = addedup + ord(letter2)
result = result + chr(ord(letter) + addedup)
return result
def decryptfunction():
result = ""
addedup = 0
for letter in wordtoencrypt:
for letter2 in keyword:
addedup = addedup + ord(letter2)
result = result + chr(ord(letter) - addedup)
return result
wordtoencrypt = input("Enter the word to encrypt:")
keyword = input("Enter the keyword:")
encrypt = int(input("encrypt(1) or decrypt(0)"))
if encrypt == 1:
print(encryptfunction())
else:
print(decryptfunction())