0

I'm using libsodium with the python bindings in pysodium 0.6.6

When using crypto_box and crypto_box_open, I always get a ValueError. Here is a simple example:

import pysodium
import random

serverPK, serverSK = pysodium.crypto_box_keypair()
clientPK, clientSK = pysodium.crypto_box_keypair()

testText = "test message"

nonce1 = str(random.random())
nonce2 = str(random.random())

cipherText = pysodium.crypto_secretbox(testText,nonce1,clientPK)
message = pysodium.crypto_secretbox_open(cipherText, nonce2, clientSK)
print message

And here is the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/.../pysodium-0.6.6/pysodium/__init__.py", line 181, in crypto_box_open
__check(sodium.crypto_box_open(msg, padded, ctypes.c_ulonglong(len(padded)), nonce, pk, sk))
  File "/Users/.../pysodium-0.6.6/pysodium/__init__.py", line 70, in __check
raise ValueError
ValueError
Alex Forsyth
  • 177
  • 1
  • 9

1 Answers1

2

crypto_box_keypair() creates a key pair, to be used with crypto_box().

crypto_secretbox() is not asymmetric encryption: a single key is used both to encrypt and to decrypt. If this is actually what you want, the key can be generated that way:

key = pysodium.randombytes(pysodium.crypto_secretbox_KEYBYTES)

For a given key, the nonce has to be unique for each message, and has to be pysodium.crypto_secretbox_NONCEBYTES bytes long. It can be a simple counter, or a random nonce:

nonce = pysodium.randombytes(pysodium.crypto_secretbox_NONCEBYTES)

Unlike the secret key, a nonce can be public. But it has to be the same for encrypting and for decrypting:

cipherText = pysodium.crypto_secretbox(testText, nonce, key)
message = pysodium.crypto_secretbox_open(cipherText, nonce, key)

The libsodium documentation provides examples on how to use box and secretbox, which can be easily translated to pysodium equivalents.

Frank Denis
  • 1,475
  • 9
  • 12