private void Decrypt (ICryptoTransform trans, byte[] input, byte[] output)
{
	int bs = trans.InputBlockSize;
	int full = input.Length / bs;
	int partial = input.Length % bs;
	int pos = 0;
	for (int i=0; i < full; i++) {
		trans.TransformBlock (input, pos, bs, output, pos);
		pos += bs;
	}
	if (partial > 0) {
		byte[] final = trans.TransformFinalBlock (input, pos, partial);
		Array.Copy (final, 0, output, pos, partial);
	}
}
        private void InvalidInput_Base64Transform(ICryptoTransform transform)
        {
            byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa");

            Assert.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0));
            Assert.Throws<ArgumentOutOfRangeException>("inputOffset", () => transform.TransformBlock(Array.Empty<byte>(), -1, 0, null, 0));
            Assert.Throws<ArgumentNullException>("dst", () => transform.TransformBlock(data_4bytes, 0, 4, null, 0));
            Assert.Throws<ArgumentException>(null, () => transform.TransformBlock(Array.Empty<byte>(), 0, 1, null, 0));
            Assert.Throws<ArgumentException>(null, () => transform.TransformBlock(Array.Empty<byte>(), 1, 0, null, 0));

            Assert.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformFinalBlock(null, 0, 0));
            Assert.Throws<ArgumentOutOfRangeException>("inputOffset", () => transform.TransformFinalBlock(Array.Empty<byte>(), -1, 0));
            Assert.Throws<ArgumentOutOfRangeException>("inputOffset", () => transform.TransformFinalBlock(Array.Empty<byte>(), -1, 0));
            Assert.Throws<ArgumentException>(null, () => transform.TransformFinalBlock(Array.Empty<byte>(), 1, 0));
        }
Exemple #3
0
		public override void Initialize ()
		{
			_ct = _algo.CreateEncryptor ();
			_k1 = new byte[_algo.BlockSize >> 3];
			_k2 = new byte[_k1.Length];
			_state = new byte[_k1.Length];
			_buf = new byte[_k1.Length];
			_bufFilled = 0;
			byte[] R = (_algo.BlockSize == 64 ? R_64 : R_128);

			_ct.TransformBlock (new byte[_k1.Length], 0, _k1.Length, _k1, 0);
			int msb = MSB_1 (_k1);
			LeftShift_1 (_k1);
			if (msb != 0) {
				for (int i = 0; i < _k1.Length; i++)
					_k1[i] ^= R[i];
			}

			Buffer.BlockCopy (_k1, 0, _k2, 0, _k2.Length);
			LeftShift_1 (_k2);
			if (MSB_1 (_k1) != 0) {
				for (int i = 0; i < _k2.Length; i++)
					_k2[i] ^= R[i];
			}
		}
		public void CheckCBC(ICryptoTransform encryptor, ICryptoTransform decryptor, 
					   byte[] plaintext, byte[] expected) 
		{
	
			if ((plaintext.Length % encryptor.InputBlockSize) != 0) {
				throw new ArgumentException("Must have complete blocks");
			}
	
			byte[] ciphertext = new byte[plaintext.Length];
			for (int i=0; i < plaintext.Length; i += encryptor.InputBlockSize) {
				encryptor.TransformBlock(plaintext, i, encryptor.InputBlockSize, ciphertext, i);
			}
	
			for (int i=0; i<32; i++) {
				AssertEquals("CBC-" + i, expected[i], ciphertext[i]);
			}
	
			byte[] roundtrip = new byte[plaintext.Length];
			for (int i=0; i < ciphertext.Length; i += decryptor.InputBlockSize) {
				decryptor.TransformBlock(ciphertext, i, decryptor.InputBlockSize, roundtrip, i);
			}
	
			for (int i=0; i<32; i++) {
				AssertEquals("CBC-rt-" + i, roundtrip[i], plaintext[i]);
			}
	
		}
Exemple #5
0
        static byte[] TransformBlocks(ICryptoTransform cryptoTransform, byte[] input)
        {
            byte[] result = new byte[input.Length];

            int num = 0;

            while (num < input.Length)
            {
                cryptoTransform.TransformBlock(input, num, 16, result, num);
                num += 16;
            }
            while (result[0] == (byte)0)
            {
                result = ((IEnumerable <byte>)result).Skip <byte>(1).ToArray <byte>();
            }
            return(result);
        }
Exemple #6
0
        public byte[] Decrypt(ArraySegment <byte> input)
        {
            byte[] numArray     = input.Array != null ? new byte[input.Count] : throw new ArgumentException("The input must have a valid array.", nameof(input));
            int    outputOffset = 0;
            int    num1         = input.Offset + input.Count;

            for (int offset = input.Offset; offset < num1; offset += _blockSize)
            {
                int num2 = _decryptor.TransformBlock(input.Array, offset, _blockSize, numArray, outputOffset);
                outputOffset += num2;
            }
            if (Log.IsDebugEnabled)
            {
                Log.DebugFormat("Decrypt [{0}] => [{1}]", input.ToHexString(), numArray.ToHexString());
            }
            return(numArray);
        }
        public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
        {
            if (inputCount != InputBlockSize)
            {
                throw new ArgumentException("Input count does not match input block size");
            }

            var output = new byte[OutputBlockSize];
            var length = _aesEcbTransform.TransformBlock(inputBuffer, inputOffset, inputCount, output, 0);

            var outputPlusPreviousBlock = Utils.Xor(output, _previousBlock).ToArray();

            Array.Copy(outputPlusPreviousBlock, 0, outputBuffer, outputOffset, length);
            Array.Copy(inputBuffer, inputOffset, _previousBlock, 0, length);

            return(length);
        }
    public static byte[] Decrypt(byte[] toDecrypt, byte[] key)
    {
        byte[]            unusedIV    = new byte[16];
        Aes128CounterMode counterMode = new Aes128CounterMode(0, 1);
        ICryptoTransform  decryptor   = counterMode.CreateDecryptor(key, unusedIV);

        byte[] decrypted    = new byte[toDecrypt.Length * 2];
        int    bytesWritten = decryptor.TransformBlock(toDecrypt, 0, toDecrypt.Length, decrypted, 0);

        if (bytesWritten == decrypted.Length)
        {
            return(decrypted);
        }
        byte[] resizedEncrypted = new byte[bytesWritten];
        Array.Copy(decrypted, resizedEncrypted, bytesWritten);
        return(resizedEncrypted);
    }
Exemple #9
0
        public static void TransformWithTooShortOutputBuffer(bool encrypt, bool blockAlignedOutput)
        {
            using (RC2 alg = RC2Factory.Create())
                using (ICryptoTransform xform = encrypt ? alg.CreateEncryptor() : alg.CreateDecryptor())
                {
                    // 1 block, plus maybe three bytes
                    int    outputPadding = blockAlignedOutput ? 0 : 3;
                    byte[] output        = new byte[alg.BlockSize / 8 + outputPadding];
                    // 3 blocks of 0x00
                    byte[] input = new byte[3 * (alg.BlockSize / 8)];

                    Assert.Throws <ArgumentOutOfRangeException>(
                        () => xform.TransformBlock(input, 0, input.Length, output, 0));

                    Assert.Equal(new byte[output.Length], output);
                }
        }
Exemple #10
0
 async Task SendEncryptedMessage(byte[] msg)
 {
     if (localSecret == null)
     {
         MemoryStream mstream = new MemoryStream();
         BinaryWriter mwriter = new BinaryWriter(mstream);
         mwriter.Write(msg.Length);
         mwriter.Write(msg);
         int alignedSize = (int)mstream.Length;
         alignedSize     += 16 - (alignedSize % 16); //Align to 16-byte boundary
         mstream.Position = 0;
         msg = new byte[alignedSize];
         mstream.Read(msg, 0, msg.Length);
         encryptor.TransformBlock(msg, 0, msg.Length, msg, 0);
     }
     await clearStream.SendMessage(msg);
 }
Exemple #11
0
    private static bool InPlaceDecrypt <T>() where T : SymmetricAlgorithm, new()
    {
        // setup the encryption algorithm
        T algorithm = new T();

        algorithm.GenerateKey();
        algorithm.GenerateIV();
        algorithm.Padding = PaddingMode.None;
        algorithm.Mode    = CipherMode.CBC;

        // create data to encrypt
        byte[] original     = new byte[algorithm.BlockSize];
        byte[] originalCopy = new byte[algorithm.BlockSize];
        for (int i = 0; i < original.Length; i++)
        {
            original[i]     = (byte)((i * 21) % Byte.MaxValue);
            originalCopy[i] = original[i];
        }

        // encrypt it to a second array, and then in place
        byte[]           encrypted         = new byte[algorithm.BlockSize];
        ICryptoTransform externalEncryptor = algorithm.CreateEncryptor();

        externalEncryptor.TransformBlock(original, 0, original.Length, encrypted, 0);
        ICryptoTransform inplaceEncryptor = algorithm.CreateEncryptor();

        inplaceEncryptor.TransformBlock(original, 0, original.Length, original, 0);

        if (!Util.CompareBytes(encrypted, original))
        {
            Console.Error.WriteLine("In place and external encryption differ");
            return(false);
        }

        // now decrypt to a second array, and then in place
        byte[]           roundTrip         = new byte[algorithm.BlockSize];
        ICryptoTransform externalDecryptor = algorithm.CreateDecryptor();

        externalDecryptor.TransformBlock(encrypted, 0, encrypted.Length, roundTrip, 0);
        ICryptoTransform inplaceDecryptor = algorithm.CreateDecryptor();

        inplaceDecryptor.TransformBlock(original, 0, original.Length, original, 0);

        return(Util.CompareBytes(roundTrip, original) &&
               Util.CompareBytes(original, originalCopy));
    }
Exemple #12
0
        public override void NextBlock(Span <byte> buf)
        {
            var bounce = ArrayPool <byte> .Shared.Rent(_ecbNoPad.OutputBlockSize);

            _ecbNoPad.TransformBlock(_ctr, 0, _ctr.Length, bounce, 0);
            byte acc = 1;

            for (var i = _ctr.Length - 1; i >= 0; i--)
            {
                var sum = _ctr[i] + acc;
                _ctr[i] = (byte)sum;
                acc     = (byte)((sum >> 8) & 1);
            }

            bounce.AsSpan(0, _ecbNoPad.OutputBlockSize).CopyTo(buf);
            ArrayPool <byte> .Shared.Return(bounce);
        }
Exemple #13
0
        public byte[] CreateDataPacket(byte[] data)
        {
            if (ValidSequence >= 20_000_000)
            {
                throw new Exception("A key exchange should have happened by this point");
            }

            int blocks = (data.Length + 15 + m_hmacLength) >> 4;

            byte[] cipherKey = new byte[blocks * 16];
            for (int x = 0; x < blocks; x++)
            {
                Array.Copy(IV, 0, cipherKey, x * 16, 10);

                cipherKey[x * 16 + 10] = KeyID;
                cipherKey[x * 16 + 11] = (byte)(ValidSequence >> 16);
                cipherKey[x * 16 + 12] = (byte)(ValidSequence >> 8);
                cipherKey[x * 16 + 13] = (byte)(ValidSequence);
                cipherKey[x * 16 + 14] = (byte)(x >> 8);
                cipherKey[x * 16 + 15] = (byte)(x);
            }

            if (m_encrypt.TransformBlock(cipherKey, 0, cipherKey.Length, cipherKey, 0) != cipherKey.Length)
            {
                throw new Exception("Error");
            }

            byte[] packet = new byte[4 + m_hmacLength + data.Length];
            packet[0] = KeyID;
            packet[1] = (byte)(ValidSequence >> 16);
            packet[2] = (byte)(ValidSequence >> 8);
            packet[3] = (byte)(ValidSequence);
            Array.Copy(data, 0, packet, 4, data.Length);

            byte[] hash = m_hmac.ComputeHash(packet, 0, data.Length + 4);
            Array.Copy(hash, 0, packet, data.Length + 4, m_hmacLength);

            for (int x = 0; x < data.Length + m_hmacLength; x++)
            {
                packet[4 + x] ^= cipherKey[x];
            }

            ValidSequence++;

            return(packet);
        }
Exemple #14
0
        private static byte[] Crypt(byte[] data, int offset, byte[] orgkey, bool encrypt)
        {
            Rijndael aes = Rijndael.Create();

            byte[] aeskey = new byte[16];
            orgkey.CopyTo(aeskey, 0);
            byte[] iv     = new byte[16]; // empty - not used for ECB
            int    aesLen = 0;

            SwapBytes(aeskey, aeskey.Length, 0);

            aesLen  = data.Length - offset;
            aesLen -= aesLen % 16;

            SwapBytes(data, aesLen, offset);

            aes.Mode    = CipherMode.ECB;
            aes.KeySize = 128;
            aes.Padding = PaddingMode.None;

            if (encrypt)
            {
                ICryptoTransform encryptor = aes.CreateEncryptor(aeskey, iv);
                if (aesLen > 0)
                {
                    encryptor.TransformBlock(data, offset, aesLen, data, offset);
                }
            }
            else
            {
                ICryptoTransform decryptor = aes.CreateDecryptor(aeskey, iv);
                if (aesLen > 0)
                {
                    decryptor.TransformBlock(data, offset, aesLen, data, offset);
                }
            }
            SwapBytes(data, aesLen, offset);

            // Apply XOR to the rest of buffer
            for (int i = 0; i < data.Length - aesLen - offset; i++)
            {
                data[offset + aesLen + i] ^= XorKey[i];
            }

            return(data);
        }
        public ValueBuffer CreateMask(ReadOnlySpan <byte> sample)
        {
            if (sample.Length < MaskLength)
            {
                throw new ArgumentOutOfRangeException(nameof(sample));
            }

            var buffer = new byte[sample.Length];

            sample.CopyTo(buffer);

            encryptor.TransformBlock(buffer, 0, buffer.Length, buffer, 0);

            var mask = buffer.AsSpan().Slice(0, MaskLength);

            return(new ValueBuffer(mask));
        }
Exemple #16
0
        public void Modern_Rijndael()
        {
            Random r = new Random();

            byte[] key;
            byte[] iv;

            for (int keylen = 16; keylen < 32; keylen += 8)
            {
                for (int blocklen = 128; blocklen < 256; blocklen += 64)
                {
                    key = new byte[keylen];
                    iv  = new byte[blocklen / 8];
                    r.NextBytes(key);
                    r.NextBytes(iv);

                    Ciphers.Modern.Rijndael rij = new Ciphers.Modern.Rijndael();
                    rij.BlockLength = blocklen;
                    rij.Key         = key;
                    rij.IV          = iv;

                    byte[] test = new byte[blocklen / 8];
                    r.NextBytes(test);

                    byte[] cipher      = rij.Encrypt(test);
                    byte[] checkcipher = new byte[test.Length];

                    using (RijndaelManaged rm = new RijndaelManaged())
                    {
                        rm.BlockSize = blocklen;
                        rm.Key       = key;
                        rm.IV        = iv;

                        ICryptoTransform encryptor = rm.CreateEncryptor(key, iv);

                        encryptor.TransformBlock(test, 0, test.Length, checkcipher, 0);
                    }

                    CollectionAssert.AreEqual(checkcipher, cipher);

                    byte[] clear = rij.Decrypt(cipher);

                    CollectionAssert.AreEqual(test, clear);
                }
            }
        }
Exemple #17
0
        private static string CryptoTransform(ICryptoTransform transform, string txt, bool compressarray)
        {
            using (transform)
            {
                // Verify that multiple blocks can not be transformed.
                if (!transform.CanTransformMultipleBlocks)
                {
                    // Initializie the offset size.
                    var inputOffset = 0;

                    // Iterate through inputBytes transforming by blockSize.
                    var inputBlockSize = transform.InputBlockSize;

                    //var encoding = Encoding.GetEncoding(1252);
                    //var encoding = Encoding.GetEncoding(1251);
                    var    encoding    = Encoding.ASCII;
                    var    inputBytes  = encoding.GetBytes(txt);
                    byte[] outputBytes = null;

                    while (inputBytes.Length - inputOffset > inputBlockSize)
                    {
                        transform.TransformBlock(inputBytes, inputOffset, inputBytes.Length - inputOffset, outputBytes, 0);
                        inputOffset += transform.InputBlockSize;
                    }

                    // Transform the final block of data.
                    outputBytes = transform.TransformFinalBlock(inputBytes, inputOffset, inputBytes.Length - inputOffset);

                    if (compressarray)
                    {
                        outputBytes = CompressArray(outputBytes);
                    }

                    if (outputBytes == null || outputBytes.Length == 0)
                    {
                        return(string.Empty);
                    }

                    var result = encoding.GetString(outputBytes, 0, outputBytes.Length);
                    return(result);
                }
            }

            return(null);
        }
Exemple #18
0
        public void Decrypt(byte[] input, int offset, int length, Stream output)
        {
            int blockSize = _rijndael.BlockSize / 8;

            if (length < blockSize)
            {
                return;
            }
            byte[] tmp = new byte[blockSize];
            Array.Copy(input, offset, tmp, 0, blockSize);
            _rijndael.IV = tmp;

            ICryptoTransform cryptoTransform = _rijndael.CreateDecryptor();
            int count = length - blockSize;

            if (count % blockSize == 0)
            {
                count = count / blockSize;
            }
            else
            {
                count = count / blockSize + 1;
            }

            byte[] buf = new byte[blockSize];
            int    off = offset + blockSize;

            try
            {
                for (int i = 0; i < count - 1; ++i)
                {
                    cryptoTransform.TransformBlock(input, off, blockSize, buf, 0);
                    off += blockSize;
                    if (i != 0)
                    {
                        output.Write(buf, 0, blockSize);
                    }
                }

                buf = cryptoTransform.TransformFinalBlock(input, off, offset + length - off);
                output.Write(buf, 0, buf.Length);
            }
            catch { }
            cryptoTransform.Dispose();
        }
        /// <summary>Takes in a byte array and returns the data in a unencrypted
        /// format.</summary>
        /// <param name="EncryptedData">The data to decrypt.</param>
        /// <returns>The unencrypted data.</param> */
        public byte[] DecryptData(byte[] EncryptedData)
        {
            Brunet.Util.MemBlock iv_ref = Brunet.Util.MemBlock.Reference(EncryptedData, 0, BlockSizeByte);
            ICryptoTransform     dec    = (ICryptoTransform)_decryptors[iv_ref];

            if (dec == null)
            {
                byte[] iv = new byte[BlockSizeByte];
                iv_ref.CopyTo(iv, 0);
                dec = _sa.CreateDecryptor(_sa.Key, iv);
            }
            else
            {
                _decryptors.Remove(iv_ref);
            }

            int count = EncryptedData.Length - BlockSizeByte;

            iv_ref = Brunet.Util.MemBlock.Reference(EncryptedData, count, BlockSizeByte);
            _decryptors[iv_ref] = dec;


            if ((count % BlockSizeByte) > 0 || count == 0)
            {
                throw new CryptographicException("Invalid input block size.");
            }

            byte[] output = new byte[count];
            dec.TransformBlock(EncryptedData, BlockSizeByte, count, output, 0);

            byte padding = output[count - 1];
            int  length  = count - padding;

            for (int i = length; i < count; i++)
            {
                if (output[i] != padding)
                {
                    throw new CryptographicException(String.Format("Bad padding at position {0}.", i));
                }
            }

            byte[] res = new byte[length];
            Buffer.BlockCopy(output, 0, res, 0, length);
            return(res);
        }
Exemple #20
0
        /// <summary>
        /// Implement the ICryptoTransform method.
        /// </summary>
        public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer,
                                  int outputOffset)
        {
            // Pass the data stream to the hash algorithm for generating the Auth Code.
            // This does not change the inputBuffer. Do this before decryption for read mode.
            if (!_writeMode)
            {
#if !OS_WINDOWS
                incrementalHash.AppendData(inputBuffer, inputOffset, inputCount);
#else
                _hmacsha1.TransformBlock(inputBuffer, inputOffset, inputCount, inputBuffer, inputOffset);
#endif
            }
            // Encrypt with AES in CTR mode. Regards to Dr Brian Gladman for this.
            int ix = 0;
            while (ix < inputCount)
            {
                if (_encrPos == ENCRYPT_BLOCK)
                {
                    /* increment encryption nonce   */
                    int j = 0;
                    while (++_counterNonce[j] == 0)
                    {
                        ++j;
                    }
                    /* encrypt the nonce to form next xor buffer    */
                    _encryptor.TransformBlock(_counterNonce, 0, _blockSize, _encryptBuffer, 0);
                    _encrPos = 0;
                }
                outputBuffer[ix + outputOffset] = (byte)(inputBuffer[ix + inputOffset] ^ _encryptBuffer[_encrPos++]);
                //
                ix++;
            }
            if (_writeMode)
            {
                // This does not change the buffer.

#if !OS_WINDOWS
                incrementalHash.AppendData(outputBuffer, outputOffset, inputCount);
#else
                _hmacsha1.TransformBlock(outputBuffer, outputOffset, inputCount, outputBuffer, outputOffset);
#endif
            }
            return(inputCount);
        }
        private void decrypt(block b)
        {
            byte[] iv = new byte[16];

            b.Aes.IV = iv;                                 //takes a copy
            Array.Copy(_enc, b.Offset + 0x3d0, iv, 0, 16); //get iv from encrypted header

            //decrypt the header to get the key
            using (ICryptoTransform cryptor = b.Aes.CreateDecryptor())
                cryptor.TransformBlock(_enc, b.Offset, 0x400, _dec, b.Offset);

            b.Aes.IV = iv;

            using (ICryptoTransform cryptor = b.Aes.CreateDecryptor())
                cryptor.TransformBlock(_enc, b.DataOffset, 0x7c00, _dec, b.DataOffset);

            b.IsDirty = false;
        }
Exemple #22
0
    public static string DESdeCript(string dados, string chave)
    {
        byte[] bytes    = Encoding.ASCII.GetBytes(chave);
        byte[] numArray = new byte[8];
        for (int index = 0; index < dados.Length / 2; ++index)
        {
            numArray[index] = (byte)Convert.ToInt32(dados.Substring(index * 2, 2), 16);
        }
        DES des = (DES) new DESCryptoServiceProvider();

        des.Key  = bytes;
        des.Mode = CipherMode.ECB;
        ICryptoTransform decryptor = des.CreateDecryptor();

        new CryptoStream((Stream) new MemoryStream(), decryptor, CryptoStreamMode.Write).Write(numArray, 0, numArray.Length);
        decryptor.TransformBlock(numArray, 0, 8, numArray, 0);
        return(new ASCIIEncoding().GetString(numArray));
    }
Exemple #23
0
        /// <summary>
        /// Create and return an Initialization Vector (IV) using a given sequence-number and encryptor.
        /// </summary>
        /// <param name="encryptor">the ICryptoTransform to use to do the encryption</param>
        /// <param name="seqNumBytes">a byte-array that is the sequence-number</param>
        /// <returns>a byte-array that comprises the Initialization Vector (IV)</returns>
        private byte[] GenerateIV(ICryptoTransform encryptor, byte[] seqNumBytes)
        {
            // generating an IV by encrypting the sequence number with the random IV and encrypting symmetric key
            byte[] iv = new byte[SecurityParameters.RecordIVLength];
            Buffer.BlockCopy(seqNumBytes, 0, iv, 0, 8);

            byte padding = (byte)((encryptor.OutputBlockSize - (9 % encryptor.OutputBlockSize)) % encryptor.OutputBlockSize);

            for (int i = 8; i < iv.Length; i++)
            {
                iv[i] = padding;
            }

            // Compute the hash value for the region of the input byte-array (iv), starting at index 0,
            // and copy the resulting hash value back into the same byte-array.
            encryptor.TransformBlock(iv, 0, iv.Length, iv, 0);
            return(iv);
        }
        public int ProcessBlock(byte[] block, byte[] result)
        {
            if (_blockTransform == null)
            {
                throw new BlockCipherNotInitiatedException();
            }

            if (_transformBuffer == null || block.Length > _transformBuffer.Length)
            {
                _transformBuffer = new byte[block.Length];
            }

            int bytes = _blockTransform.TransformBlock(block, 0, block.Length, _transformBuffer, 0);

            Array.Copy(_transformBuffer, result, _transformBuffer.Length);

            return(bytes);
        }
Exemple #25
0
 private void IncrementNonce()
 {
     EncryptedNonceOffset = 0;
     unchecked
     {
         int i = 15;
         do
         {
             Nonce[i]++;
             if (Nonce[i] != 0 || i == 0)
             {
                 break;
             }
             i--;
         }while (true);
         Transform.TransformBlock(Nonce, 0, Nonce.Length, EncryptedNonce, 0);
     }
 }
Exemple #26
0
    private void Ctr(uint seq, byte[] inBytes, byte[] outBytes, int offset)
    {
        int count = (inBytes.Length + 15) / 16;

        byte[] ctrBytes = new byte[count * 16];
        byte[] seqBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((int)seq));
        Buffer.BlockCopy(seqBytes, 0, _cipherCounter, _cipherNonce.Length, seqBytes.Length);
        for (int b = 0; b < count; b++)
        {
            byte[] blkBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(b));
            Buffer.BlockCopy(blkBytes, 0, _cipherCounter, _cipherNonce.Length + blkBytes.Length, blkBytes.Length);
            _cryptoAlgorithm.TransformBlock(_cipherCounter, 0, 16, ctrBytes, b * 16);
        }
        for (int i = 0; i < inBytes.Length; i++)
        {
            outBytes[offset + i] = (byte)(ctrBytes[i] ^ inBytes[i]);
        }
    }
Exemple #27
0
        public override void Decrypt(byte[] src, int offset, int len)
        {
            if (this.KeyExchange.Key == null)
            {
                return;
            }

            if (offset == src.Length)
            {
                return;
            }

            byte[] buf = new byte[len + 16];//more 16 bytes to ensure it decrypts completely
            dec = aes.CreateDecryptor(this.KeyExchange.Key, new byte[16]);
            src.CopyTo(buf, 0);
            dec.TransformBlock(buf, offset, len + 16, buf, offset);
            Array.Copy(buf, offset, src, offset, len);
        }
Exemple #28
0
        public static void Decrypt(ICryptoTransform trans, byte[] input, byte[] output)
        {
            int bs      = trans.InputBlockSize;
            int full    = input.Length / bs;
            int partial = input.Length % bs;
            int pos     = 0;

            for (int i = 0; i < full; i++)
            {
                trans.TransformBlock(input, pos, bs, output, pos);
                pos += bs;
            }
            if (partial > 0)
            {
                byte[] final = trans.TransformFinalBlock(input, pos, partial);
                Array.Copy(final, 0, output, pos, partial);
            }
        }
Exemple #29
0
        public byte[] Decrypt(byte[] src, int offset)
        {
            if (aesKey == null)
            {
                return(src);
            }
            if (offset == src.Length)
            {
                return(src);
            }
            ICryptoTransform crypt = aes.CreateDecryptor(aesKey, new byte[16]);
            int len = src.Length - offset;

            byte[] buf = new byte[src.Length];
            src.CopyTo(buf, 0);
            crypt.TransformBlock(src, offset, len, buf, offset);
            return(buf);
        }
Exemple #30
0
        public static byte[] CreateEncryptedAnswerBlob(string answer, List <Direction> moveSequence)
        {
            byte[] key = MoveSequenceToKey(moveSequence);

            AesManaged aes = new AesManaged();

            aes.Key = key;
            aes.IV  = PuzzleIV;
            ICryptoTransform encryptor = aes.CreateEncryptor();

            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            byte[] answerBuffer = encoding.GetBytes(answer);

            byte[] encAnswer = new byte[answerBuffer.Length];
            encryptor.TransformBlock(answerBuffer, 0, answerBuffer.Length, encAnswer, 0);

            return(encAnswer);
        }
        public static string CreateOTP(YubikeySettings key, Form1 form)
        {
            string tokenID = ModHex.Encode(key.TokenID);

            // Assemble key unencrypted data
            byte[] keyBytes = new byte[16];
            for (int i = 0; i < key.PrivateID.Length; ++i)
            {
                keyBytes[i] = key.PrivateID[i];
            }
            keyBytes[6]         = (byte)(key.SessionCounter & 0xff);
            keyBytes[7]         = (byte)((key.SessionCounter >> 8) & 0xff);
            form.SessionCounter = key.SessionCounter.ToString();
            TimeSpan diff  = DateTime.Now - key.StartTime;
            int      timer = (int)((((uint)(diff.TotalSeconds / TS_SEC) & 0x00FFFFFF) + key.TimeStamp) & 0x00FFFFFF);

            form.Timestamp  = timer.ToString();
            keyBytes[8]     = (byte)(timer & 0xff);
            keyBytes[9]     = (byte)((timer >> 8) & 0xff);
            keyBytes[10]    = (byte)((timer >> 16) & 0xff);
            keyBytes[11]    = key.UseCounter++;
            form.UseCounter = keyBytes[11].ToString();
            byte[] buffer = new byte[2];
            RNGCryptoServiceProvider.Create().GetBytes(buffer);
            form.Random  = (((int)buffer[1] << 8) + (int)buffer[0]).ToString();
            keyBytes[12] = buffer[0];
            keyBytes[13] = buffer[1];
            CRC(keyBytes);

            using (Rijndael aes = Rijndael.Create())
            {
                aes.Padding = PaddingMode.None;
                aes.Mode    = CipherMode.ECB;

                using (ICryptoTransform xform = aes.CreateEncryptor(key.Secret, new byte[16]))
                {
                    byte[] plainBytes = new byte[16];
                    xform.TransformBlock(keyBytes, 0, keyBytes.Length, plainBytes, 0);

                    string otp = tokenID + ModHex.Encode(plainBytes);
                    return(otp);
                }
            }
        }
Exemple #32
0
        public int TransformDataUnit(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset, uint dataUnit)
        {
            byte[] encryptedTweak = new byte[0x10];
            byte[] tweak          = _tweakBytes;

            // Update tweak with data unit number
            Array.Copy(BitConverter.GetBytes(dataUnit), tweak, 4);

            // Encrypt tweak
            _tweakEncryptor.TransformBlock(tweak, 0, tweak.Length, encryptedTweak, 0);

            byte[] encryptedTweakOrig = new byte[0x10];
            Array.Copy(encryptedTweak, encryptedTweakOrig, 0x10);

            int blocks = inputCount / BlockSize;

            // Apply first part of tweak (input-tweak) to input buffer all at once
            for (int i = 0; i < blocks; i++)
            {
                for (int y = 0; y < BlockSize; y++)
                {
                    outputBuffer[outputOffset + (i * BlockSize) + y] = (byte)(inputBuffer[inputOffset + (i * BlockSize) + y] ^ encryptedTweak[y % encryptedTweak.Length]);
                }

                encryptedTweak = MultiplyTweak(encryptedTweak);
            }

            // AES transform the data...
            var transformedBytes = _dataTransform.TransformBlock(outputBuffer, outputOffset, inputCount, outputBuffer, outputOffset);

            // Reset tweak back to original encrypted tweak and then apply output-tweak
            Array.Copy(encryptedTweakOrig, encryptedTweak, 0x10);
            for (int i = 0; i < blocks; i++)
            {
                for (int y = 0; y < BlockSize; y++)
                {
                    outputBuffer[outputOffset + (i * BlockSize) + y] = (byte)(outputBuffer[outputOffset + (i * BlockSize) + y] ^ encryptedTweak[y % encryptedTweak.Length]);
                }

                encryptedTweak = MultiplyTweak(encryptedTweak);
            }

            return(transformedBytes);
        }
Exemple #33
0
        /* The Base64-encoded content in this file has been encrypted via AES-128 in ECB mode under the key
         *
         *  "YELLOW SUBMARINE".
         *  (case-sensitive, without the quotes; exactly 16 characters; I like "YELLOW SUBMARINE" because it's exactly 16 bytes long, and now you do too).
         *
         *  Decrypt it. You know the key, after all.
         */
        static void Main(string[] args)
        {
            //http://cryptopals.com/static/challenge-data/7.txt
            byte[] inbytes  = Convert.FromBase64String(getWebStuff("http://cryptopals.com/static/challenge-data/7.txt").Result);
            byte[] outbytes = new byte[inbytes.Length];
            byte[] block;
            byte[] key = Encoding.ASCII.GetBytes("YELLOW SUBMARINE");
            AesCryptoServiceProvider acsp = new AesCryptoServiceProvider();

            acsp.Mode    = CipherMode.ECB;
            acsp.KeySize = key.Length * 8;    // 16 bytes * 8 bits/byte = 128 although this is superfluous since AES-128 means 128 bit key
            acsp.Padding = PaddingMode.PKCS7; // Default padding mode for PKCS7; I tried none but discovered that the input data is in fact padded
            MemoryStream     inst   = new MemoryStream(inbytes);
            MemoryStream     outs   = new MemoryStream(outbytes);
            BinaryReader     rea    = new BinaryReader(inst);
            BinaryWriter     writer = new BinaryWriter(outs);
            ICryptoTransform decr   = acsp.CreateDecryptor(key, null);

            block = new byte[decr.InputBlockSize];
            int index  = 0;
            int oindex = 0;

            // Decrypt block by block, when we find that we are near the end of the stream
            // of input data, perform a final transform.
            while ((index = (int)rea.BaseStream.Position) < (int)rea.BaseStream.Length)
            {
                if (((int)rea.BaseStream.Length - index) <= decr.InputBlockSize)
                {
                    // Append last block to output byte stream
                    // by rewinding the output stream pointer oblock bytes
                    // from the end and writing the oblock to the output bytes
                    block = rea.ReadBytes(decr.InputBlockSize);
                    byte[] oblock = decr.TransformFinalBlock(block, 0, decr.InputBlockSize);
                    writer.BaseStream.Seek(-(long)oblock.Length, SeekOrigin.End);
                    writer.Write(oblock);
                    continue;
                }
                block = rea.ReadBytes(decr.InputBlockSize);
                decr.TransformBlock(block, 0, decr.InputBlockSize, outbytes, oindex);
                oindex = index;
            }
            System.Console.WriteLine(Encoding.ASCII.GetString(outbytes));
            System.Console.ReadKey();
        }
        // similar to previous case but here we try to skip several blocks
        // i.e. encdata.Length versus decdata.Length
        public void DontDecryptMultipleBlock(CipherMode mode, PaddingMode padding)
        {
            SymmetricAlgorithm algo = Algorithm;

            algo.Mode    = mode;
            algo.Padding = padding;
            ICryptoTransform enc = algo.CreateEncryptor();

            byte[] plaintext = new byte[BlockSize * 7];
            byte[] encdata   = new byte[BlockSize * 8];
            int    len       = enc.TransformBlock(plaintext, 0, plaintext.Length, encdata, 0);

            Assert.AreEqual(plaintext.Length, len, "encdata");

            ICryptoTransform dec = algo.CreateDecryptor();

            byte[] decdata = new byte[BlockSize];
            dec.TransformBlock(encdata, 0, encdata.Length, decdata, 0);
        }
		public void CheckCBC(ICryptoTransform encryptor, ICryptoTransform decryptor, 
					   byte[] plaintext, byte[] expected) 
		{
	
			if ((plaintext.Length % encryptor.InputBlockSize) != 0) {
				throw new ArgumentException("Must have complete blocks");
			}
	
			byte[] ciphertext = new byte[plaintext.Length];
			for (int i=0; i < plaintext.Length; i += encryptor.InputBlockSize) {
				encryptor.TransformBlock(plaintext, i, encryptor.InputBlockSize, ciphertext, i);
			}
			Assert.AreEqual (expected, ciphertext, "CBC");
	
			byte[] roundtrip = new byte[plaintext.Length];
			for (int i=0; i < ciphertext.Length; i += decryptor.InputBlockSize) {
				decryptor.TransformBlock(ciphertext, i, decryptor.InputBlockSize, roundtrip, i);
			}
			Assert.AreEqual (plaintext, roundtrip, "CBC-rt");
		}
        public Packet RecvPacket(ICryptoTransform decryptor)
        {
            if (decryptor == null)
            {
                Packet packet = new Packet();
                uint packet_length = reader.ReadUInt32();
                byte padding_length = reader.ReadByte();
                byte[] payload = reader.ReadBytes(packet_length - padding_length - 1);
                byte[] padding = reader.ReadBytes(padding_length);
                packet.SetPayload(payload);
                return packet;
            }
            else
            {
                int blocksize = Math.Max(decryptor.InputBlockSize, 8);
                MemoryStream ms_packet = new MemoryStream();
                NetworkByteWriter writer_packet = new NetworkByteWriter(ms_packet);

                byte[] buffer = new byte[blocksize];

                bool first = true;
                int more = 0;
                while (true)
                {
                    // read a block
                    int ret = reader.ReadBytes(buffer, 0, blocksize);
                    // must be a real block size;
                    if (ret != blocksize) return null;
                    decryptor.TransformBlock(buffer, 0, buffer.Length, buffer, 0);
                    writer_packet.WriteBytes(buffer);

                    if (first) // it's first time, need parse packet_length and padding_length
                    {
                        NetworkByteReader reader_buffer = new NetworkByteReader(new MemoryStream(buffer));
                        uint packet_length_t = reader_buffer.ReadUInt32();
                        first = false;

                        more = (int)packet_length_t + 4 - blocksize;
                        if (more % blocksize != 0) return null;
                    }
                    else
                    {
                        more -= blocksize;
                    }
                    if (more <= 0) break;
                }

                byte[] mac = reader.ReadBytes(20);

                ms_packet.Seek(0, SeekOrigin.Begin);
                NetworkByteReader reader_packet = new NetworkByteReader(ms_packet);

                Packet packet = new Packet();
                uint packet_length = reader_packet.ReadUInt32();
                byte padding_length = reader_packet.ReadByte();
                byte[] payload = reader_packet.ReadBytes(packet_length - padding_length - 1);
                byte[] padding = reader_packet.ReadBytes(padding_length);
                packet.SetPayload(payload);

                return packet;
            }
        }
