RSA在python中为URL进行加密和解密

时间:2019-02-26 09:04:50

标签: python python-2.7 encryption rsa

我的任务是加密ID并传递给url。然后,从网址中获取加密的ID并解密该ID。我必须在python中执行此任务。 我正在使用RSA算法。 我可以对ID进行加密,但是在解密时遇到了麻烦。另外我也不知道如何减少加密ID的长度。因为当我将加密的ID添加到很长的url中时。

您的帮助或任何新建议都会有所帮助。 谢谢

下面是我正在加密的代码

from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
import codecs

# Below commented code to Generate Private and Public Key
# key = RSA.generate(1024)
# private_key=key.exportKey()
# public_key=key.publickey().exportKey()

private_key = """-----BEGIN RSA PRIVATE KEY-----
    MIICXAIBAAKBgQCXmxgIXMkim2EBdiHjJLsgHxqhGUbO3n64MgAO+Ugbr2GVkchV
    aQUUWnNacmMOjq7h6OO1HLvH/tyow9d5XQlSjVlo28i9hHw40CTcBh0F3Fnzylwo
    8YHt1b4wSdO970ZnxSrtF6D8J3KPiPhzcJjrBpOU6seF46iuOwPFnjSg/QIDAQAB
    AoGAAUtvcBrYE4s/en4MxLN6mZ1KYpfO//3sbRxC3d3echtppO0CyJ/wotTcPqh9
    ahFpMuqvOcu4sCOKtNzp89JfPamHhjGU9xEGtqGWDWUrRjBAX22qq9Tkwlxhyoi1
    VYPK14nJPJYIFVA1tQvKNjQcEpN8rkaqesM9MGsbnL5r9C0CQQC4vmWhD7aHH3I7
    T9LTwvABXiaUYe39EOtJ8nc+4E9StwtUSQ/AGuGxrIyYfTHX70nWMDTikorEltWm
    rncHN1RvAkEA0hSow9/qe0CSmp5On14w6Ev+5glm6c2YqoaKAWfRggTrBQkIN1nh
    m0Wqbk4gqvxCtJ26Sgi4d62GG93WRipPUwJAe90L/qSuWII48JNgYyJ8EC6z5yCR
    k+7YEkhCsyFpjae0LNqfeMmNMLbjvQmTdZe2Balki9R8vbnznUG0BF6QeQJAdNxZ
    JNyiKv24j5oQUkarHg1oNb51KQndKr68dhuyR4lE0wA7Oc8d2KngLIv5UCQTVzWG
    Mzi2pJw6RbYZQ961UQJBAIbJOhfvy+T99aDxQKMWV0vEP93ebzlK1WW9MjhbzlIi
    UXfH1dJFtNZiZO5eM7oGl9Icyb6aGHx91c17zOptXHo=
    -----END RSA PRIVATE KEY-----"""

public_key = """-----BEGIN PUBLIC KEY-----
    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXmxgIXMkim2EBdiHjJLsgHxqh
    GUbO3n64MgAO+Ugbr2GVkchVaQUUWnNacmMOjq7h6OO1HLvH/tyow9d5XQlSjVlo
    28i9hHw40CTcBh0F3Fnzylwo8YHt1b4wSdO970ZnxSrtF6D8J3KPiPhzcJjrBpOU
    6seF46iuOwPFnjSg/QIDAQAB
    -----END PUBLIC KEY-----"""

id = "5070930456"
h = SHA256.new(id)

priv_key = RSA.importKey(private_key)
pub_key = RSA.importKey(public_key)

singer = PKCS1_v1_5.new(priv_key)
signature = singer.sign(h)

hexify = codecs.getencoder('hex')
m = hexify(signature)[0]

#Output Encrypted ID
print m

加密ID输出:313729e2535c19f6a7121a8c80529b3d49ba1cdf7277aabddd2c04ff41ee85d55f5edc1c9e798da381cc0a5aabff529be62fa7ee6be61b1a0d25c57c45c9e6f65f726bb35fd5646bf7ce495d9a12bbe88688bd287bc667b5ff0f4a90218377cc2a0454e448ab53940a2457e20553deeb7b23c78d259660e9362be572384be344

0 个答案:

没有答案