Noc*_*wer 18 python encryption-asymmetric python-3.x
是否有一个模块,我的搜索无法发现,将允许编写如下代码?想要编写这样的代码的原因并不重要.我所追求的是一些代码,它有一个简单的API来生成公钥和私钥字节密钥,并使用这些密钥轻松编码和解码数据.
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
Run Code Online (Sandbox Code Playgroud)
大多数似乎可用的东西需要下载一个包,并且只能在Python 2.x上运行.查找使用PEM文件或其他类型证书的库也很常见.我想避免处理这些文件,动态生成公钥和私钥,并快速处理内存中的数据.
Ray*_*ger 32
公钥加密不在标准库中.虽然PyPi上有一些第三方库:
如果你对它背后的数学感兴趣,Python可以很容易地进行实验:
code = pow(msg, 65537, 5551201688147) # encode using a public key
plaintext = pow(code, 109182490673, 5551201688147) # decode using a private key
Run Code Online (Sandbox Code Playgroud)
密钥生成涉及更多一点.下面是如何使用urandom作为熵源在内存中进行密钥生成的简化示例.代码在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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27749 次 |
| 最近记录: |