I have tested Public-key-cryptography by libsodium and came across a strange behavior. The encrypted message is decrypted without the private key.
Example from official site libsodium
#include "sodium.h"
#define MESSAGE "test"
#define MESSAGE_LEN 4
#define CIPHERTEXT_LEN (crypto_box_MACBYTES + MESSAGE_LEN)
static bool TestSodium()
{
unsigned char alice_publickey[crypto_box_PUBLICKEYBYTES];
unsigned char alice_secretkey[crypto_box_SECRETKEYBYTES];
crypto_box_keypair(alice_publickey, alice_secretkey);
unsigned char bob_publickey[crypto_box_PUBLICKEYBYTES];
unsigned char bob_secretkey[crypto_box_SECRETKEYBYTES];
crypto_box_keypair(bob_publickey, bob_secretkey);
unsigned char nonce[crypto_box_NONCEBYTES];
unsigned char ciphertext[CIPHERTEXT_LEN];
randombytes_buf(nonce, sizeof nonce);
// message alice -> bob
if (crypto_box_easy(ciphertext, (const unsigned char*)MESSAGE, MESSAGE_LEN, nonce, bob_publickey, alice_secretkey) != 0)
{
return false;
}
unsigned char decrypted[MESSAGE_LEN + 1];
decrypted[MESSAGE_LEN] = 0;
// Original!
//if (crypto_box_open_easy(decrypted, ciphertext, CIPHERTEXT_LEN, nonce, alice_publickey, bob_secretkey) != 0)
// Whis works without Bobs secret key!
if (crypto_box_open_easy(decrypted, ciphertext, CIPHERTEXT_LEN, nonce, bob_publickey, alice_secretkey) != 0)
{
return false;
}
if(strcmp((const char*)decrypted, MESSAGE) != 0) return false;
return true;
}
Using public-key authenticated encryption, Alice can encrypt a confidential message specifically for Bob, using Bob's public key.
Using Alice's public key, Bob can verify that the encrypted message was actually created by Alice and was not tampered with, before eventually decrypting it.
Bob only needs Alice's public key, the nonce and the ciphertext.
And in order to send messages to Bob, Alice only needs Bobs's public key.
In original examle Bob decrypts message from Alice by own secret key and verifies it by Alice's public key. I made a mistake in code and message was properly decrypted without Bob's private key!
How it is possible? Where is my mistake? Thanks