是否有一个模块在我的搜索中无法发现允许编写如下代码?想要编写这样的代码的原因并不重要。我所追求的只是一些具有简单 API 的代码,用于生成公共(public)和私有(private)字节 key ,并使用这些 key 轻松编码和解码数据。
import module, os
method, bits, data = 'RSA', 1024, os.urandom(1024)
public, private = module.generate_keys(method, bits)
assert isinstance(public, bytes) and isinstance(private, bytes)
assert module.decode(module.encode(data, private), public) == data
assert module.decode(module.encode(data, public), private) == data
大多数似乎可用的功能都需要下载一个包,并且只能在 Python 2.x 上运行。找到使用 PEM 文件或其他类型证书的库也很常见。我希望避免处理此类文件,即时生成公钥和私钥,并快速处理内存中的数据。
最佳答案
公钥加密不在标准库中。不过,PyPi 上有一些第三方库:
如果您对它背后的数学感兴趣,Python 可以让您轻松进行实验:
code = pow(msg, 65537, 5551201688147) # encode using a public key
plaintext = pow(code, 109182490673, 5551201688147) # decode using a private key
key 生成涉及更多。这是一个简化的示例,说明如何使用 urandom 作为熵源在内存中生成 key 。代码在Py2.6和Py3.x下都运行:
import random
def gen_prime(N=10**8, bases=range(2,20000)):
# XXX replace with a more sophisticated algorithm
p = 1
while any(pow(base, p-1, p) != 1 for base in bases):
p = random.SystemRandom().randrange(N)
return p
def multinv(modulus, value):
'''Multiplicative inverse in a given modulus
>>> multinv(191, 138)
18
>>> 18 * 138 % 191
1
'''
# http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
x, lastx = 0, 1
a, b = modulus, value
while b:
a, q, b = b, a // b, a % b
x, lastx = lastx - q * x, x
result = (1 - lastx * modulus) // value
return result + modulus if result < 0 else result
def keygen(N):
'''Generate public and private keys from primes up to N.
>>> pubkey, privkey = keygen(2**64)
>>> msg = 123456789012345
>>> coded = pow(msg, 65537, pubkey)
>>> plain = pow(coded, privkey, pubkey)
>>> assert msg == plain
'''
# http://en.wikipedia.org/wiki/RSA
prime1 = gen_prime(N)
prime2 = gen_prime(N)
totient = (prime1 - 1) * (prime2 - 1)
return prime1 * prime2, multinv(totient, 65537)
关于python - 使用标准库的 Python 中的私有(private)/公共(public)加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8539441/