生活不易,一直在前进,一直在学习
工作中用到了RSA非对称加密,与java进行对接
对方实现的是分段加密,分段解密
python生成rsa加密的公钥和密钥
在线生成rsa公钥密钥
http://tool.chacuo.net/cryptrsakeyvalid
PKCS1私钥生成
openssl genrsa -out private.pem 1024
PKCS1私钥转换为PKCS8(该格式一般Java调用)
openssl pkcs8 -topk8 -inform PEM -in private.pem -outform pem -nocrypt -out pkcs8.pem
PKCS8格式私钥转换为PKCS1(传统私钥格式)
openssl rsa -in pkcs8.pem -out pkcs1.pem
python也可以实现分段加密,分段解密
def minsheng_encrypt(biz_content):
'''
rsa加密
:param biz_content:
:param public_key:
:return:
'''
public_key = open('min.pem').read()
public_key = rsa.PublicKey.load_pkcs1_openssl_pem(public_key)
biz_content = biz_content.encode('utf-8')
# 1024bit key
default_encrypt_length = 117
len_content = len(biz_content)
if len_content < default_encrypt_length:
return base64.b64encode(rsa.encrypt(biz_content, public_key))
offset = 0
params_lst = []
while len_content - offset > 0:
if len_content - offset > default_encrypt_length:
params_lst.append(rsa.encrypt(biz_content[offset:offset+default_encrypt_length], public_key))
else:
params_lst.append(rsa.encrypt(biz_content[offset:], public_key))
offset += default_encrypt_length
target = ''.join(params_lst)
return base64.b64encode(target)
def minsheng_decrypt(biz_content):
'''
rsa解密
:param biz_content:
:param private_key:
:return:
'''
private_key = open('ik.pem').read()
priv_key = rsa.PrivateKey._load_pkcs1_pem(private_key)
biz_content = base64.b64decode(biz_content.encode('utf-8'))
# 1024bit key
default_length = 128
len_content = len(biz_content)
if len_content < default_length:
return rsa.decrypt(biz_content, priv_key)
offset = 0
params_lst = []
while len_content - offset > 0:
if len_content - offset > default_length:
params_lst.append(rsa.decrypt(biz_content[offset: offset+default_length], priv_key))
else:
params_lst.append(rsa.decrypt(biz_content[offset:], priv_key))
offset += default_length
target = ''.join(params_lst)
return target