1

I have some code that I wrote below with Python 2.7 and uses pynacl, running on a mac os x. It currently works as written below and it will encrypt the password and then decrypt it later. I want to know if there is away where the last few lines that decrypt can be on a separate python file ? The separate python file is a cronjob that run daily and will need the password to run, this is the reason why I need the decryption part to be on file #2. Please let me know of any suggestions.

I have tried importing the File #1 to File #2 and also even saving the required variables in File #1 to files but the "SealedBox" cannot be saved into a file with error "TypeError: argument 1 must be convertible to a buffer, not SealedBox"

#!/usr/bin/env python2


import nacl.utils
from nacl.public import PrivateKey, SealedBox
import getpass

# Generate Bob's private key, as we've done in the Box example
skbob = PrivateKey.generate()
pkbob = skbob.public_key

# Alice wishes to send a encrypted message to Bob,
# but prefers the message to be untraceable
sealed_box = SealedBox(pkbob)

# This is Alice's message
message = getpass.getpass("LDAP Password is:")

# Encrypt the message, it will carry the ephemeral key public part
# to let Bob decrypt it
encrypted = sealed_box.encrypt(message)

# Store the data with binary mode:
# with open('file.bin', 'wb') as f:
#   f.write(encrypted)

unseal_box = SealedBox(skbob)

# with open('file2.bin', 'wb') as f:
#   f.write(unseal_box)

# decrypt the received message, this is where File #2 would start
plaintext = unseal_box.decrypt(encrypted)
print(plaintext.decode('utf-8'))
user5578188
  • 63
  • 1
  • 8
  • Possible duplicate of [How do I do encryption/decryption without generating keypairs again?](https://stackoverflow.com/q/44917150/1820553) – kelalaka May 10 '19 at 23:14

1 Answers1

0

you can use pickle:

encrypt script

from nacl.public import PrivateKey, SealedBox
import getpass
import pickle

# Generate Bob's private key, as we've done in the Box example
skbob = PrivateKey.generate()
pkbob = skbob.public_key

# Alice wishes to send a encrypted message to Bob,
# but prefers the message to be untraceable
sealed_box = SealedBox(pkbob)

# This is Alice's message
message = getpass.getpass("LDAP Password is:")

# Encrypt the message, it will carry the ephemeral key public part
# to let Bob decrypt it
encrypted = sealed_box.encrypt(message.encode())

# Store the data with binary mode:
with open('file.bin', 'wb') as f:
    pickle.dump(encrypted, f)
with open('file2.bin', 'wb') as f:
    pickle.dump(skbob, f)

decrypt script

from nacl.public import SealedBox
import pickle

with open('file.bin', 'rb') as f:
    encrypted = pickle.load(f)
with open('file2.bin', 'rb') as f:
    skbob = pickle.load(f)

unseal_box = SealedBox(skbob)
# decrypt the received message, this is where File #2 would start
plaintext = unseal_box.decrypt(encrypted)
print(plaintext.decode('utf-8'))