python解密rsa

  • 以下仅针对之前处理过的案例,上游提供的私钥为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
  • 使用python解密
pkcs1_key_file=r"D:\HKdata\HKkey.txt"
data_file=r'D:\20191213-03.csv'
block_lenth=128  #分段长度,从与加密时保持一致
# 从文件获取pkcs1格式的私钥
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
# 将加密的bytes分段解密,返回字符串
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)

你可能感兴趣的:(python)