Encrypting a Text File in Python, Preferably with a Module [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Context:
I have a class, in which I have to make a password protected something or other.
(My instructor is not very specific.) The reason for me asking for a method in which I could use a standard import statement was so I could just upload a single folder that only contained a text file and the program itself. I want to do something as follows:
#Import Statements Here
outFile = open('myFile.txt',"wt");
#Here is the tricky part.
#In place of all of these comments,
#I want to encrypt the file with a key given by a user(in this case,givenKey):
givenKey = input("Please input your key:>>>");
outFile.close();
Resolution:
The answer by Sasszem was the one that worked for me. Look into the comments
for a simplified explanation of the main answer. The person who gave me his/her custom made code (I cant remember who gave it to me, sorry.) had a good idea. But I don't like using code I don't understand. And finally, the person who gave me the Cryptography module as an idea wasn't wrong, but I use python on Windows.

A simple way to encrypt data is to add a constant to every byte.
You can generate some random byte from the pwd and then add it to every byte in the input. It won't be strong, but it's simple.
If you make something like your program generates random numbers to add to the bytes after seeding your pwd to the random generator, your instructor will be impressed.
To decode, simply subtract the same numbers from the bytes.

Package cryptography provides support for encryption/decryption: https://pypi.python.org/pypi/cryptography. I understand that it is included in Anaconda.

Here is a module I wrote a while back. It uses only built-in python modules. I give you permission to use it!
import string, random
class Round(object):
def __init__(self, *seqs):
self.position = 0
self.data = [i for x in seqs for i in x]
self.len = len(self.data)
def __repr__(self):
return str(self.data)
def __iter__(self):
self.position = 0
return self
def is_item(self, item):
if str(self.data[self.position]) == str(item):
return True
return False
def __getitem__(self, index):
if index < self.len-1 and index >= 0:
return self.data[index]
else:
while index < 0:
index += self.len-1
while index > self.len-1:
index -= self.len-1
return self.data[index]
def next(self):
if self.position >= self.len-1:
self.position = 0
raise StopIteration
else:
self.position += 1
return self.data[self.position-1]
class JCripter(object):
def __init__(self, string):
self.string = string
self.generate_key_set()
self.encrypted = False
def generate_key_set(self):
self.alphabet = list(string.ascii_lowercase)
self.numbers = [str(x) for x in range(10)]
self.special_characters = ['"',"'",',','?','.',
' ','(',')',':',';',
'!','#','#','$','%',
'^','&','*','_','-',
'+','=','<','>','~',
'`','{','[','}',']',
'\\','|']
self.key_base = Round(self.alphabet, self.numbers, self.special_characters)
def get_key_index(self, key):
for i in self.key_base:
if isinstance(key, int):
if i == self.key_base[key]:
return self.key_base.position-1
elif i == key.lower():
return self.key_base.position-1
else:
print 'not found'
def __repr__(self):
return self.string
def _encrypt(self, string, func, *args):
if string == None:
string = self.string
if string == None:
return
string = string.lower()
n_string = func(string, *args)
self.encrypted = not self.encrypted
self.string = n_string
return n_string
class CeaserCypher(JCripter):
def __init__(self, string, shift=None):
JCripter.__init__(self, string)
if shift == None:
self.shift = random.randint(0, self.key_base.len)
else:
self.shift = shift
def encrypt(self, string=None):
def inner(string):
n_string=''
for i in string:
if self.encrypted == True:
n_string += self.key_base[self.get_key_index(i)-self.shift]
else:
n_string += self.key_base[self.get_key_index(i)+self.shift]
return n_string
return self._encrypt(string, inner)
class PseudoRandomCypher(JCripter):
def __init__(self, string, shifts=None):
if shifts == None:
self.shift = [random.randint(0, 500) for x in string]
else:
self.shift = shifts
JCripter.__init__(self, string)
def encrypt(self, string=None):
def inner(string):
ind = 0
n_string = ''
for i in string:
if ind >= len(self.shift)-1:
ind = 0
if self.encrypted == True:
n_string += self.key_base[self.get_key_index(i)-self.shift[ind]]
else:
n_string += self.key_base[self.get_key_index(i)+self.shift[ind]]
ind += 1
return n_string
return self._encrypt(string, inner)
class PolyAlphabeticCypher(JCripter):
def __init__(self, string, key, enc=False):
JCripter.__init__(self, string)
self.key=list(key)
self.encrypted = enc
def encrypt(self, string=None):
def inner(string):
index = 0
n_string = ''
for i in string:
if index >= len(self.key)-1:
index = 0
if self.encrypted == True:
n_string += self.key_base[self.get_key_index(i)-self.get_key_index(self.key[index])]
else:
n_string += self.key_base[self.get_key_index(i)+self.get_key_index(self.key[index])]
index += 1
return n_string
return self._encrypt(string, inner)
n = 'Hello world my name is anonymous!'
p = PolyAlphabeticCypher(n, 'super_secret_password')
print p.encrypt() #--> returns encrypted data
print p.encrypt() #--> decrypts data
#if you are decrypting a previously encrypted text
n = 'Some sensitive data'
first = PolyAlphabeticCypher(n, 'some pass')
my_data = first.encrypt()
second = PolyAlphabeticCypher(my_data, 'some pass', True)
print second.encrypt()

Related

a program to check if a reversed string is a palindrome or not using Stack Machine in python

can u help me to solve the following
am trying to get a string input from user, then push the string into the StackMachine so as to check the validity of the string. if the String passes the rules defined, the output string from the StackMachine is to be checked if its a palindrome or not ..this is what i have tried so far
note you can only use the function in the StackMachine class and not another method to determine the validity of the string. The condition to accept a string is that you have read all the input string and the stack is empty
```
class StackMachine(object):
SMRules = {} # dictionary of SM rules
def __init__(self):
self.Stack = ['S'] # populate stack with initial 'S'
self.size = 1 # set size of stack to 1
self.SMRules = {} # Place rules here
def pop(self):
if len(self.Stack) <1:
pass
else:
self.Stack.pop(0)
self.size-= 1 # reduce stack size by 1
return
def peek(self):
ss = ""
if len(self.Stack) < 1:
return ""
else:
ss = self.Stack
return ss[0]
def stackIsEmpty(self):
if len(self.Stack) == 0:
return True
else:
return False
def push(self,str):
sStr = str[::-1] # slicing
for chr in sStr:
self.Stack.insert(0,chr) # push string onto top of stack
self.size = len(self.Stack)
return
def printStack(self):
print("Stack: [",end='')
for item in self.Stack:
print(item,end='')
print("]")
return
def printRules(self):
print("SM Rules:")
rn = 1
for key, value in self.SMRules.items():
print("Rule",rn,"%4s" % key,"|", value)
rn += 1
return
def main():
Stk = StackMachine()
text =str(input('Please enter the string: '))
for character in text:
Stk.push(character)
reversed_text = ''
while not Stk.stackIsEmpty():
reversed_text = reversed_text + Stk.pop()
if text == reversed_text:
print('The string is a palindrome.')
else:
print('The string is not a palindrome.')
if __name__ == '__main__':
main()
Am getting the following Error and i dont know how to solve it
```
File "C:\Users\user\Stack-Machine\StackMachine.py", line 91, in main
reversed_text = reversed_text + Stk.pop()
TypeError: can only concatenate str (not "NoneType") to str`enter code here`
my question is
1.how do I solve the error?
2.how to print string chracter by character from the stackMachine
3.successfully check if the processed string from the Stack Machine is a palindrome or not
As defined, StackMachine.pop() returns None.
When you do reversed_text + Stk.pop(), even though reversed_text is a string, Stk.pop() is None, which causes the TypeError you are seeing.
Why do you need to use the so called StackMachine class to check if a string is a palindrome? There are simpler ways to check if a string is a palindrome.
If all you want to do is get a string input and determine whether it's a palindrome, you can do so like this:
text = input()
isPalindrome = text == text[::-1]

Python: FIFO with limited depth - optimisation question and review

Again, I am new to python. I need a FIFO with a limited depth.
F.e the depth is 5000, so after 5000 and more added items the first one's should be deleted to keep its depth is 5000. Some times I need to read 'the first' one and sometimes read the 'last one'. If I read the first one then it should be removed.
# class
class DictionaryDeque:
from collections import OrderedDict
def __init__(self, dequeDict=10):
self._stack = OrderedDict()
self._range = dictRange
self.setRange(dictRange)
self._len = 0
def len(self):
self._len = len(self._stack)
return self._len
def getRange(self):
return self._range
def setRange(self, range):
self._range = range
# change the dict range if the dict has more items
self.do_pop()
def add(self, key, value):
self._stack[key] = value
self.len()
self.do_pop()
def stack(self):
if self._len > 0:
self.do_pop()
return self._stack
else:
return ""
def last(self):
self.do_pop()
if self._len > 0:
return list(self._stack)[-1]
else:
return list(self._stack)[0]
def first(self):
self.do_pop()
return list(self._stack)[0]
def do_pop(self):
while self.len() > self._range:
self._stack.popitem(last=False)
self.len()
# end of class
dequeDict = DictionaryDeque(30)
for i in range (0, 40):
now = str(datetime.datetime.now())
dequeDict.add(now, i)
dequeDict.setRange(10)
print(dequeDict.len())
print(dequeDict.last())
print(dequeDict.first())
print(dequeDict.stack())
I have to implement the 'first read and remove' and some more functions, but before I start with that, I would love to know if this the/a way to go, or should there be something better?
Is there a way to avoid the list part in
list(self._stack)[0]
?
BTW, what is a good name for this class? < class name changed
Thank you

Getting Pylint E1101 - Instance has no such member

Pylint doesn't like this code:
class sequence(list):
def __init__(self, n):
list.__init__(self)
self += self._generate_collatz_seq(n)
self.pivots = self._generate_pivots()
self.data = self._make_data()
def _collatz_function(self, n):
if n % 2 == 0:
return(int(n/2))
else:
return(3*n + 1)
def _generate_collatz_seq(self, x):
int(x)
sequence_holder = []
while x != 1:
sequence_holder.append(x)
x = self._collatz_function(x)
sequence_holder.append(1)
return sequence_holder
def _generate_pivots(self):
pivots_holder = []
for element in self:
if element % 2 != 0:
pivots_holder.append(element)
return pivots_holder
def _make_data(self):
data_holder = []
data_holder.append(len(self))
data_holder.append(len(self.pivots))
return data_holder
It says
E1101: Instance of 'sequence' has no 'pivots' member(56,36)
This is before I have made any instances of sequence. I'm sure I haven't gone about my task in the most efficient way, but I can't see that I've done anything wrong.

NameError: name 'self' is not defined at the last block only?

Why it tells me "NameError: name 'self' is not defined" when I run this code?
I don't know why it's all fine except the last block (update method) gives me that error anyone can help?
This code is a game that takes in the lenth of the hand and gives you a random letters to create a word from the hand ,when you enter an currect word, the letters used in the word get removed automaticlly till the words
import random
class Hand(object):
self.hand = {}
def __init__(self, n):
'''
Initialize a Hand.
n: integer, the size of the hand.
'''
assert type(n) == int
self.HAND_SIZE = n
self.VOWELS = 'aeiou'
self.CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
# Deal a new hand
self.dealNewHand()
def dealNewHand(self):
'''
Deals a new hand, and sets the hand attribute to the new hand.
'''
# Set self.hand to a new, empty dictionary
self.hand = {}
# Build the hand
numVowels = self.HAND_SIZE // 3
for i in range(numVowels):
x = self.VOWELS[random.randrange(0,len(self.VOWELS))]
self.hand[x] = self.hand.get(x, 0) + 1
for i in range(numVowels, self.HAND_SIZE):
x = self.CONSONANTS[random.randrange(0,len(self.CONSONANTS))]
self.hand[x] = self.hand.get(x, 0) + 1
def setDummyHand(self, handString):
'''
Allows you to set a dummy hand. Useful for testing your implementation.
handString: A string of letters you wish to be in the hand. Length of this
string must be equal to self.HAND_SIZE.
This method converts sets the hand attribute to a dictionary
containing the letters of handString.
'''
assert len(handString) == self.HAND_SIZE, "Length of handString ({0}) must equal length of HAND_SIZE ({1})".format(len(handString), self.HAND_SIZE)
self.hand = {}
for char in handString:
self.hand[char] = self.hand.get(char, 0) + 1
def calculateLen(self):
'''
Calculate the length of the hand.
'''
ans = 0
for k in self.hand:
ans += self.hand[k]
return ans
def __str__(self):
'''
Display a string representation of the hand.
'''
output = ''
hand_keys = sorted(self.hand.keys())
for letter in hand_keys:
for j in range(self.hand[letter]):
output += letter
return output
def update(self, word):
"""
Does not assume that self.hand has all the letters in word.
Updates the hand: if self.hand does have all the letters to make
the word, modifies self.hand by using up the letters in the given word.
Returns True if the word was able to be made with the letter in
the hand; False otherwise.
word: string
returns: Boolean (if the word was or was not made)
"""
for i in word :
if self.hand.get(i , 0) == 0 :
return False
else :
self.hand[i] -=1
return True
I think it's this line:
self.hand = {}
at the top of your class that is the problem. There is no self at the point when the class is being defined. This line should be inside your __init__ method.
def __init__(self, n):
'''
Initialize a Hand.
n: integer, the size of the hand.
'''
self.hand = {}
# ... and the rest

Is there a way to create a class with an undetermined number of inputs?

I'm trying to create a class for a vector, and as such the number of inputs would depend on the dimension of the vector. Here's my code right now:
class vector:
def __init__(self, entries):
self.elements = []
self.dimensionality = len(entries)
for entry in entries:
self.elements.append(entry)
def __str__(self):
buff = "("
for e in self.elements:
buff += str(e)
if self.elements.index(e) < len(self.elements) - 1:
buff += ", "
buff += ")"
return buff
def __mul__(self, otherVector):
if self.dimensionality != otherVector.dimensionality:
raise RuntimeError("Cannot multiply vectors of different dimensions")
else:
product = 0
for e in self.elements:
product += e * otherVector.elements[self.elements.index(e)]
return product
def __eq__(self, otherVariable):
return size(self) == size(otherVariable)
def size(x):
norm = 0
for e in x.elements:
norm += e**2
return norm**(1/2)
As you can see right now I'm just taking a list as an input so I don't have to deal with that, but I want to do matrices next, and that would require a list of lists, which is a pretty tedious way to input information. Anyone know a way to create a class with a flexible number of arguments?
Thanks

Categories

Resources