- 以下仅针对之前处理过的案例,上游提供的私钥为java的pkcs8私钥,先在开头结尾加上文件头使其成为标准格式
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAPNCSPn5JWYP7Fwst/RP/FCsdxeoD9Pv1t3xohwJLDiXPMayfXtrwAmX+Hp2ZD9Rzb3gQlHDnanwYLgpN3ibYBxTZD/bKT/hn4w3sp.............
-----END PRIVATE KEY-----
- 将pkcs8私钥转为pkcs1私钥,之后python才能处理,生成的私钥开头为"-----BEGIN RSA PRIVATE KEY-----"
openssl rsa -in /c/Users/pkcs8.txt -out /c/Users/HKkey.txt
pkcs1_key_file=r"D:\HKdata\HKkey.txt"
data_file=r'D:\20191213-03.csv'
block_lenth=128
def getPrivateKey(pkcs1_key_file):
with open(pkcs1_key_file, 'r') as privatefile:
p = privatefile.read()
privkey = rsa.PrivateKey.load_pkcs1(p.encode('utf8'))
return privkey
def decryptByPrivateKey_byte2string(bytes,privkey,block_lenth):
text = []
for i in range(0, len(bytes), block_lenth):
cont = bytes[i:i + block_lenth]
text.append(rsa.decrypt(cont, privkey).decode('utf8'))
return ''.join(text)
def decryptByPrivateKey_pkcs1_block(pkcs1_key_file,data_file,block_lenth):
strlist=[]
privkey=getPrivateKey(pkcs1_key_file)
with open(data_file, 'rb') as f:
t=map(lambda x:x.decode(),f.readlines())
for s in t:
strlist.append(decryptByPrivateKey_byte2string(base64.decodebytes(s.encode()),privkey,block_lenth))
return '\n'.join(strlist)