# Encypting and Decrypting

**URL:** https://discuss.python.org/t/encypting-and-decrypting/12882
**Category:** Python Help
**Tags:** help
**Created:** [January 4, 2022, 1:53pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882 "2022-01-04T13:53:33Z")
**Posts on this page:** 14
**Page:** 1

<div class="post-metadata">

### Author: ![Duvelril](https://avatars.discourse-cdn.com/v4/letter/d/9de0a6/32.png) [@Duvelril](https://discuss.python.org/u/Duvelril)
#### Post date: [January 4, 2022, 1:53pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/1 "2022-01-04T13:53:33Z")

</div>

So I am working on a project for school in which I need to make a code to encrypt and decrypt text seperatly from eachother. My current code works to encrypt and decrypt at the same time but I can’t seem to get it working seperatly.  
My code:

```auto

from cryptography.fernet import Fernet
 
# we will be encryting the below string.
message =input("Give your message: ")
 
# generate a key for encryptio and decryption
# You can use fernet to generate
# the key or use random key generator
# here I'm using fernet to generate key
 
key = Fernet.generate_key()
 
# Instance the Fernet class with the key
 
fernet = Fernet(key)
 
# then use the Fernet class instance
# to encrypt the string string must must
# be encoded to byte string before encryption
encMessage = fernet.encrypt(message.encode())
 
print("original string: ", message)
print("encrypted string: ", encMessage)
 
# decrypt the encrypted string with the
# Fernet instance of the key,
# that was used for encrypting the string
# encoded byte string is returned by decrypt method,
# so decode it to string with decode methods
decMessage = fernet.decrypt(encMessage).decode()
 
print("decrypted string: ", decMessage)

```

Does anyone know how to seperate this?

---

<div class="post-metadata">

### Author: ![nachoXXL](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/nachoxxl/32/5297_2.png) [@nachoXXL](https://discuss.python.org/u/nachoXXL)
#### Post date: [January 4, 2022, 3:24pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/2 "2022-01-04T15:24:39Z")

</div>

Hi Thomas,  
If you mean by separate: to have a script for encryption and one for decryption, then you’ll have  
to think where you ‘store’ the encrypted message or: how to transfer the message from one script  
to another. Storing it into a file is the most obvious.  
Nacho

---

<div class="post-metadata">

### Author: ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)
#### Post date: [January 4, 2022, 3:57pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/3 "2022-01-04T15:57:11Z")

</div>

Hi Thomas, and welcome!

I’m sorry, I don’t understand what you mean by encrypting and decrypting  
“at the same time”. It looks like different times to me:

First you encrypt:

```
encMessage = fernet.encrypt(message.encode())
print("original string: ", message)
print("encrypted string: ", encMessage)

```

Then later you decrypt:

```
decMessage = fernet.decrypt(encMessage).decode()
print("decrypted string: ", decMessage)

```

Can you explain in more detail what you are trying to do?

---

<div class="post-metadata">

### Author: ![Duvelril](https://avatars.discourse-cdn.com/v4/letter/d/9de0a6/32.png) [@Duvelril](https://discuss.python.org/u/Duvelril)
#### Post date: [January 5, 2022, 12:42pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/4 "2022-01-05T12:42:00Z")

</div>

Hello,

I’m trying to get a seperate script for encryting and decrypting. So if I were to send an email with a text that I have encrypted that the receiver can decrypt it with a seperate decryption script.

---

<div class="post-metadata">

### Author: ![Duvelril](https://avatars.discourse-cdn.com/v4/letter/d/9de0a6/32.png) [@Duvelril](https://discuss.python.org/u/Duvelril)
#### Post date: [January 5, 2022, 12:44pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/5 "2022-01-05T12:44:53Z")

</div>

Hello,

Would this stll be possible to do if I were to need it to send emails to others. So I encrypt it, send the file and then they decrypt it again with a separate decryption script?

---

<div class="post-metadata">

### Author: ![tiran](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tiran/32/48_2.png) [@tiran](https://discuss.python.org/u/tiran)
#### Post date: [January 5, 2022, 12:51pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/6 "2022-01-05T12:51:01Z")

</div>

`Fernet.generate_key()` creates a new random key every time you call the function. You need to save and transfer the key somehow.

---

<div class="post-metadata">

### Author: ![Duvelril](https://avatars.discourse-cdn.com/v4/letter/d/9de0a6/32.png) [@Duvelril](https://discuss.python.org/u/Duvelril)
#### Post date: [January 5, 2022, 1:29pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/7 "2022-01-05T13:29:46Z")

</div>

Hello Christian,

Would it be possible to make the code create a file that saves the key and the encrypted message that can be sent through mail? The receiver gets the file, downloads it and runs it through a similar code that decrypts the message. Is this possible or will I need a different code for this?

