示例#1
0
        /// <summary>
        /// Encrypted the data.
        /// </summary>
        /// <param name="data">The data to encrypted.</param>
        /// <param name="passphrase">The passphrase key used to mask the data.</param>
        /// <returns>The encrypted data.</returns>
        public byte[] Encrypt(byte[] data, string passphrase)
        {
            // Create the key parameters.
            byte[] key = Encoding.Default.GetBytes(passphrase);
            Key.Crypto.Parameters.KeyParameter keyParameter = new KeyParameter(key);

            // Initialise the cryptography engine.
            Key.Crypto.Engines.TwofishEngine twofish = new TwofishEngine();
            twofish.Init(true, keyParameter);

            int dataLength   = data.Length;
            int blockSize    = twofish.GetBlockSize();
            int modBlockSize = dataLength % blockSize;
            int blockCount   = dataLength / blockSize;

            // If there is a remained then add en extra block count.
            if ((modBlockSize) > 0)
            {
                // Add one extra block.
                blockCount++;
            }

            // Encrypted data store.
            byte[] encryptedData = new byte[blockCount * blockSize];
            byte[] decryptedData = new byte[blockCount * blockSize];

            // Copy the decrypted data.
            for (int j = 0; j < dataLength; j++)
            {
                // Assign the data.
                decryptedData[j] = data[j];
            }

            // For each block size in the the data.
            for (int i = 0; i < blockCount; i++)
            {
                // Encrypt the block.
                twofish.ProcessBlock(decryptedData, (i * blockSize), encryptedData, (i * blockSize));
            }

            // Return the encrypted data.
            return(encryptedData);
        }