Utility

Conversions

1 byte = 8 bit = 2 hex

int —> char

chr()

char —> int

ord()

bytes —> HEX

<BYTES>.hex()

HEX —> bytes

bytes.fromhex(<HEX>)

HEX —> int

int(<HEX>, 16)

int —> HEX

format(<INT>, 'x') # ff
hex(<INT>) # 0xff

bytes —> int

int.from_bytes(<BYTES>, <endianes>)

From Crypto.Util.number

bytes_to_long(<BYTES>)

int —> bytes

<INT>.to_bytes(<nblock>, <endianes>)

From Crypto.Util.number

long_to_bytes(<INT>)

bytes —> Base64

From base64

b64encode(<BASE64>)

Base64 —> bytes

From base64

b64decode(<BYTES>)

bytes XOR bytes

From PwnTools

xor()

Functions

GCD

From sympy

gcd(<A>, <B>)

Modular Inverse

From Crypto.Util.number

inverse(<NUM>, <MOD>)

From sympy

mod_inverse(<NUM>, <MOD>)

Extended Euclidean

X*A + Y*B = GCD(A,B)

From sympy

X, Y, MCD = gcdex(<A>, <B>)

Chinese Remainder Theorem

x % M1 = U1 x = U1 % M1 x % M2 = U2 x = U2 % M2

From sympy.ntheory.modular

crt([M1, M2, …], [U1, U2, …])

Congruence Resolution

N1 == N2 (mod M) Solves the modules and returns if they are congruent modulo M

From sympy.ntheory.modular

solve_congruence((N1, M), (N2, M))

A*? = B mod N

x such that A*x = B mod N

From Crypto.Util.number

inverse(A, N)*B)%N)

From sympy

mod_inverse(A, N)*B)%N)

Discrete Logarithm

Given a prime p, g is defined to be a primitive root of p if for every y ∈ {1, .... , p-1} there exists an i such that: y = g^i mod p

From sympy.ntheory

discrete_log(p, y, g)

N-th root

N-th root of v. Returns 2 values, the approximate root, and if it is perfect (with or without approximation).

From gmpy2

iroot(v, n)

N-th root Extended

N-th root of A (A^(1/N))

From decimal.Decimal

int(pow(Decimal(<A>)), Decimal(Decimal('1')/Decimal(<N>))))

Large Number

From decimal.Decimal, decimal.getcontext

getcontext().prec = 1000
Decimal(<N>)

Modular Square Root

Find the square root of x mod p (hard problem, like factorization).

From sympy

sqrt_mod(x, p)

SAT & SMT solver

From z3

pip install z3-solver
# Define variables 
a, b = Ints('a b')
# Define equations
equation1 = a + b == 50 
equation2 = a * b == 625
# Create Solver 
s = Solver()
# Add equations 
s.add(equation1) 
s.add(equation2)
# If there are solutions extract them
if s.check() == sat: 
  model = s.model() 
  a_val = model[a].as_long() 
  b_val = model[b].as_long()

For my setting on macOS

import sys
sys.path.append("/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/")
from sage.all import *

From sage

Discrete Logarithm

Calculate i in: RESULT = BASE^i mod M

discrete_log(Mod(<RESULT>, <M>), Mod(<BASE>, <M>), ord=<EULER_FUNCTION>)

Factorization

Gets the factorization of the number n. Returns the list of factors.

factor(n)

Chinese Remainder Theorem

x % M1 = U1 x = U1 % M1 x % M2 = U2 x = U2 % M2

crt([U1, U2, …], [M1, M2, …])

Last updated