[Fixed]-Converting RSA encryption code from php to python

1👍

They use this class for RSA

https://github.com/AlaFalaki/Pclass/blob/master/libraries/rsa.class.php

My advice: Run away screaming.

RSA is a mine field of security issues. There are a lot of things that you can screw up. So when someone implements the primitives in PHP using the BC extension, that’s the security equivalent of standing naked in front of a firing squad and expecting to have no holes.

Recommendation: Use Libsodium Instead

There are both PHP and Python bindings available for libsodium.

If RSA is Unavoidable…

If you really want RSA and not modern cryptography, check out phpseclib.

<?php
use 
$rsa = new RSA();

// HIGHLY RECOMMENDED FOR SECURITY:
$rsa->setEncryptionMode(RSA::ENCRYPTION_OAEP);
$rsa->setMGFHash('sha256');

$rsa->loadKey($yourPEMencodedRSAPublicKey);
$ciphertext = $rsa->encrypt($plaintext);

If you’re going to encrypt with RSA, you must follow these cryptography rules. If your library doesn’t let you follow these rules, it’s time to switch to libsodium.

Also note that encrypting large messages with RSA is both slow and dangerous: There’s usually nothing preventing messages from being reordered, which can be really bad.

The solution here is: Use symmetric-key authenticated encryption and use RSA to encrypt the public key. That’s what EasyRSA does, although I’m not aware of any Python equivalents, so I can’t recommend that as a solution.

Of course, if you use libsodium’s crypto_box API you don’t have to worry about that!

Leave a comment