Skip to content

Instantly share code, notes, and snippets.

@koolay
Last active July 3, 2020 14:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koolay/d6a909da6dcb82eeb6daeae47ee86bc6 to your computer and use it in GitHub Desktop.
Save koolay/d6a909da6dcb82eeb6daeae47ee86bc6 to your computer and use it in GitHub Desktop.
rsa.python
import base64
import io
from Crypto import Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP as PKCS1_OAEP_Cipher
def gen_key_pair(passpharse=None):
"""
生成key
eg:
pem, pub = gen_key_pair('my password')
print('Private Key:\n%s\n' % pem)
print('Public Key:\n%s\n' % pub)
:param passpharse:
:return:
"""
random_generator = Random.new().read
key = RSA.generate(2048, random_generator)
return key.exportKey(passphrase=passpharse), key.publickey().exportKey()
def rsa_encrypt(message, pub):
"""
加密数据
eg:
message = 'To be encrypted'
encdata = rsa_encrypt(message.encode('utf-8'), pub)
print('Encrypted Message:\n', encdata)
:param message: 字符串
:param pub:公钥
:return:
"""
keystream = io.BytesIO(pub)
pubkey = RSA.importKey(keystream.read())
#h = SHA.new(message)
cipher = PKCS1_OAEP_Cipher.new(pubkey)
return base64.b64encode(cipher.encrypt(message))
def rsa_decrypt(ciphertext, pem, passphrase=None):
"""
解密数据
eg:
decdata = rsa_decrypt(encdata, pem, passphrase)
print('Decrypted Message:\n', decdata)
:param ciphertext:
:param pem: 私钥
:param passphrase:
:return:
"""
ciphertext = base64.b64decode(ciphertext)
keystream = io.BytesIO(pem)
pemkey = RSA.importKey(keystream.read(), passphrase=passphrase)
cipher = PKCS1_OAEP_Cipher.new(pemkey)
return cipher.decrypt(ciphertext)
def sign(message, pem, passphrase=None):
keystream = io.BytesIO(pem)
pub_key = RSA.importKey(keystream.read(), passphrase)
data_hash = SHA.new(message.encode('utf-8'))
_signer = PKCS1_v1_5.new(pub_key)
return base64.b64encode(_signer.sign(data_hash))
def verify_sign(message, signature, pub, passphrase=None):
keystream = io.BytesIO(pub)
pub_key = RSA.importKey(keystream.read(), passphrase)
signature = base64.b64decode(signature)
data_hash = SHA.new(message.encode('utf-8'))
_signer = PKCS1_v1_5.new(pub_key)
return _signer.verify(data_hash, signature)
def _write_file():
pem, pub = gen_key_pair()
with open('/tmp/rsa.pem', 'wb') as f:
f.write(pem)
with open('/tmp/rsa.pub', 'wb') as f:
f.write(pub)
def _read_rsa():
with open('/tmp/rsa.pem', 'rb') as f:
pem = f.read()
with open('/tmp/rsa.pub', 'rb') as f:
pub = f.read()
return pem, pub
if __name__ == '__main__':
pem, pub = _read_rsa()
encrypted = rsa_encrypt('haha'.encode('utf-8'), pub)
decrypted = rsa_decrypt(encrypted, pem, None)
print(decrypted)
@koolay
Copy link
Author

koolay commented Dec 24, 2017

requirement: pip install pycryptodome

@koolay
Copy link
Author

koolay commented Dec 24, 2017

php

<?php

$pub = file_get_contents('/tmp/rsa.pub');

if (openssl_public_encrypt('hello, rsa', $encrypted, $pub, OPENSSL_PKCS1_OAEP_PADDING)) {
    $data = base64_encode($encrypted);
    if (isset($data)) {
        echo $data;
    }
}

$signature = 'LLVRgsnKwe2eHM3Pswj8flnCDTr13jbXbTL7pYwCpYWkjsVKW9Bv3i8kn9I+bSgm8T2EpSB6T97v08BUt3tKAc8g/l28It28cOF+bj0+7KS7Z9Y7DuUsXsOZqCX9fq/WizNg1+11psA3Dr7ty763TCKscmvo1t1ykr1MaNe9ZreFxZkBB5+B/vMfv0by8rABwgiVgemdvsmmYH3OgJTqi4RpvPjwLJWVr2FrZmgP
bOU1N53LoXM3Vc3xR9gDVnC+5j+ccmSgPf1Jf2YY5AXM4+Yy0egLqlthwPoywon3aqEpGSQpMMDuxirJs2IvebmPSnHvrviwiNwgGlp+6fPY6g==';
$pub = file_get_contents('/tmp/rsa.pub');
$message = 'hello';
$result = openssl_verify($message, base64_decode($signature), $pub, OPENSSL_ALGO_SHA1);
var_dump($result);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment