Skip to content

Instantly share code, notes, and snippets.

@omsobliga
Last active September 28, 2016 11:28
Show Gist options
  • Save omsobliga/3b2141711a3dc9c0a8687c3f8f0f2ddc to your computer and use it in GitHub Desktop.
Save omsobliga/3b2141711a3dc9c0a8687c3f8f0f2ddc to your computer and use it in GitHub Desktop.
公开密钥加密 RSA
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 参考资料:
# * https://en.wikipedia.org/wiki/RSA
#
# Show RSA document:
# > from Crypto.PublicKey import RSA
# > help(RSA)
from Crypto.PublicKey import RSA
from Crypto import Random
KEY_LENGTH = 1024
def generate_key(key_length=KEY_LENGTH):
random_generator = Random.new().read
return RSA.generate(key_length, random_generator)
def encrypt(public_key, plaintext):
key = RSA.importKey(public_key)
return key.encrypt(plaintext, 0)[0]
def decrypt(private_key, ciphertext):
key = RSA.importKey(private_key)
return key.decrypt(ciphertext)
if __name__ == '__main__':
key = generate_key()
public_key = key.publickey().exportKey()
private_key = key.exportKey()
plaintext = 'abc'
ciphertext = encrypt(public_key, plaintext)
plaintext = decrypt(private_key, ciphertext)
print plaintext
print ciphertext
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment