Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I encrypt and decrypt a string in python 3.7?

I've found this exactly same question. But PyCrypto doesn't install both on python 3.6.5 and 3.7.0.

So, I implement some kind of Gronsfeld-like cipher. I know, that's awful, but I can simply encrypt and derypt string with password

def encrypt(string, password):
    int_list = []
    password_len = len(password)
    for cnt, sym in enumerate(string):
        password_sym = password[cnt % password_len]
        int_list.append(ord(sym)-ord(password_sym))
    return int_list

# got some list which contain mine key to Todoist api, yes, this can be bruteforced, but same as any other API key
>>> [-20, -20, -50, -14, -61, -54, 2, 0, 32, 27, -51, -21, -54, -53, 4, 3, 29, -14, -51, 29, -10, -6, 1, 4, 28,
       29, -55, -17, -59, -42, 2, 50, -13, -14, -52, -15, -56, -59, -44, 4]

def decrypt(int_list, password):
    output_string = ""
    password_len = len(password)
    for cnt, numb in enumerate(int_list):
        password_sym = password[cnt % password_len]
        output_string += chr(numb+ord(password_sym))
    return output_string

So, how to do it properly?

like image 699
Egor Egorov Avatar asked Aug 21 '18 09:08

Egor Egorov


People also ask

How do you decrypt a string?

Decryption Approach:Find the length L of the string. Find the ceil and floor values of √Length and assign them to the variables. Create a 2D matrix and fill the matrix by characters of string column-wise. Read the matrix row-wise to get the decrypted string.

Does Python have built in encryption?

Python has no built-in encryption schemes, no. You also should take encrypted data storage serious; trivial encryption schemes that one developer understands to be insecure and a toy scheme may well be mistaken for a secure scheme by a less experienced developer. If you encrypt, encrypt properly.

How do you encrypt a letter in Python?

Caesar Cipher Technique is the simple and easy method of encryption technique. It is simple type of substitution cipher. Each letter of plain text is replaced by a letter with some fixed number of positions down with alphabet.


1 Answers

Cryptography is an actively developed library that provides cryptographic recipes and primitives. It supports Python 2.6-2.7, Python 3.3+ and PyPy.

Installation

$ pip install cryptography

Example code using high level symmetric encryption recipe:

from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
plain_text = cipher_suite.decrypt(cipher_text)
like image 194
Sathiyakugan Avatar answered Oct 13 '22 02:10

Sathiyakugan