简体   繁体   English

如何在python 3.7中加密和解密字符串?

[英]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.但是 PyCrypto 不会同时安装在 python 3.6.5 和 3.7.0 上。

So, I implement some kind of Gronsfeld-like cipher.所以,我实现了某种类似 Gronsfeld 的密码。 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?那么,如何正确操作呢?

Cryptography is an actively developed library that provides cryptographic recipes and primitives.密码学是一个积极开发的库,提供密码配方和原语。 It supports Python 2.6-2.7, Python 3.3+ and PyPy.它支持 Python 2.6-2.7、Python 3.3+ 和 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM