如何从 pyNaCl 中的值加载 SigningKey?

How to load SigningKey from its value in pyNaCl?

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

这是生成新 SigningKey 和 public 密钥的代码。

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,但唯一可用的选项是使用种子生成一个新的。

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

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)