Python: Encrypting file contents using a password and decrypting it by users
I already read a lot about this topic but I don’t really understand how I should implement this. I want to encrypt a (text) file of a user A. The user has set up a password for his/her account and the text file is being encrypted with this password. Now the user shares his encrypted file with another user B. This user, of course, has another password set for his/her account. However, he/she and just he/she, should be able to decrypt the text without knowing user A’s password. I guess I have to use a private/public key algorithm. I already looked at PyCrypto but I don’t really understand how to create a public/private key from user A’s password. I’d prefer a real python solution that does not include a pgp executable or dll. Some pseudo code:
key, encrypted = generate_public_key_and_encrypt(userA.password, "Hello World!") userA.share_data(userB, key) decrypted = decrypt(userB.password, key, encrypted)
What exactly is your question? We generally expect a minimal reproducible example and a specific issue for these questions.
How do I encrypt a string using a user’s password? How can another user decrypt it after the first user has shared it?
Generally you derive a random symmetric key, encrypt this with the other users public key, encrypt the file with the symmetric key and then transmit both over to the other user. Your question is a bit too broad for StackOverflow, however, so it will likely be closed.
1 Answer 1
First of all, password authentication (password based) and encryption (key based) are completely different. Basically, if you want to implement an encryption/decryption, you have to be able to have a mechanism to exchange keys between the users. If you plan to use public/private keys for this purpose, private key is always used to decrypt not to encrypt. If you want to map password to private key, you should use your own password to decrypt the message not to encrypt.
If you still want to use password for this kind of mechanism, you can map your private key to the password and use this password indirectly to decrypt the message everytime. And, all the other users should be aware of the public key which maps to this user.
If you plan on using PyCrypto as you mentioned you might need to do the following for encryption/decryption.
>>> from Crypto.PublicKey import RSA >>> key = RSA.generate(2048) >>> public = key.publickey()
Let’s say you want to encrypt a message 1234
# Encrypting using public key of user which is broadcasted >>> cipher = public.encrypt(1234, 22) # Decrypting using users own secret private key >>> message = key.decrypt(cipher)
As far as your requirement is considered, maintain a map for your password and private key somewhere. Whenever user wants to decrypt the message, you can ask him for the password and use the exported key to decrypt the message.
# exporting private key >>> private_key = key.exportKey() # exporting public key public = key.publickey() public_key = public.exportKey()
Encrypting a Text File in Python, Preferably with a Module [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
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.
I don’t think that the Python standard library has the features you want (yet). You’ll need some third-party library to provide them.
Aside from everything else, in the last line of your snippet you think you close the outFile , while, in fact, you don’t.
If it’s for a class, and the instructor wasn’t specific, the encryption strength probably doesn’t matter. I doubt it’s even supposed to be encrypted. Side note: who taught you to end Python statements with a semicolon?
3 Answers 3
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.
Ok, this seems like the right answer, but like I said, I am a beginner. Is there a guide that toy can point me to?
Here’s the most simple method: Input a number from the user, that’ll be your password. Open the input file in binary mode, open the output in binary mode, read a byte from input, add your value to it and then write it to the output. When done, close both files.
I’ve found my encrypter and uploaded to git. If you want to take a look: github.com/Sasszem/encrypter
That. that is SO AWESOME! Thank you SO MUCH! Its so obvious now! It won’t mean much, but I will credit you in my program!
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_baseEncrypt file with password python: 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()
Шифрование и криптография в Python
В Python не так уж много инструментов стандартной библиотеки, которые работают с шифрованием. Однако, в нашем распоряжении есть библиотеки хешинга. Давайте рассмотрим этот вопрос в данной статье, но более детально сфокусируемся на двух сторонних пакетах: PyCrypto и cryptography. Мы научимся шифровать и расшифровывать строки при помощи двух этих библиотек.
Хеширование
Если вам нужно защитить хэши или алгоритм дайджеста сообщений, то для этого прекрасно подойдет модуль стандартной библиотеки Python hashlib. Он включает в себя безопасные алгоритмы хеширования FIPS, такие как SHA1, SHA224, SHA256, SHA384, а также SHA512 и MD5. Python также поддерживает функции хеширования adler32 и crc32, но они содержатся в модуле zlib. Одно из самых популярны применений хеширования это хранение хеша пароля, вместо самого пароля. Конечно, хеш должен быть хорошим, в противном случае он может быть расшифрован.
Другой популярный случай, в котором применяется хеширование – это хеширование файла, с последующей отправкой файла и его хеша по отдельности. Получатель файла может запустить хеш в файле, чтобы убедиться в том, что файл соответствует отправленному хешу. Если это так, значит никто не менял файл, когда он был отправлен. Давайте попробуем создать хеш md5. Но оказывается, чтобы использовать хеш md5, нужно передать его строке байта, вместо обычной. Так что мы попробовали сделать это, после чего вызвали метод дайджеста, чтобы получить наш хеш. Если вы претпочитаете хешированный дайджест, мы можем сделать и это: