首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从pyNaCl中的值加载SigningKey?

如何从pyNaCl中的值加载SigningKey?
EN

Stack Overflow用户
提问于 2019-01-08 22:07:36
回答 1查看 1K关注 0票数 1

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

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

代码语言:javascript
复制
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,但唯一可用的选项是使用种子生成一个新的种子。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-25 08:30:18

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

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54093558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档