将RSA解密函数从Golang转换为Python

时间:2018-01-08 09:35:56

标签: python python-2.7 go rsa

我需要Python中这个golang函数的等价物:

func RsaDecrypt(ciphertext []byte) ([]byte, error) {
    block, _ := pem.Decode(privateKey)
    if block == nil {
        return nil, errors.New("private key error!")
    }
    priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}

我是一名python开发人员,并不了解其工作原理。我创建了这个函数,但它不一样:

import rsa

with open("rsa.key") as f:
    priv_key_pkcs1 = f.read()

priv_key = rsa.PrivateKey.load_pkcs1(priv_key_pkcs1)
line = '''
Lyzkh2pqrisgM_p32O6FmA8oDvzaimvrU9zyd0vyW6HBM2BznuHLbAYUMGp5oYgEHCxmZTWDs67Jt5AGulfn-LrcewCQi89wrb00ZvP69YdjwBe-7aoXBG4_zNMZ7ecLgd8WzUqBGGtVvUhCTVSBBi85mNMSCcgYHt__PFefRHZE09nHnEX25w6iR0ZZlQxuESBkuqTcs8qjUhs2Guin1xBMSWRINj4JDdCjIVHV4hdSjrINgFU-VF1sYFRibWcboYlXifROOxCF50MGtIBkcf7dnqsrR8HEXgZLnCyikhhlQAFoh2hsj4lPWNpWum-dBWj-B0b8P-hRmermDzcPqA==
'''
encrypted = line.decode('base64')
decrypted = rsa.decrypt(encrypted, priv_key)
print decrypted

任何人都可以帮我转换Python中的golang函数吗?或者告诉我一些我在实际python代码中出错的信息?

1 个答案:

答案 0 :(得分:1)

您正在使用错误的base64解码器来解码您的密文。从密文中出现的“ - ”和“_”字符可以看出,它是使用base64的URL安全变体编码的。要对此进行解码,您应该使用base64模块,例如

import base64

line = '''
Lyzkh2pqrisgM_p32O6FmA8oDvzaimvrU9zyd0vyW6HBM2BznuHLbAYUMGp5oYgEHCxmZTWDs67Jt5AGulfn-LrcewCQi89wrb00ZvP69YdjwBe-7aoXBG4_zNMZ7ecLgd8WzUqBGGtVvUhCTVSBBi85mNMSCcgYHt__PFefRHZE09nHnEX25w6iR0ZZlQxuESBkuqTcs8qjUhs2Guin1xBMSWRINj4JDdCjIVHV4hdSjrINgFU-VF1sYFRibWcboYlXifROOxCF50MGtIBkcf7dnqsrR8HEXgZLnCyikhhlQAFoh2hsj4lPWNpWum-dBWj-B0b8P-hRmermDzcPqA==
'''

encrypted = base64.urlsafe_b64decode(line)
print len(encrypted)
print encrypted.encode('hex')