/// <summary>Creates a Secret Box</summary> /// <param name="message">The message.</param> /// <param name="nonce">The 24 byte nonce.</param> /// <param name="key">The 32 byte key.</param> /// <returns>The encrypted message.</returns> /// <exception cref="KeyOutOfRangeException"></exception> /// <exception cref="NonceOutOfRangeException"></exception> /// <exception cref="CryptographicException"></exception> public static byte[] Create(byte[] message, byte[] nonce, byte[] key) { //validate the length of the key if (key == null || key.Length != KEY_BYTES) { throw new KeyOutOfRangeException("key", (key == null) ? 0 : key.Length, string.Format("key must be {0} bytes in length.", KEY_BYTES)); } //validate the length of the nonce if (nonce == null || nonce.Length != NONCE_BYTES) { throw new NonceOutOfRangeException("nonce", (nonce == null) ? 0 : nonce.Length, string.Format("nonce must be {0} bytes in length.", NONCE_BYTES)); } //pad the message, to start with ZERO_BYTES null bytes var paddedMessage = new byte[message.Length + ZERO_BYTES]; Array.Copy(message, 0, paddedMessage, ZERO_BYTES, message.Length); var buffer = new byte[paddedMessage.Length]; var ret = SodiumLibrary.crypto_secretbox(buffer, paddedMessage, paddedMessage.Length, nonce, key); if (ret != 0) { throw new CryptographicException("Failed to create SecretBox"); } return(buffer); }