Пример #1
0
        /// <summary>Opens a detached Box</summary>
        /// <param name="cipherText">The cipherText.</param>
        /// <param name="mac">The 16 byte mac.</param>
        /// <param name="nonce">The 24 byte nonce.</param>
        /// <param name="secretKey">The recipient's secret key.</param>
        /// <param name="publicKey">The sender's public key.</param>
        /// <returns>The decrypted message.</returns>
        /// <exception cref="KeyOutOfRangeException"></exception>
        /// <exception cref="MacOutOfRangeException"></exception>
        /// <exception cref="NonceOutOfRangeException"></exception>
        /// <exception cref="CryptographicException"></exception>
        public static byte[] OpenDetached(byte[] cipherText, byte[] mac, byte[] nonce, byte[] secretKey,
                                          byte[] publicKey)
        {
            //validate the length of the secret key
            if (secretKey == null || secretKey.Length != SecretKeyBytes)
            {
                throw new KeyOutOfRangeException("secretKey", secretKey == null ? 0 : secretKey.Length,
                                                 string.Format("key must be {0} bytes in length.", SecretKeyBytes));
            }

            //validate the length of the public key
            if (publicKey == null || publicKey.Length != PublicKeyBytes)
            {
                throw new KeyOutOfRangeException("publicKey", publicKey == null ? 0 : secretKey.Length,
                                                 string.Format("key must be {0} bytes in length.", PublicKeyBytes));
            }

            //validate the length of the mac
            if (mac == null || mac.Length != MAC_BYTES)
            {
                throw new MacOutOfRangeException("mac", mac == null ? 0 : mac.Length,
                                                 string.Format("mac must be {0} bytes in length.", MAC_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));
            }

            var buffer = new byte[cipherText.Length];
            var ret    = SodiumLibrary.crypto_box_open_detached(buffer, cipherText, mac, cipherText.Length, nonce,
                                                                secretKey, publicKey);

            if (ret != 0)
            {
                throw new CryptographicException("Failed to open public detached Box");
            }

            return(buffer);
        }