Exemple #37
0
 private static void Collect(this List<byte> l, ICryptoTransform transform, Stream input, int count)
 {
     byte[] buffer = new byte[count];
     int numRead = input.Read(buffer, 0, count);
     Assert.Equal(count, numRead);
     byte[] buffer2 = new byte[count];
     int numBytesWritten = transform.TransformBlock(buffer, 0, count, buffer2, 0);
     Array.Resize(ref buffer2, numBytesWritten);
     l.AddRange(buffer2);
 }
Exemple #38
0
        /// <summary>
        /// Create and return an Initialization Vector (IV) using a given sequence-number and encryptor.
        /// </summary>
        /// <param name="encryptor"></param>
        /// <param name="seqNumBytes"></param>
        /// <returns></returns>
        private byte[] GenerateIV(ICryptoTransform encryptor, byte[] seqNumBytes)
        {
            // generating an IV by encrypting the sequence number with the random IV and encrypting symmetric key
            byte[] iv = new byte[SecurityParameters.RecordIVLength];
            Buffer.BlockCopy(seqNumBytes, 0, iv, 0, 8);

            byte padding = (byte)((encryptor.OutputBlockSize - (9 % encryptor.OutputBlockSize)) % encryptor.OutputBlockSize);
            for (int i = 8; i < iv.Length; i++)
            {
                iv[i] = padding;
            }

            // Compute the hash value for the region of the input byte-array (iv), starting at index 0,
            // and copy the resulting hash value back into the same byte-array.
            encryptor.TransformBlock(iv, 0, iv.Length, iv, 0);
            return iv;
        }
		static byte[] AESCTREncrypt(ICryptoTransform aes, byte[] buffer, int bufferLen, byte[] ivec, byte[] evec, ref int blockOffset, ref int blockIndex)
		{			
			byte[] ret = new byte[bufferLen];
			for (int i = 0 ; i < bufferLen ; i++)
			{
				if (blockOffset == 0) //calculate the encrypted block
				{
					//increment the ivec as if it were a 128-bit big endian number
					byte[] newIvec = (byte[])ivec.Clone();
					long val = BitConverter.ToInt64(ivec, 8);
					val = IPAddress.HostToNetworkOrder(IPAddress.NetworkToHostOrder(val) + blockIndex);
					byte[] valarray = BitConverter.GetBytes(val);
					valarray.CopyTo(newIvec, 8);
					aes.TransformBlock(newIvec, 0, newIvec.Length, evec, 0);
					blockIndex++;
				}
				ret[i] = (byte)(buffer[i] ^ evec[blockOffset]);
				blockOffset = (blockOffset + 1) % aes.OutputBlockSize;
			}
			return ret;
		}
Exemple #40
0
        private byte[] GenerateIV(ICryptoTransform encryptor, byte[] seqNumBytes)
        {
            // generating an IV by encrypting the sequence number with the random IV and encrypting symmetric key
            byte[] iv = new byte[SecurityParameters.RecordIVLength];
            Buffer.BlockCopy(seqNumBytes, 0, iv, 0, 8);

            byte padding = (byte)((encryptor.OutputBlockSize - (9 % encryptor.OutputBlockSize)) % encryptor.OutputBlockSize);
            for (int i = 8; i < iv.Length; i++)
            {
                iv[i] = padding;
            }

            encryptor.TransformBlock(iv, 0, iv.Length, iv, 0);
            return iv;
        }
Exemple #41
0
        static void Encrypt(byte[] data, int offset, int len, ICryptoTransform key, byte[] iv, int startCounter, byte[] temp512)
        {
            var buf = temp512;
            var block = startCounter;

            const int numBlocks = 32;

            for (var pos = 0; pos < len; pos += 16 * numBlocks)
            {
                var blocks = numBlocks;
                if (pos + 16 * numBlocks > len)
                    blocks = (len - pos + 15) / 16;

                for (var i = 0; i < blocks; i++)
                {
                    Buffer.BlockCopy(iv, 0, buf, i * 16, 14);
                    buf[i * 16 + 14] = (byte)(block >> 8);
                    buf[i * 16 + 15] = (byte)block;
                    ++block;
                }

                key.TransformBlock(buf, 0, blocks * 16, buf, 0);
                var end = Math.Min(pos + numBlocks * 16, len);
                for (int i = pos, j = 0; i < end; i++, j++)
                {
                    data[offset + i] ^= buf[j];
                }
            }
        }
Exemple #42
0
 public static ulong[] GetH(ICryptoTransform key)
 {
     var bytes = new byte[16];
     key.TransformBlock(bytes, 0, 16, bytes, 0);
     int offset = 0;
     var h1 = Utils.ReadUInt64(bytes, ref offset);
     var h2 = Utils.ReadUInt64(bytes, ref offset);
     Utils.ClearArray(bytes);
     return Construct(h1, h2);
 }
Exemple #43
0
        public void CheckECBRoundtrip(ICryptoTransform encryptor, ICryptoTransform decryptor, 
					   byte[] plaintext, byte[] expected)
        {
            byte[] ciphertext = new byte[plaintext.Length];
            encryptor.TransformBlock(plaintext, 0, plaintext.Length, ciphertext, 0);

            Assert.AreEqual (expected, ciphertext, "ECB");

            byte[] roundtrip = new byte[plaintext.Length];
            decryptor.TransformBlock(ciphertext, 0, ciphertext.Length, roundtrip, 0);

            Assert.AreEqual (plaintext, roundtrip, "ECB-rt-len");
        }
Exemple #44
0
 void TransformMultiByte(byte[] input, byte[] output, ICryptoTransform transform)
 {
     if (input.Length != output.Length)
     {
         throw new Exception("Input and output size must match");
     }
     if (testmode)
     {
         Buffer.BlockCopy(input, 0, output, 0, output.Length);
         return;
     }
     int ib = transform.InputBlockSize;
     if (transform.CanTransformMultipleBlocks)
     {
         transform.TransformBlock(input, 0, output.Length, output, 0);
     }else {
         for (int i = 0; i < output.Length; i += ib)
         {
             transform.TransformBlock(input, i, ib, output, i);
         }
     }
 }
Exemple #45
0
        private static byte[] TransformRecordBytes(BulkCipherAlgorithmType cipherType, ICryptoTransform transform, byte[] input)
        {
            if (cipherType != BulkCipherAlgorithmType.AEAD) {
                // In case of non-AEAD cipher algorithm, check that data matches block size
                if (input.Length % transform.InputBlockSize != 0) {
                    throw new Exception("Input data size doesn't match block size");
                }
            }

            int blockCount = input.Length / transform.InputBlockSize;
            if (cipherType == BulkCipherAlgorithmType.AEAD) {
                // Make sure there is enough data at TransformFinalBlock, because
                // decryption requires that the authentication tag is present
                if (blockCount > 0) {
                    blockCount--;
                }
            }

            byte[] output = new byte[blockCount * transform.OutputBlockSize];
            if (transform.CanTransformMultipleBlocks) {
                transform.TransformBlock(input, 0, blockCount*transform.InputBlockSize, output, 0);
            } else {
                for (int i=0; i<blockCount; i++) {
                    transform.TransformBlock(input, i*transform.InputBlockSize,
                                             transform.InputBlockSize,
                                             output, i*transform.OutputBlockSize);
                }
            }

            if (cipherType == BulkCipherAlgorithmType.AEAD) {
                int currentPosition = blockCount*transform.InputBlockSize;

                // Transfer the last block when encrypting or authentication tag when decrypting
                byte[] finalBytes = transform.TransformFinalBlock(input, currentPosition, input.Length-currentPosition);
                if (finalBytes == null) {
                    return null;
                } else if (finalBytes.Length > 0) {
                    byte[] finalOutput = new byte[output.Length + finalBytes.Length];
                    Buffer.BlockCopy(output, 0, finalOutput, 0, output.Length);
                    Buffer.BlockCopy(finalBytes, 0, finalOutput, output.Length, finalBytes.Length);
                    output = finalOutput;
                }
            }

            return output;
        }
		public void CheckECBRoundtrip(ICryptoTransform encryptor, ICryptoTransform decryptor, 
					   byte[] plaintext, byte[] expected)
		{
			byte[] ciphertext = new byte[plaintext.Length];
			int n = encryptor.TransformBlock(plaintext, 0, plaintext.Length, ciphertext, 0);
	
			AssertEquals("ECB-len", n, expected.Length);
			for (int i=0; i < ciphertext.Length; i++) {
				AssertEquals("ECB-encrypt-" + i, ciphertext[i], expected[i]);
			}
	
			byte[] roundtrip = new byte[plaintext.Length];
			n = decryptor.TransformBlock(ciphertext, 0, ciphertext.Length, roundtrip, 0);
	
			AssertEquals("ECB-rt-len", n, plaintext.Length);
			for (int i=0; i < roundtrip.Length; i++) {
				AssertEquals("ECB-rt-" + i, roundtrip[i], plaintext[i]);
			}
		}
Exemple #47
0
        private void DecryptBytes(ICryptoTransform decryptor, byte[] cipherBytes,
          out byte[] plainBytes, out byte[] mac, out byte[] padding)
        {
            if (cipherBytes.Length % decryptor.InputBlockSize != 0)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.EncryptedFrameInvalidLength, "Invalid block size for cipher bytes");
            }

            byte[] frameBytes = new byte[cipherBytes.Length];

            int dataLength;
            int paddingSize;

            if (SecurityParameters.BulkCipherAlgorithm != BulkCipherAlgorithm.Null)
            {
                decryptor.TransformBlock(cipherBytes, 0, cipherBytes.Length, frameBytes, 0);

                paddingSize = frameBytes[frameBytes.Length - 1] + 1;

                if (paddingSize > decryptor.InputBlockSize)
                {
                    // somebody tamper the message, we don't want throw the exception yet because
                    // of timing issue, we need to throw the exception after the mac check,
                    // therefore we will change the padding size to the size of the block
                    paddingSize = decryptor.InputBlockSize;
                }

                dataLength = frameBytes.Length - paddingSize - SecurityParameters.MACLength;

                // data length can be zero if somebody tamper with the padding
                if (dataLength < 0)
                {
                    dataLength = 0;
                }
            }
            else
            {
                dataLength = frameBytes.Length - SecurityParameters.MACLength;
                frameBytes = cipherBytes;
                paddingSize = 0;
            }

            plainBytes = new byte[dataLength];
            Buffer.BlockCopy(frameBytes, 0, plainBytes, 0, dataLength);

            mac = new byte[SecurityParameters.MACLength];
            Buffer.BlockCopy(frameBytes, dataLength, mac, 0, SecurityParameters.MACLength);

            padding = new byte[paddingSize];
            Buffer.BlockCopy(frameBytes, dataLength + SecurityParameters.MACLength, padding, 0, paddingSize);
        }
