如何从pyNaCl中的值加载SigningKey?

时间:2019-01-08 14:07:36

标签: python python-cryptography pynacl

我需要在pyNaCl中生成签名和私钥,并将它们存储在某个地方。之后,我需要使其能够从字符串中加载它们。

这是一个生成新的SigningKey和公共密钥的代码。

def gen_keys():
    global sk
    sk = nacl.signing.SigningKey.generate()
    global pk
    pk = sk.verify_key
    pk = pk.encode(encoder=nacl.encoding.HexEncoder)
    sk = sk.encode(encoder=nacl.encoding.HexEncoder)
    pk_list.insert(INSERT, "=PRIVATE=\n")
    pk_list.insert(INSERT, sk)
    pk_list.insert(INSERT, "\n=PUBLIC=\n")
    pk_list.insert(INSERT, pk)
    pk_list.insert(INSERT, "\n\n")

我希望从其值加载SigningKey,但是唯一可用的选项是使用种子生成一个新的签名。

1 个答案:

答案 0 :(得分:0)

此代码将执行您想要的操作:

import nacl.encoding
import nacl.signing
import os

# Generate a new signing key
signing_key_original = nacl.signing.SigningKey.generate()
# Obtain its verify key (which we will use to test the reloaded signing key)
verify_key = signing_key_original.verify_key
# Export the signing key to hex (binary)
private_key_bytes = signing_key_original.encode(encoder=nacl.encoding.HexEncoder)
# Save the signing key to the environment variables
if os.supports_bytes_environ:
    # The operating system supports hex-encoded environment variables
    os.environb['private_key_bytes'] = private_key_bytes
else:
    # The operating system does not support hex-encoded environment variables - decode to utf-8
    private_key_utf8 = private_key_bytes.decode('utf-8')
    os.environ['private_key_utf8'] = private_key_utf8

# Now reverse the process (by loading a signing key from the appropriate environment variable)
if os.supports_bytes_environ:
    # The operating system supports hex-encoded environment variable
    private_key_bytes_loaded = os.environb['private_key_bytes']
else:
    # The operating system does not support hex-encoded environment variables - look for the utf-8 encoded private key
    private_key_utf8_loaded = os.environ['private_key_utf8']
    private_key_bytes_loaded = str.encode(private_key_utf8_loaded)

# Create a PyNaCL signing key from the loaded private key
signing_key_loaded = nacl.signing.SigningKey(private_key_bytes_loaded, encoder=nacl.encoding.HexEncoder)
# Sign a new message
signed_with_loaded = signing_key_loaded.sign(b"PyNaCl signing keys can be exported, saved and loaded")
# Verify the new signed message with the original verify key (the one we created with signing_key_original)
verify_key.verify(signed_with_loaded)