Danger

Nothing here should be used for any security purposes.

  • If you need cryptographic tools in a Python environment use pyca.

  • If you need efficient and reliable abstract math utilities in a Python-like environment consider using SageMath.

RSA

Imported with:

import toy_crypto.rsa

Let’s see a simple example, from the original publication describing the RSA algorithm. This will require the text decoding scheme used then which is in toy_crypto.utils.Rsa129.decode().

import toy_crypto.rsa as rsa
from toy_crypto.utils import Rsa129

# From the challenge itself
modulus=114381625757888867669235779976146612010218296721242362562561842935706935245733897830597123563958705058989075147599290026879543541
pub_exponent=9007
ctext=96869613754622061477140922254355882905759991124574319874695120930816298225145708356931476622883989628013391990551829945157815154

# We have since learned p and q
p=3490529510847650949147849619903898133417764638493387843990820577
q=32769132993266709549961988190834461413177642967992942539798288533

priv_key = rsa.PrivateKey(p, q, pub_exponent = pub_exponent)

pub_key = priv_key.pub_key
assert pub_key.N == modulus

decrypted = priv_key.decrypt(ctext)  # This is a large int

# Now the Rsa129 text decoder
ptext = Rsa129.decode(decrypted)
print(ptext)
THE MAGIC WORDS ARE SQUEAMISH OSSIFRAGE
class toy_crypto.rsa.PublicKey(modulus: int, public_exponent: int)

Public key from public values.

Parameters:
  • modulus (int)

  • public_exponent (int)

property N: int

Public modulus N.

property e: int

Public exponent e

encrypt(message: int) int

Primitive encryption with neither padding nor nonce.

Raises:
Parameters:

message (int)

Return type:

int

class toy_crypto.rsa.PrivateKey(p: int, q: int, pub_exponent: int = 65537)

RSA private key from primes p and q.

This does not perform any sanity checks on p and q. It is your responsibility to ensure that p and q are prime

Raises:

ValueError – if e is not coprime with lcm(p - 1, q - 1).

Parameters:
decrypt(ciphertext: int) int

Primitive decryption.

Parameters:

ciphertext (int)

Return type:

int

property e: int

Public exponent.

property pub_key: PublicKey

The public key corresponding to self.

The public key does not contain any secrets.

toy_crypto.rsa.default_e() int

Returns the default public exponent, 65537

Return type:

int