+/* Blue Sky: File Systems in the Cloud
+ *
+ * Copyright (C) 2009 The Regents of the University of California
+ * Written by Michael Vrable <mvrable@cs.ucsd.edu>
+ *
+ * TODO: Licensing
+ */
+
+#include <stdint.h>
+#include <errno.h>
+#include <pthread.h>
+#include <glib.h>
+#include <string.h>
+#include <gcrypt.h>
+
+#include "bluesky.h"
+
+/* Cryptographic operations. The rest of the BlueSky code merely calls into
+ * the functions in this file, so this is the only point where we interface
+ * with an external cryptographic library. */
+
+#define CRYPTO_BLOCK_SIZE 16 /* 128-bit AES */
+#define CRYPTO_KEY_SIZE 16
+
+GCRY_THREAD_OPTION_PTHREAD_IMPL;
+
+void bluesky_crypt_init()
+{
+ gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
+
+ if (gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
+ return;
+
+ g_print("libgcrypt not yet initialized, initializing...\n");
+
+ if (!gcry_check_version(GCRYPT_VERSION))
+ g_error("libgcrypt version mismatch\n");
+
+ gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
+ gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
+}
+
+/* Return cryptographically-strong random data. */
+void bluesky_crypt_random_bytes(guchar *buf, gint len)
+{
+ gcry_randomize(buf, len, GCRY_STRONG_RANDOM);
+}
+
+/* Encrypt a data block. */
+BlueSkyRCStr *bluesky_crypt_encrypt(BlueSkyRCStr *in, const uint8_t *key)
+{
+ gcry_error_t status;
+ gcry_cipher_hd_t handle;
+
+ status = gcry_cipher_open(&handle, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC,
+ GCRY_CIPHER_CBC_CTS);
+ if (status) {
+ g_error("gcrypt error setting up encryption: %s\n",
+ gcry_strerror(status));
+ }
+
+ uint8_t *out = g_malloc0(in->len + CRYPTO_BLOCK_SIZE);
+
+ gcry_cipher_setkey(handle, key, CRYPTO_KEY_SIZE);
+ if (status) {
+ g_error("gcrypt error setting key: %s\n",
+ gcry_strerror(status));
+ }
+
+ bluesky_crypt_random_bytes(out, CRYPTO_BLOCK_SIZE);
+ status = gcry_cipher_setiv(handle, out, CRYPTO_BLOCK_SIZE);
+ if (status) {
+ g_error("gcrypt error setting IV: %s\n",
+ gcry_strerror(status));
+ }
+
+ gcry_cipher_encrypt(handle, out + CRYPTO_BLOCK_SIZE, in->len,
+ in->data, in->len);
+ if (status) {
+ g_error("gcrypt error encrypting: %s\n",
+ gcry_strerror(status));
+ }
+
+ gcry_cipher_close(handle);
+
+ return bluesky_string_new(out, in->len + CRYPTO_BLOCK_SIZE);
+}