python 使用Python和Simple-Crypt加密/解密

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用Python和Simple-Crypt加密/解密相关的知识,希望对你有一定的参考价值。

# https://github.com/andrewcooke/simple-crypt

import base64
import argparse
from flata import Flata, Query, where
from flata.storages import JSONStorage
from simplecrypt import encrypt, decrypt
from getpass import getpass

db_init = Flata('mydb.json', storage=JSONStorage)
db_init.table('collection1', id_field = 'uid')
db = db_init.get('collection1')

def base64_encode(string):
	encoded_string = base64.b64encode(string)
	return encoded_string

def base64_decode(string):
	decoded_string = base64.b64decode(string)
	return decoded_string

def check_passphrase(password):
	if len(password) < 6:
		raise SystemExit('Passphrase needs to be more than 6 charachters')

def check_description(description):
	if description == None:
		raise SystemExit('Description is needed when encryption mode is used')
		
def MainApp():
	parser = argparse.ArgumentParser(description='Utility to Encrypt/Decrypt')
	parser.add_argument('-t', '--type', help='option: encrypt/decrypt/list', required=True)
	parser.add_argument('-c', '--cipher', help='option: cipher to decrypt', required=False)
	parser.add_argument('-s', '--string', help='option: string to encrypt', required=False)
	parser.add_argument('-d', '--description', help='option: descryption for secret', required=False)
	args = parser.parse_args()

	if args.type == 'encrypt':
		secret_string = args.string
		password = getpass()
		check_passphrase(password)
		check_description(args.description)
		secret_desc = args.description
		cipher = encrypt(password, secret_string)
		encoded_string = base64_encode(cipher)
		db.insert({'Description': secret_desc, 'EncryptedString': encoded_string})
		return encoded_string

	if args.type == 'decrypt':
		try:
			secret_string = args.cipher
			password = getpass()
			decoded_string = base64_decode(secret_string)
			decrypted_string = decrypt(password, decoded_string)
			return decrypted_string
		
		except Exception as e:
			return e
		
        if args.type == 'list':
		try:
			db_list = db.all()
			return db_list
		except Exception as e:
			return e
		
if __name__ == '__main__':
	val = MainApp()
	print(val)

以上是关于python 使用Python和Simple-Crypt加密/解密的主要内容,如果未能解决你的问题,请参考以下文章

python2和python3同时存在如何安装和使用pip

电脑同时安装python2和python3 ,默认使用python3

[Python] Window机器上同时安装Python 2 和 Python 3,如何兼容切换使用?

jupyter notebook同时使用python2和python3

Python同时安装了python2和python3时,pip命令该如何使用?

python的安装和简单使用