Exemple #48
0
        private byte[] EncryptBytes(ICryptoTransform encryptor, ContentType contentType, ulong seqNum,
          int frameIndex, byte[] plainBytes)
        {
            byte[] mac;

            if (SecurityParameters.MACAlgorithm != MACAlgorithm.Null)
            {
                byte[] versionAndType = new byte[] { (byte)contentType, m_protocolVersion[0], m_protocolVersion[1] };
                byte[] seqNumBytes = BitConverter.GetBytes(seqNum);
                byte[] messageSize = BitConverter.GetBytes(plainBytes.Length);
                byte[] frameIndexBytes = BitConverter.GetBytes(frameIndex);

                m_encryptionHMAC.Initialize();
                m_encryptionHMAC.TransformBlock(seqNumBytes, 0, seqNumBytes.Length, seqNumBytes, 0);
                m_encryptionHMAC.TransformBlock(versionAndType, 0, versionAndType.Length, versionAndType, 0);
                m_encryptionHMAC.TransformBlock(messageSize, 0, messageSize.Length, messageSize, 0);
                m_encryptionHMAC.TransformBlock(frameIndexBytes, 0, frameIndexBytes.Length, frameIndexBytes, 0);
                m_encryptionHMAC.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
                mac = m_encryptionHMAC.Hash;
            }
            else
            {
                mac = new byte[0];
            }

            int length = plainBytes.Length + SecurityParameters.MACLength;
            byte padding = 0;

            if (SecurityParameters.BulkCipherAlgorithm != BulkCipherAlgorithm.Null)
            {
                padding = (byte)((encryptor.OutputBlockSize -
                                        (plainBytes.Length + SecurityParameters.MACLength + 1) % encryptor.OutputBlockSize) %
                                       encryptor.OutputBlockSize);

                length += padding + 1;
            }

            byte[] cipherBytes = new byte[length];

            Buffer.BlockCopy(plainBytes, 0, cipherBytes, 0, plainBytes.Length);
            Buffer.BlockCopy(mac, 0, cipherBytes, plainBytes.Length, SecurityParameters.MACLength);

            if (SecurityParameters.BulkCipherAlgorithm != BulkCipherAlgorithm.Null)
            {
                for (int i = plainBytes.Length + SecurityParameters.MACLength; i < cipherBytes.Length; i++)
                {
                    cipherBytes[i] = padding;
                }

                encryptor.TransformBlock(cipherBytes, 0, cipherBytes.Length, cipherBytes, 0);
            }

            return cipherBytes;
        }
Exemple #49
0
 void TransformBlocksFast(byte[] bufIn, byte[] bufOut, ICryptoTransform transformer)
 {
     for (int i = 0; i < bufIn.Length / BlockSize; i++)
         transformer.TransformBlock(bufIn, i * BlockSize, BlockSize, bufOut, i * BlockSize);
 }
Exemple #50
0
 public void decrypt(byte[] criptedData, byte[] destination)
 {
     tfDecryptor = tf.CreateDecryptor(tf.Key,tf.IV);
     for (int i = 0;i<criptedData.Length/16;i++)
         tfDecryptor.TransformBlock(criptedData,i*16,16,destination,i*16);
 }
Exemple #51
0
 internal static byte[] GenericTransform(ICryptoTransform transform,
                                     byte[] data)
 {
     List<byte> byteList = new List<byte>();
       byte[] outputBytes;
       int inputLength = data.Length;
       int inputBlockSize = transform.InputBlockSize;
       if (typeof(FromBase64Transform).IsInstanceOfType(transform)) {
     // workaround for apparent bug where FromBase64Transform.InputBlockSize
     // returns 1 when it should return 4
     inputBlockSize = 4;
       }
       int inputOffset = 0;
       outputBytes = new byte[transform.OutputBlockSize];
       if (!transform.CanTransformMultipleBlocks) {
     while (inputLength - inputOffset > inputBlockSize) {
       transform.TransformBlock(data, inputOffset, inputBlockSize,
     outputBytes, 0);
       byteList.AddRange(outputBytes);
       inputOffset += inputBlockSize;
     }
       }
       outputBytes = transform.TransformFinalBlock(data, inputOffset,
                                           inputLength - inputOffset);
       byteList.AddRange(outputBytes);
       byte[] result = byteList.ToArray();
       ClearByteList(byteList);
       return result;
 }
Exemple #52
0
 public void encrypt(byte[] plainData, byte[] destination)
 {
     tfEncryptor = tf.CreateEncryptor(tf.Key,tf.IV);
     for (int i = 0;i<plainData.Length/16;i++)
         tfEncryptor.TransformBlock(plainData,i*16,16,destination,i*16);
 }
Exemple #53
0
        /// <summary>
        /// Does the actual work of pulling the filestreams in
        /// and passing the blocks into the crytoprovider
        /// </summary>
        /// <param name="filenames">An array of String objects, each containing a filename</param>
        /// <param name="cryptoInterface">An <see cref="ICryptoTransform"/> interface pointing to a cryptoprovider</param>
        /// <param name="blockSize">Size in bytes of the transform block / read buffer</param>
        protected void ComputeHashes(String[] filenames, ICryptoTransform cryptoInterface, int blockSize)
        {
            for (int loop = 0; loop <= filenames.GetUpperBound(0); loop++)
            {
                using (FileStream inputFile = new FileStream(filenames[loop], FileMode.Open, FileAccess.Read))
                {
                    byte[] readBuffer = new byte[(int)blockSize];
                    byte[] copyBuffer;
                    long fileLength = inputFile.Length;
                    int bytesRead = 0;
                    long totalBytesRead = 0;

                    while (totalBytesRead < fileLength)
                    {
                        bytesRead = inputFile.Read(readBuffer, 0, (int)blockSize);
                        if (bytesRead == blockSize) { copyBuffer = readBuffer; }
                        else
                        {
                            copyBuffer = new byte[bytesRead];
                            Array.Copy(readBuffer, copyBuffer, bytesRead);
                        }
                        totalBytesRead += bytesRead;
                        if (totalBytesRead == fileLength && loop == filenames.GetUpperBound(0))
                        {
                            // Last block of the last file
                            cryptoInterface.TransformFinalBlock(copyBuffer, 0, copyBuffer.Length);
                        }
                        else
                        {
                            cryptoInterface.TransformBlock(copyBuffer, 0, copyBuffer.Length, copyBuffer, 0);
                        }
                        // Report progress and
                        // check for cancellation request
                        OnHashBlockProcessed(new HasherEventArgs(HasherEventReportType.ProgressReport,
                                         filenames.Length,
                                         loop + 1,
                                         totalBytesRead,
                                         fileLength));
                        if (this.cancelRequested == true)
                        {
                            throw new OperationCanceledException();
                        }

                    }
                }
            }
            // Report hash computed
            OnHashComputed(new HasherEventArgs(HasherEventReportType.Completed, null, null, null, null));
        }
		private void TransformBlock_One (ICryptoTransform ct, int expected)
		{
			byte[] data = new byte[ct.InputBlockSize];
			Assert.AreEqual (expected, ct.TransformBlock (data, 0, ct.InputBlockSize, data, 0));
		}
Exemple #55
0
 private static int TransformBlock16Rounds(ICryptoTransform instance, byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
 {
     int res = 0;
     for (int i = 0; i < 16; ++i)
     {
         res = instance.TransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
     }
     return inputCount;
 }