网上提供的方案描述都不太清晰,主要需要注意的是Py中使用的是pkcs1标准,注意这一点即可
使用AES加密时候需要注意填充模式
py
import os
import uuid
import base64
import wmi
import json
from datetime import datetime
import random
import rsa
import binascii
from rsa import transform, core
from binascii import b2a_hex, a2b_hex
def getAESRomdomKey():
"""
获取密钥 n 密钥长度
:return:
"""
n = 16
c_length = int(n)
source = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
length = len(source) - 1
result = ''
for i in range(c_length):
result += source[random.randint(0, length)]
return result
def add_to_16(text):
"""
明文使用PKCS7填充
最终调用AES加密方法时,传入的是一个byte数组,要求是16的整数倍,因此需要对明文进行处理
:param text: 待加密内容(明文)
:return:
"""
bs = AES.block_size # 16
length = len(text)
bytes_length = len(bytes(text, encoding='utf-8'))
# tips:utf-8编码时,英文占1个byte,而中文占3个byte
padding_size = length if(bytes_length == length) else bytes_length
padding = bs - padding_size % bs
# tips:chr(padding)看与其它语言的约定,有的会使用'\0'
padding_text = chr(padding) * padding
# print(text + padding_text)
return (text + padding_text).encode('utf-8')
def aes_ECB_Encrypt(text, key): # ECB模式的加密函数,data为明文,key为16字节密钥
key = key.encode('utf-8')
mode = AES.MODE_ECB
text = add_to_16(text)
cryptos = AES.new(key, mode)
cipher_text = cryptos.encrypt(text)
# return b2a_hex(cipher_text)
result = base64.b64encode(cipher_text).decode('utf8')
return result
def aes_ECB_Decrypt(text, key): # ECB模式的解密函数,data为密文,key为16字节密钥
key = key.encode('utf-8')
# key = base64.b64decode(key.encode('utf-8'))
mode = AES.MODE_ECB
cryptor = AES.new(key, mode)
# plain_text = cryptor.decrypt(a2b_hex(text))
plain_text = cryptor.decrypt(base64.b64decode(text.encode('utf-8')))
result= bytes.decode(plain_text).rstrip('\0')
# print(result)
length = len(result)
# print(result[length-1])
unpadding = ord(result[length - 1])
# print(unpadding)
finalText = result[0:length - unpadding]
# print(finalText)
return finalText
"""
data为base64字符串
"""
def rsa_Encrypt(data):
# public_key, private_key = rsa.newkeys(2048)
with open(r'C:\Users\ives\Desktop\applicense\RSA\pkcs1_rsa_public_key_2048.pub', 'r') as f:
public_key = rsa.PublicKey.load_pkcs1_openssl_pem(f.read().encode())
encrypted_data = rsa.encrypt(data, public_key)
# print(encrypted_data)
return encrypted_data
"""
data为base64字符串
"""
def rsa_Decrypt(data):
with open(r'C:\Users\ives\Desktop\applicense\RSA\pkcs1.pem', 'r') as f:
private_key = rsa.PrivateKey._load_pkcs1_pem(f.read().encode())
secretTextByte = base64.b64decode(data)
decrypted_data = rsa.decrypt(secretTextByte, private_key)
print(decrypted_data)
c#
标签:AES,加密,c#,text,length,result,key,import,data
From: https://www.cnblogs.com/ives/p/17781121.html