---

<div class="post-metadata">

### Author: ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)
#### Post date: [January 5, 2022, 1:45pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/8 "2022-01-05T13:45:23Z")

</div>

If you store the key and the encrypted message together, then anyone who  
receives the message can just use the key to decrypt the message. The  
level of security is effectively zero. Is that what you intend?

---

<div class="post-metadata">

### Author: ![Duvelril](https://avatars.discourse-cdn.com/v4/letter/d/9de0a6/32.png) [@Duvelril](https://discuss.python.org/u/Duvelril)
#### Post date: [January 5, 2022, 2:10pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/9 "2022-01-05T14:10:43Z")

</div>

Yeah I just need to be able to send emails that are encrypted that others can decrypt, don’t really care about security since it is just a concept and will not be used as an actual way of sending information.

---

<div class="post-metadata">

### Author: ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)
#### Post date: [January 5, 2022, 2:53pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/10 "2022-01-05T14:53:04Z")

</div>

Okay, with the understanding that this is totally insecure and  
just suitable for playing around, you could try this:

```
# Untested.
key = Fernet.generate_key()
fernet = Fernet(key)
encMessage = fernet.encrypt(message.encode())
with open("secret_message", "w") as f:
    f.write(key)
    f.write(encMessage)

```

You may need to encode or decode either the key or message.

I’m assuming that the key is a fixed length, let’s assume it is 128  
characters, so when you want to decrypt it:

```
with open("secret_message", "r") as f:
    message = f.read()
key = message[:128]
message = message[128:]

```

I hope this points you in the right direction.

---

<div class="post-metadata">

### Author: ![Duvelril](https://avatars.discourse-cdn.com/v4/letter/d/9de0a6/32.png) [@Duvelril](https://discuss.python.org/u/Duvelril)
#### Post date: [January 7, 2022, 11:58am UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/11 "2022-01-07T11:58:32Z")

</div>

Thank you for the code, I just tested it but I get the error:  
Traceback (most recent call last):  
File “main.py”, line 8, in   
f.write(key)  
TypeError: write() argument must be str, not bytes

Is there a way to maybe get f.write(key) back to a string instead of bytes?

---

<div class="post-metadata">

### Author: ![Duvelril](https://avatars.discourse-cdn.com/v4/letter/d/9de0a6/32.png) [@Duvelril](https://discuss.python.org/u/Duvelril)
#### Post date: [January 7, 2022, 12:17pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/12 "2022-01-07T12:17:30Z")

</div>

And one other question, I am currently working with Replit, only this can’t seem to make files on my pc so I can’t really test if the files work. What is a good programme that works with pc files to write this code in?

---

<div class="post-metadata">

### Author: ![CAM-Gerlach](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/cam-gerlach/32/3688_2.png) [@CAM-Gerlach](https://discuss.python.org/u/CAM-Gerlach)
#### Post date: [January 11, 2022, 12:54am UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/13 "2022-01-11T00:54:02Z")

</div>

Like the error message says, you are writing the file in text mode (i.e. representing textual characters with a given text encoding, like ASCII or UTF-8), but `encMesssage` and `key` are binary data, just a sequence of bytes (in particular, note that you use `.encode()` on the input message to convert it to bytes, and `decode()` on the decrypted message to convert it back to text).

To fix this, replace `"w"` in your `open` call with `"wb"`. Similarly, when you open it, you want to read it in as bytes, so use `"rb"` instead of `"r"`.

If you want the full nitty-gritty, you can read [the official unicode tutorial](https://docs.python.org/3/howto/unicode.html), though you may want to look for something more introductory if you find it too complex.

---

<div class="post-metadata">

### Author: ![alen](https://avatars.discourse-cdn.com/v4/letter/a/9dc877/32.png) [@alen](https://discuss.python.org/u/alen)
#### Post date: [March 12, 2025, 2:55pm UTC](https://discuss.python.org/t/encypting-and-decrypting/12882/14 "2025-03-12T14:55:11Z")

</div>

Hello, another question related to this topic. I am decrypting multiple lines from .txt file.  
It works when 1 have 1 line in .txt with one name and encrypted text.  
When I add more lines with same types of data, it calls an error.:

def read\_messages():  
with open(‘messages.txt’, ‘r’) as paper:  
for line in paper:  
name, encrypted\_message = line.lstrip().split(‘,’)  
poruka = f.decrypt(encrypted\_message.encode())  
print(name +" : " + message.decode())

As I said, it works when I have one name and 1 message in .txt.  
When I add in new row another name and message it shows:

ERROR:

During handling of the above exception, another exception occurred:  
raise InvalidToken
