Browse Source

[Minor] Add ability to encrypt data using pubkey only

tags/1.7.6
Vsevolod Stakhov 6 years ago
parent
commit
c1e80bdef0
2 changed files with 66 additions and 1 deletions
  1. 50
    0
      src/libcryptobox/keypair.c
  2. 16
    1
      src/libcryptobox/keypair.h

+ 50
- 0
src/libcryptobox/keypair.c View File

@@ -978,6 +978,7 @@ rspamd_keypair_decrypt (struct rspamd_cryptobox_keypair *kp,

return TRUE;
}

gboolean
rspamd_keypair_encrypt (struct rspamd_cryptobox_keypair *kp,
const guchar *in, gsize inlen,
@@ -1025,5 +1026,54 @@ rspamd_keypair_encrypt (struct rspamd_cryptobox_keypair *kp,
*outlen = olen;
}

return TRUE;
}

gboolean
rspamd_pubkey_encrypt (struct rspamd_cryptobox_pubkey *pk,
const guchar *in, gsize inlen,
guchar **out, gsize *outlen,
GError **err)
{
guchar *nonce, *mac, *data, *pubkey;
struct rspamd_cryptobox_keypair *local;
gsize olen;

g_assert (pk != NULL);
g_assert (in != NULL);

if (pk->type != RSPAMD_KEYPAIR_KEX) {
g_set_error (err, rspamd_keypair_quark (), EINVAL,
"invalid pubkey type");

return FALSE;
}

local = rspamd_keypair_new (pk->type, pk->alg);

olen = inlen + sizeof (encrypted_magic) +
rspamd_cryptobox_pk_bytes (pk->alg) +
rspamd_cryptobox_mac_bytes (pk->alg) +
rspamd_cryptobox_nonce_bytes (pk->alg);
*out = g_malloc (olen);
memcpy (*out, encrypted_magic, sizeof (encrypted_magic));
pubkey = *out + sizeof (encrypted_magic);
mac = pubkey + rspamd_cryptobox_pk_bytes (pk->alg);
nonce = mac + rspamd_cryptobox_mac_bytes (pk->alg);
data = nonce + rspamd_cryptobox_nonce_bytes (pk->alg);

ottery_rand_bytes (nonce, rspamd_cryptobox_nonce_bytes (pk->alg));
memcpy (data, in, inlen);
memcpy (pubkey, rspamd_pubkey_get_pk (pk, NULL),
rspamd_cryptobox_pk_bytes (pk->alg));
rspamd_cryptobox_encrypt_inplace (data, inlen, nonce, pubkey,
rspamd_keypair_component (local, RSPAMD_KEYPAIR_COMPONENT_SK, NULL),
mac, pk->alg);
rspamd_keypair_unref (local);

if (outlen) {
*outlen = olen;
}

return TRUE;
}

+ 16
- 1
src/libcryptobox/keypair.h View File

@@ -303,6 +303,21 @@ gboolean rspamd_keypair_encrypt (struct rspamd_cryptobox_keypair *kp,
const guchar *in, gsize inlen,
guchar **out, gsize *outlen,
GError **err);

/**
* Encrypts data usign specific pubkey (must have KEX type).
* This method actually generates ephemeral local keypair, use public key from
* the remote keypair and encrypts data
* @param kp keypair
* @param in raw input
* @param inlen input length
* @param out output (allocated internally using g_malloc)
* @param outlen output size
* @param err pointer to error
* @return TRUE if encryption has been completed, out must be freed in this case
*/
gboolean rspamd_pubkey_encrypt (struct rspamd_cryptobox_pubkey *pk,
const guchar *in, gsize inlen,
guchar **out, gsize *outlen,
GError **err);

#endif /* SRC_LIBCRYPTOBOX_KEYPAIR_H_ */

Loading…
Cancel
Save