Skip to content

Instantly share code, notes, and snippets.

@r-vdp

r-vdp/sealing.py Secret

Last active January 27, 2023 11:03
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save r-vdp/b7ac0106a4fd395ee1c37bfe6f552a36 to your computer and use it in GitHub Desktop.
Save r-vdp/b7ac0106a4fd395ee1c37bfe6f552a36 to your computer and use it in GitHub Desktop.
#! /usr/bin/env nix-shell
#! nix-shell -i python3 --packages python3Packages.pynacl
from base64 import b64encode, b64decode
from nacl.encoding import RawEncoder
from nacl.public import SealedBox
from nacl.signing import SigningKey, VerifyKey
key_length = 32
private_key_signature = b'\x00\x00\x00\x40'
public_key_signature = b'\x00\x00\x00\x20'
openssh_pub = "AAAAC3NzaC1lZDI1NTE5AAAAIGHiwdXSxs4ISO6VFQeig2QQ88BToaWkuyB5TBHNWSla"
openssh_priv = "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW" + \
"QyNTUxOQAAACBh4sHV0sbOCEjulRUHooNkEPPAU6GlpLsgeUwRzVkpWgAAAJg0HF8oNBxf" + \
"KAAAAAtzc2gtZWQyNTUxOQAAACBh4sHV0sbOCEjulRUHooNkEPPAU6GlpLsgeUwRzVkpWg" + \
"AAAEDJdaAVoKjmCUq071/xUqmlNOiJXehg5QgEyGYai+Kpb2HiwdXSxs4ISO6VFQeig2QQ" + \
"88BToaWkuyB5TBHNWSlaAAAAD3JhbXNlc0BiZW51YzAwMgECAwQFBg=="
# Extract length bytes counting from the first occurence of the given signature.
def bytes_after(signature, length, bytestr):
start = bytestr.find(signature) + len(signature)
return bytestr[start:start+length]
def extract_curve_private_key(openssh_priv_key):
openssh_priv_bytes = b64decode(openssh_priv_key)
priv_bytes = bytes_after(private_key_signature,
key_length,
openssh_priv_bytes)
nacl_priv_ed = SigningKey(seed=priv_bytes, encoder=RawEncoder)
return nacl_priv_ed.to_curve25519_private_key()
def extract_curve_public_key(openssh_public_key):
openssh_pub_bytes = b64decode(openssh_public_key)
pub_bytes = bytes_after(public_key_signature,
key_length,
openssh_pub_bytes)
nacl_pub_ed = VerifyKey(key=pub_bytes, encoder=RawEncoder)
return nacl_pub_ed.to_curve25519_public_key()
def seal(pubkey, secret):
seal_box = SealedBox(pubkey)
sealed = seal_box.encrypt(secret.encode('utf8'))
return b64encode(sealed).decode('utf8')
def unseal(privkey, sealed_box):
unseal_box = SealedBox(privkey)
decoded = b64decode(sealed_box)
return unseal_box.decrypt(decoded).decode('utf8')
def main():
def print_hex(byte_str):
print(" ".join(hex(b) for b in byte_str))
private_key = extract_curve_private_key(openssh_priv)
public_key = extract_curve_public_key(openssh_pub)
print_hex(private_key._private_key)
print_hex(private_key.public_key._public_key)
print_hex(public_key._public_key)
sealed = seal(public_key, "This is the secret!")
print(sealed)
print(unseal(private_key, sealed))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment