0x01 rsa private key encrypt
java to python pkcs8 to pkcs1 format
openssl rsa -in sign.pem -out sign_p1.pem
import M2Crypto
import base64
private_key=b'''
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCV0tKmYsopD9tQxyUbEe4cOkeWb3MCA9aTGWhON5V90el2XK/v
rxUfm9LYGUsc0V4G5PUGteYqdKlLjwwjW/ghTBbWYIIFQGKvlsDK/ifQj35MY42f
TVGq8HKwjDEX9N36vcl1QPJTenAJnjQMcWpdiYju+HVGGJFQ+QJl3AcZGwIDAQAB
AoGAG/ooV+Wutog9fhIR/cIVYrQHVjItmby5vvJJpgF/KuWd4Pph6DIbkbF5Z90h
R5pZIpRypPQmrNroGjH2JEwyQ0sAeG0ncHfG/u9XRbYz3w7+kefG0Z81UfEwAmUl
IxWAD/1vtL3MHampZhio38zt2F56eKc35kMEe140VdZMuLECQQDtXGMTYIfpY2sg
mOJDOx2IC5sGawIx0Otf+oNtrsPksntl6KT0o87VcMZTfbYtzpblO2M7k/+FtgVX
wq0BNjLdAkEAoZaxGi0g0CBNvgcA1taqr3kIgLkny9Nk2e+hG9dgxKwSqVdKw9vQ
Cg2IyB51mqL8kBP/FrE3SLTBbaDd00YQVwJBANEsK3t2BA/etxdg43RP8jRj1dgQ
ET0JWYOZZp0P+D3gM/KY1FVqzek2mvAUxqkTd9LHRSnJwNJ6l7bBLmj09FkCQET+
weoKYNtdH7TG6r3Q9RptlIraBDsMrSA9KE5p/UCctG8n/Z15avAP7Vp9XvvDIhIm
56F508AwpfK4YF8IqIsCQFgDnX48zBU2Py6FHJW4Mmu2EqCgeAJurjyOdH3H9eFJ
749JS/OMJooxzoUoxtT2SIspNe6nTVZdKvna5scRCfk=
-----END RSA PRIVATE KEY-----
'''
def private_encrypt(data):
rsa_pri = M2Crypto.RSA.load_key_string(private_key)
ctxt_pri = rsa_pri.private_encrypt(data, M2Crypto.RSA.pkcs1_padding)
ctxt64_pri = base64.b64encode(ctxt_pri)
return ctxt64_pri
print(private_encrypt(b"Test123456").decode())
0x02 public decrypt
import M2Crypto , base64
def public_decrypt(msg):
sign_pub=b'''
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqtXUIVoPUcBV1Wl3g8rGGNvMY
ImonQdMC1Y8USwIwf7Y0GcBP/h6fAJPAS9//qYZzy8ZfDKH1+ezifFFCUTCCa/8a
YFoms223okyzeTlUIRHbIkto1JxYOazbsE6+KmE+yJiij4839SYuC1KsLWT82uHE
A3Hau/DTzW4g4xhvzQIDAQAB
-----END PUBLIC KEY-----
'''
bio = M2Crypto.BIO.MemoryBuffer(sign_pub)
rsa_pub = M2Crypto.RSA.load_pub_key_bio(bio)
ctxt_pri = base64.b64decode(rsa_pub)
output = rsa_pub.public_decrypt(ctxt_pri, M2Crypto.RSA.pkcs1_padding)
return output