コード例 #1
0
        public static byte[] HandleUser(byte[] cipher, byte[] secretKey)
        {
            TwofishEngine  engine      = new TwofishEngine();
            CtrBlockCipher blockCipher = new CtrBlockCipher(engine);
            KeyParameter   secret      = new KeyParameter(secretKey);

            ParametersWithIV key = new ParametersWithIV(secret, cipher, 0, 16);

            int cipherLength = cipher.Length;
            int blockSize    = engine.GetBlockSize();
            int fraction     = cipherLength % blockSize;

            cipherLength += blockSize - fraction;

            byte[] input = new byte[cipherLength];
            Array.Copy(cipher, input, cipher.Length);

            blockCipher.Init(false, key);

            byte[] result = new byte[cipherLength - 16];
            int    pos    = 0;

            while (pos < cipher.Length - 16)
            {
                int length = blockCipher.ProcessBlock(input, pos + 16, result, pos);
                pos += length;
            }

            return(result);
        }
コード例 #2
0
ファイル: Twofish.cs プロジェクト: waffle-iron/nequeo
        /// <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);
        }