一、安装及生成密钥
#pip install pycryptodome
#pip install Crypto
# 在控制台下运行,用以生成加密的公钥和私钥
# openssl genrsa -out ./myPrivateKey.pem -passout pass:"wodeceshi" -des3 2048
# openssl rsa -pubout -in ./myPrivateKey.pem -passin pass:"wodeceshi" -out ./myPublicKey.pem
二、代码
1、rsa2048.py
加密文字或验证文字或解密文字,都是bytes对象,因此str字符串要encode,居然能支持中文字符串,空字符串也可以
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5 as PKCS1_v1_5_sign
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_v1_5_cipher
from base64 import b64encode, b64decode
#pip install pycryptodome
#pip install Crypto
# 在控制台下运行,用以生成加密的公钥和私钥
# openssl genrsa -out ./myPrivateKey.pem -passout pass:"wodeceshi" -des3 2048
# openssl rsa -pubout -in ./myPrivateKey.pem -passin pass:"wodeceshi" -out ./myPublicKey.pem
# 加密文字或验证文字或解密文字,都是bytes对象,因此str字符串要encode,居然能支持中文字符串,空字符串也可以
sss = '好好学习'
msg = sss.encode('utf-8')
# print(msg)
# 验证签名
def rsa_sign(message):
try:
private_key_file = open('./myPrivateKey.pem', 'r')
private_key = RSA.importKey(private_key_file.read(), 'wodeceshi')
hash_obj = SHA.new(message)
signer = PKCS1_v1_5_sign.new(private_key)
d = b64encode(signer.sign(hash_obj))
return d
except Exception as e:
print(e)
return None
def rsa_verify(message, signature):
try:
public_key_file = open('./myPublicKey.pem', 'r')
public_key = RSA.importKey(public_key_file.read())
sign = b64decode(signature)
h = SHA.new(message)
verifier = PKCS1_v1_5_sign.new(public_key)
# 单独增加一项长度验证,因为经测试,编码后的字符串长度变长,验证也能通过,因此加长度验证
if len(signature) != 344:
return False
return verifier.verify(h, sign)
except Exception as e:
print(e)
return False
s = rsa_sign(msg)
print(s)
print(msg)
v = rsa_verify(msg, s)
print(v)
# # 文字的加密与解密
# def rsa_encrypt(message):
# try:
# public_key_file = open('./myPublicKey.pem', 'r')
# public_key = RSA.importKey(public_key_file.read())
# signer = PKCS1_v1_5_cipher.new(public_key)
# rsa_text = b64encode(signer.encrypt(message))
# return rsa_text
# except Exception as e:
# print(e)
# return None
#
#
# def rsa_decrypt(message):
# try:
# private_key_file = open('./myPrivateKey.pem', 'r')
# private_key = RSA.importKey(private_key_file.read(), 'wodeceshi')
# signer = PKCS1_v1_5_cipher.new(private_key)
# back_text = signer.decrypt(b64decode(message), 0)
# return back_text.decode('utf-8')
# except Exception as e:
# print(e)
# return None
#
# v = rsa_encrypt(msg)
# print(v)
# k = rsa_decrypt(v)
# print(k)
2、mygetConfig.py
import configparser
def get_config(config_file='zyconfig.ini'):
parser = configparser.ConfigParser()
parser.read(config_file,encoding='UTF-8')
_conf_security = [(key, str(value)) for key, value in parser.items('security')]
return dict(_conf_security )
3、zyconfig.ini
[security]
uobjct=好好学习
ukulng=天天向上
4、test.py
from flask import Flask, request
from flask_httpauth import HTTPBasicAuth
from flask import abort, jsonify
auth = HTTPBasicAuth(scheme='Token', realm="AI Object Detection")
import mygetConfig
gConfig = {}
gConfig = mygetConfig.get_config()
app = Flask(__name__)
import base64,cv2
import numpy as np
def image_to_base64(full_path):
with open(full_path, "rb") as f:
data = f.read()
image_base64_enc = base64.b64encode(data)
image_base64_enc = str(image_base64_enc, 'utf-8')
return image_base64_enc
def base64_to_image(base64_code):
img_data = base64.b64decode(base64_code)
img_array = np.fromstring(img_data, np.uint8)
image_base64_dec = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)
return image_base64_dec
def cv2_base64(image):
base64_str = cv2.imencode('.jpg',image)[1].tostring()
base64_str = base64.b64encode(base64_str)
return base64_str
@app.route('/trash1', methods=['GET', 'POST'],strict_slashes=False)
@auth.login_required
def tt():
img_bytes = request.json["img_stream"]
img = base64_to_image(img_bytes)
img_bytes = cv2_base64(img)
img_bytes = img_bytes.decode()
return img_bytes
@auth.verify_password
#验证密码:username,password 在config_docker.ini [security]中配置
def verify_password(username_or_token, password):
# 进行rsa2048验证
from rsa2048 import rsa_verify
#函数rsa_sign为加密,rsa_verify为校验
# print(gConfig['uobjct'].encode('utf-8'))
# print(gConfig['ukulng'].encode('utf-8'))
# print(username_or_token)
# print(password)
if rsa_verify(gConfig['uobjct'].encode('utf-8'), username_or_token) and rsa_verify(
gConfig['ukulng'].encode('utf-8'), password):
# print("rsa_verify: ok")
pass
else:
# return jsonify({"Result": "FAIL", "ErrorMsg": "Unauthorized Access", "Details": {}})
abort(401)
return True
if __name__ == '__main__':
app.run("0.0.0.0",port=10099)
5、postman
6、ceshi.py
import requests
import json
url = "http://192.168.1.7:10099/trash1"
payload = json.dumps({
"img_stream": ""
})
headers = {
'Authorization': 'Basic c1FBWXNHK2EvSk1BUUNNZ0dpLzFvUzFtWGtRNTJ5TzN2ZUcvUHRsT3I1SjE5MzhreFdVc2JzTTh4RWFRaExyZi9oZ2llMktON2x4dkxIYWZtMHlXQVdhZTlyQ2dkdjVKRm41SG8wU1owenpiQSsySjA1Z2tXdXYrdVRyRmlKVU9MRzk2U1VQWldsRk0zbG5veURSaDBYR3owVXkwRW1XTzFHSW9GQ1lUbTB0cjNURnZZZnBsMWsxWGsxdFZVT1loc09MVWdwYit6UTRSR3Nrd0FlYmZ1UnhzK3NWMjVwUlJkM3k4K29pTFpxblJLeVVoTmY5REZBVUhBbzZkTjhhUzN5WUJEVHFnRmYxUExzVGlXdHpWMTZ4QUVVWW9ZMTRUekd1WmRJSHJuS3BGU0FKUjY5aHJXS0xNTm5ld2Z2ZmtiSUoreGhoV09Sc00yZjRSaDJvTFRRPT06c1FBWXNHK2EvSk1BUUNNZ0dpLzFvUzFtWGtRNTJ5TzN2ZUcvUHRsT3I1SjE5MzhreFdVc2JzTTh4RWFRaExyZi9oZ2llMktON2x4dkxIYWZtMHlXQVdhZTlyQ2dkdjVKRm41SG8wU1owenpiQSsySjA1Z2tXdXYrdVRyRmlKVU9MRzk2U1VQWldsRk0zbG5veURSaDBYR3owVXkwRW1XTzFHSW9GQ1lUbTB0cjNURnZZZnBsMWsxWGsxdFZVT1loc09MVWdwYit6UTRSR3Nrd0FlYmZ1UnhzK3NWMjVwUlJkM3k4K29pTFpxblJLeVVoTmY5REZBVUhBbzZkTjhhUzN5WUJEVHFnRmYxUExzVGlXdHpWMTZ4QUVVWW9ZMTRUekd1WmRJSHJuS3BGU0FKUjY5aHJXS0xNTm5ld2Z2ZmtiSUoreGhoV09Sc00yZjRSaDJvTFRRPT0=',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)