Python密码学库
2026/5/29工具工具Pythonpycryptodomegmpy2sympy大约 4 分钟
Python密码学库
链接
是什么
Python 密码学库是 Crypto 题最常用的脚本基础。入门阶段重点掌握 pycryptodome、gmpy2、sympy,再按题目需要补 z3-solver、sage 等工具。
常见用途:
- 大整数和模运算
- RSA 解密与攻击脚本
- AES/DES/RC4 加解密
- 编码转换和字节处理
- 因数分解、逆元、同余方程
安装与配置
建议在虚拟环境中安装:
python3 -m venv crypto-env
source crypto-env/bin/activate
python3 -m pip install pycryptodome gmpy2 sympy z3-solverWindows:
py -m venv crypto-env
crypto-env\Scripts\activate
py -m pip install pycryptodome gmpy2 sympy z3-solver如果 gmpy2 安装失败,优先尝试更新 pip:
python3 -m pip install --upgrade pip wheel setuptools
python3 -m pip install gmpy2基本用法
字节和整数互转
from Crypto.Util.number import bytes_to_long, long_to_bytes
m = bytes_to_long(b"flag{test}")
print(m)
print(long_to_bytes(m))求逆元
from Crypto.Util.number import inverse
d = inverse(e, phi)AES 解密
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
cipher = AES.new(key, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct), 16)gmpy2 开根
import gmpy2
root, exact = gmpy2.iroot(c, 3)
if exact:
print(root)sympy 分解
from sympy import factorint
print(factorint(n))pycryptodome 更多用法
AES 加密模式
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
# ECB 模式
cipher = AES.new(key, AES.MODE_ECB)
ct = cipher.encrypt(pad(pt, 16))
pt = unpad(cipher.decrypt(ct), 16)
# CBC 模式
cipher = AES.new(key, AES.MODE_CBC, iv)
ct = cipher.encrypt(pad(pt, 16))
pt = unpad(cipher.decrypt(ct), 16)
# CTR 模式
from Crypto.Cipher import AES
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
ct = cipher.encrypt(pt)
pt = cipher.decrypt(ct)
# GCM 模式
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
ct, tag = cipher.encrypt_and_digest(pt)
pt = cipher.decrypt_and_verify(ct, tag)DES 加密
from Crypto.Cipher import DES
cipher = DES.new(key, DES.MODE_ECB)
ct = cipher.encrypt(pad(pt, 8))
pt = unpad(cipher.decrypt(ct), 8)RC4 加密
from Crypto.Cipher import ARC4
cipher = ARC4.new(key)
ct = cipher.encrypt(pt)
pt = cipher.decrypt(ct)RSA 基本操作
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 读取公钥
key = RSA.import_key(open("pub.pem").read())
print(key.n, key.e)
# 读取私钥
key = RSA.import_key(open("priv.pem").read())
print(key.d)
# RSA 加解密
cipher = PKCS1_OAEP.new(key)
ct = cipher.encrypt(b"secret")
pt = cipher.decrypt(ct)哈希计算
import hashlib
# MD5
h = hashlib.md5(b"data").hexdigest()
# SHA1
h = hashlib.sha1(b"data").hexdigest()
# SHA256
h = hashlib.sha256(b"data").hexdigest()HMAC
import hmac
import hashlib
h = hmac.new(key, msg, hashlib.sha256).hexdigest()gmpy2 更多用法
大整数运算
import gmpy2
# 精确开根
root, exact = gmpy2.iroot(n, 3)
# 逆元
inv = gmpy2.invert(e, phi)
# 幂运算
result = gmpy2.powmod(base, exp, mod)
# 最大公约数
g = gmpy2.gcd(a, b)
# 扩展 GCD
g, s, t = gmpy2.gcdext(a, b)素数判定
import gmpy2
# 素数判定
is_prime = gmpy2.is_prime(n)
# 下一个素数
next_p = gmpy2.next_prime(n)多精度浮点
import gmpy2
gmpy2.get_context().precision = 200
result = gmpy2.sqrt(gmpy2.mpfr(2))sympy 更多用法
因数分解
from sympy import factorint, divisors
# 因数分解
factors = factorint(n)
# 返回 {p1: e1, p2: e2, ...}
# 所有因子
divs = divisors(n)符号计算
from sympy import symbols, solve, Eq
x = symbols('x')
eq = Eq(x**2 - 5*x + 6, 0)
solutions = solve(eq, x)中国剩余定理
from sympy.ntheory.modular import crt
remainders = [2, 3, 5]
moduli = [3, 5, 7]
result = crt(moduli, remainders)椭圆曲线
from sympy import mod_inverse
# 椭圆曲线点加
def ec_add(P, Q, a, p):
if P is None:
return Q
if Q is None:
return P
if P[0] == Q[0] and P[1] != Q[1]:
return None
if P == Q:
lam = (3 * P[0]**2 + a) * mod_inverse(2 * P[1], p) % p
else:
lam = (Q[1] - P[1]) * mod_inverse(Q[0] - P[0], p) % p
x3 = (lam**2 - P[0] - Q[0]) % p
y3 = (lam * (P[0] - x3) - P[1]) % p
return (x3, y3)z3-solver 用法
约束求解
from z3 import *
# 定义变量
x = BitVec('x', 32)
y = BitVec('y', 32)
# 创建求解器
s = Solver()
# 添加约束
s.add(x + y == 100)
s.add(x - y == 20)
# 求解
if s.check() == sat:
m = s.model()
print(m[x], m[y])逆向算法求解
from z3 import *
# 假设算法: result = (input ^ 0x55) + 3
input_var = BitVec('input', 8)
result = (input_var ^ 0x55) + 3
s = Solver()
s.add(result == target_value)
if s.check() == sat:
print(s.model()[input_var])CTF常用技巧
RSA 常用模板
from Crypto.Util.number import inverse, long_to_bytes
phi = (p - 1) * (q - 1)
d = inverse(e, phi)
m = pow(c, d, n)
print(long_to_bytes(m))不要混用 crypto 和 pycryptodome
Python 里常见包名是 Crypto,但安装包推荐 pycryptodome。如果导入异常,检查是否装了旧的 crypto 包。
先写清楚数据类型
Crypto 脚本最常见错误是 bytes、str、int 混用。建议变量名体现类型:
ct_hex
ct_bytes
ct_int调试技巧
# 打印中间值
print(f"n = {n}")
print(f"e = {e}")
print(f"phi = {phi}")
print(f"d = {d}")
# 验证结果
assert pow(pow(m, e, n), d, n) == m常见问题
ModuleNotFoundError: No module named Crypto
安装 pycryptodome:
python3 -m pip install pycryptodomeinverse 报错
说明逆元不存在,通常是 gcd(e, phi) != 1,要重新判断题目参数。
iroot 不是精确根
低指数攻击只有在 m^e < n 或未取模条件满足时才直接开根。
gmpy2 安装失败
# Ubuntu/Debian
sudo apt install libgmp-dev libmpfr-dev libmpc-dev
python3 -m pip install gmpy2
# 或使用 conda
conda install gmpy2关联
- 编码、哈希与加密
- RSA基本概念
- AES基本概念
- 随机数与种子
- SageMath
- RsaCtfTool