Esempio n. 1
0
        /**
         * Create a buffered block cipher without padding.
         *
         * @param cipher the underlying block cipher this buffering object wraps.
         * @param padded true if the buffer should add, or remove, pad bytes,
         * false otherwise.
         */
        public BufferedBlockCipher(
            BlockCipher cipher)
        {
            this.cipher = cipher;

            buf    = new byte[cipher.getBlockSize()];
            bufOff = 0;

            //
            // check if we can handle partial blocks on doFinal.
            //
            String name = cipher.getAlgorithmName();
            int    idx  = name.IndexOf('/') + 1;

            pgpCFB = (idx > 0 && name.Substring(idx).StartsWith("PGP"));

            if (pgpCFB)
            {
                partialBlockOkay = true;
            }
            else
            {
                partialBlockOkay = (idx > 0 && (name.Substring(idx).StartsWith("CFB") ||
                                                name.Substring(idx).StartsWith("OFB")));
            }
        }
Esempio n. 2
0
        private int DecryptBlock(
            byte[] input,
            int inOff,
            byte[] outBytes,
            int outOff)
        {
            input.DeepCopy_NoChecks(inOff, _cbcNextV, 0, CipherBlockSize);

            int length = BlockCipher.ProcessBlock(input, inOff, outBytes, outOff);

            /*
             * XOR the cbcV and the output
             */
            outBytes.XorInPlaceInternal(outOff, _cbcV, 0, CipherBlockSize);

            /*
             * swap the back up buffer into next position
             */
            byte[] tmp;

            tmp       = _cbcV;
            _cbcV     = _cbcNextV;
            _cbcNextV = tmp;

            return(length);
        }
        /// <summary>
        /// Creates a configuration for key confirmation using an CMAC/OMAC1 construction.
        /// </summary>
        /// <param name="cipherEnum">Block cipher to use as basis of CMAC construction.</param>
        /// <returns>A key confirmation configuration as a <see cref="AuthenticationConfiguration"/>.</returns>
        public static AuthenticationConfiguration GenerateConfiguration(BlockCipher cipherEnum)
        {
            int outputSize;
            var config = AuthenticationConfigurationFactory.CreateAuthenticationConfigurationCmac(cipherEnum, out outputSize);

            return(config);
        }
Esempio n. 4
0
        /// <summary>
        ///     Reset the chaining vector back to the IV and reset the underlying cipher.
        /// </summary>
        public override void Reset()
        {
            Array.Copy(IV, 0, _cfbV, 0, IV.Length);
            _cfbOutV.SecureWipe();

            BlockCipher.Reset();
        }
Esempio n. 5
0
 /**
  * create a standard MAC based on a block cipher with the size of the
  * MAC been given in bits. This class uses CFB mode as the basis for the
  * MAC generation.
  * <p>
  * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
  * or 16 bits if being used as a data authenticator (FIPS Publication 113),
  * and in general should be less than the size of the block cipher as it reduces
  * the chance of an exhaustive attack (see Handbook of Applied Cryptography).
  *
  * @param cipher the cipher to be used as the basis of the MAC generation.
  * @param cfbBitSize the size of an output block produced by the CFB mode.
  * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
  */
 public CFBBlockCipherMac(
     BlockCipher cipher,
     int cfbBitSize,
     int macSizeInBits)
     : this(cipher, cfbBitSize, macSizeInBits, null)
 {
 }
Esempio n. 6
0
        public static void Initialize()
        {
            if (IsOpen || ListeningThread != null)
            {
                return;
            }

            ushort port = (ushort)Configuration.General["Master Port"];

            Sock = new UdpClient(Configuration.General["Master Addr"], port);

            // TODO figure out what this has to do with ICMP (in server too)
            uint IOC_IN            = 0x80000000,
                 IOC_VENDOR        = 0x18000000,
                 SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 0xC;

            Sock.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { 0 }, null);

            Key       = new Key();
            Encryptor = null;

            IsOpen          = true;
            ListeningThread = new Thread(Listener);
            ListeningThread.Start();
        }
Esempio n. 7
0
 /**
  * Basic constructor.
  *
  * @param c the block cipher to be used.
  */
 public SICBlockCipher(BlockCipher c)
 {
     this.cipher     = c;
     this.blockSize  = cipher.getBlockSize();
     this.IV         = new byte[blockSize];
     this.counter    = new byte[blockSize];
     this.counterOut = new byte[blockSize];
 }
Esempio n. 8
0
 public BlockSizeException(BlockCipher cipherEnum, int requestedSizeBits)
     : base(String.Format("The size {0} is not supported for use with the {1} cipher.", requestedSizeBits,
                          Athena.Cryptography.BlockCiphers[cipherEnum].DisplayName))
 {
     RequestedSize = requestedSizeBits;
     Mode          = cipherEnum;
     AllowedSizes  = Athena.Cryptography.BlockCiphers[cipherEnum].AllowableBlockSizesBits.ToList();
 }
Esempio n. 9
0
        /**
         * basic constructor.
         *
         * @param cipher the block cipher to be wrapped.
         * @exception IllegalArgumentException if the cipher has a block size other than
         * one.
         */
        public StreamBlockCipher(
            BlockCipher cipher)
        {
            if (cipher.getBlockSize() != 1)
            {
                throw new ArgumentException("block cipher block size != 1.");
            }

            this.cipher = cipher;
        }
Esempio n. 10
0
        /**
         * Basic constructor.
         *
         * @param cipher the block cipher to be used as the basis of chaining.
         */
        public CBCBlockCipher(
            BlockCipher cipher)
        {
            this.cipher    = cipher;
            this.blockSize = cipher.getBlockSize();

            this.IV       = new byte[blockSize];
            this.cbcV     = new byte[blockSize];
            this.cbcNextV = new byte[blockSize];
        }
Esempio n. 11
0
        /**
         * Create a buffered block cipher with the desired padding.
         *
         * @param cipher the underlying block cipher this buffering object wraps.
         * @param padding the padding type.
         */
        public PaddedBufferedBlockCipher(
            BlockCipher cipher,
            BlockCipherPadding padding)
        {
            this.cipher  = cipher;
            this.padding = padding;

            buf    = new byte[cipher.getBlockSize()];
            bufOff = 0;
        }
Esempio n. 12
0
        /// <summary>
        /// Reset the cipher to the same state as it was after the last init (if there was one).
        /// </summary>
        public override void Reset()
        {
            if (IV != null)
            {
                Array.Copy(IV, 0, _cbcV, 0, IV.Length);
            }
            _cbcNextV.SecureWipe();

            BlockCipher.Reset();
        }
Esempio n. 13
0
        /// <inheritdoc />
        protected override void InitState(byte[] key)
        {
            // Prepend the supplied IV with zeros (as per FIPS PUB 81)
            byte[] workingIv = new byte[CipherBlockSize];
            IV.DeepCopy_NoChecks(0, workingIv, CipherBlockSize - IV.Length, IV.Length);
            Array.Clear(workingIv, 0, CipherBlockSize - IV.Length);
            IV = workingIv;

            Reset();
            BlockCipher.Init(true, key); // Streaming mode - cipher always used in encryption mode
        }
Esempio n. 14
0
        /**
         * Basic constructor.
         *
         * @param cipher the block cipher to be used as the basis of the
         * feedback mode.
         * @param blockSize the block size in bits (note: a multiple of 8)
         */
        public CFBBlockCipher(
            BlockCipher cipher,
            int bitBlockSize)
        {
            this.cipher    = cipher;
            this.blockSize = bitBlockSize / 8;

            this.IV      = new byte[cipher.getBlockSize()];
            this.cfbV    = new byte[cipher.getBlockSize()];
            this.cfbOutV = new byte[cipher.getBlockSize()];
        }
Esempio n. 15
0
        protected override BlockCipher EncryptBlock(BlockCipher block)
        {
            uint uint32_1 = BitConverter.ToUInt32(block.ToBytesArray(), 0);
            uint uint32_2 = BitConverter.ToUInt32(block.ToBytesArray(), 4);
            uint num1     = 0;
            uint num2     = 32;

            while (num2-- > 0U)
            {
            }
            return(new BlockCipher((DWord)uint32_1, (DWord)uint32_2));
        }
Esempio n. 16
0
        private void btnSaveStream_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter           = "Image files (*.png;*.jpg;*.jpeg)|*.png;*.jpg;*.jpeg";
            saveFileDialog.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;

            if (saveFileDialog.ShowDialog() == true)
            {
                File.WriteAllBytes(saveFileDialog.FileName, BlockCipher.imageToByteArray(_encryptedBitmap));
            }
        }
Esempio n. 17
0
 /// <summary>
 ///     Instantiates and returns an implementation of the requested symmetric block cipher.
 /// </summary>
 /// <returns>A <see cref="BlockCipherBase" /> cipher object implementing the relevant cipher algorithm.</returns>
 public static BlockCipherBase CreateBlockCipher(BlockCipher cipherEnum, int?blockSize = null)
 {
     if (cipherEnum == BlockCipher.None)
     {
         throw new ArgumentException("Cipher set to None.", "cipherEnum",
                                     new InvalidOperationException("Cannot instantiate null block cipher."));
     }
     if (blockSize == null)
     {
         blockSize = Athena.Cryptography.BlockCiphers[cipherEnum].DefaultBlockSizeBits;
     }
     return(EngineInstantiatorsBlock[cipherEnum](blockSize.Value));
 }
Esempio n. 18
0
 private int EncryptBlock(
     byte[] input,
     int inOff,
     byte[] outBytes,
     int outOff)
 {
     BlockCipher.ProcessBlock(_cfbV, 0, _cfbOutV, 0);
     // XOR the cfbV with the plaintext producing the ciphertext
     input.XorInternal(inOff, _cfbOutV, 0, outBytes, outOff, _feedbackSize);
     // change over the input block.
     Array.Copy(_cfbV, _feedbackSize, _cfbV, 0, _cfbV.Length - _feedbackSize);
     Array.Copy(outBytes, outOff, _cfbV, _cfbV.Length - _feedbackSize, _feedbackSize);
     return(_feedbackSize);
 }
Esempio n. 19
0
        /// <inheritdoc />
        internal override int ProcessBlockInternal(byte[] input, int inOff, byte[] output, int outOff)
        {
            BlockCipher.ProcessBlock(_ofbV, 0, _ofbOutV, 0);

            // XOR the ofbV with the plaintext producing the cipher text (and
            // the next input block).
            input.XorInternal(inOff, _ofbOutV, 0, output, outOff, CipherBlockSize);

            // change over the input block.
            Array.Copy(_ofbV, CipherBlockSize, _ofbV, 0, _ofbV.Length - CipherBlockSize);
            Array.Copy(_ofbOutV, 0, _ofbV, _ofbV.Length - CipherBlockSize, CipherBlockSize);

            return(CipherBlockSize);
        }
Esempio n. 20
0
        /// <summary>
        /// Create a configuration for a block cipher.
        /// </summary>
        /// <param name="cipher">Block cipher to use.</param>
        /// <param name="mode">Mode of operation for the cipher.</param>
        /// <param name="padding">Padding scheme to use with the mode, where necessary (e.g. CBC).</param>
        /// <param name="keySize">Key size to use, in bits.</param>
        /// <param name="blockSize">Cipher block size to use, in bits.</param>
        /// <returns>Block cipher configuration DTO.</returns>
        public static CipherConfiguration CreateBlockCipherConfiguration(BlockCipher cipher,
                                                                         BlockCipherMode mode, BlockCipherPadding padding, int?keySize = null, int?blockSize = null)
        {
            var config = new CipherConfiguration {
                Type = CipherType.Block
            };

            // Set the key size
            int keySizeNonNull = keySize ?? Athena.Cryptography.BlockCiphers[cipher].DefaultKeySizeBits;

            if (keySize == null || Athena.Cryptography.BlockCiphers[cipher].AllowableKeySizesBits.Contains(keySizeNonNull))
            {
                config.KeySizeBits = keySizeNonNull;
            }
            else
            {
                throw new CipherKeySizeException(cipher, keySizeNonNull);
            }

            // Set the block size
            int blockSizeNonNull = blockSize ?? Athena.Cryptography.BlockCiphers[cipher].DefaultBlockSizeBits;

            if (blockSize == null ||
                Athena.Cryptography.BlockCiphers[cipher].AllowableBlockSizesBits.Contains(blockSizeNonNull))
            {
                config.BlockSizeBits = blockSizeNonNull;
            }
            else
            {
                throw new BlockSizeException(cipher, blockSizeNonNull);
            }

            // Set the mode
            if (Athena.Cryptography.BlockCipherModes[mode].PaddingRequirement == PaddingRequirement.Always &&
                padding == BlockCipherPadding.None)
            {
                throw new ArgumentException(mode +
                                            " mode must be used with padding or errors will occur when plaintext length is not equal to or a multiple of the block size.");
            }

            config.ModeName    = mode.ToString();
            config.PaddingName = padding.ToString();
            config.CipherName  = cipher.ToString();

            config.InitialisationVector = new byte[config.BlockSizeBits.Value / 8];
            StratCom.EntropySupplier.NextBytes(config.InitialisationVector);

            return(config);
        }
Esempio n. 21
0
        protected override BlockCipher DecryptBlock(BlockCipher block)
        {
            uint uint32_1 = BitConverter.ToUInt32(block.ToBytesArray(), 0);
            uint uint32_2 = BitConverter.ToUInt32(block.ToBytesArray(), 4);
            uint num1     = 3337565984;
            uint num2     = 32;

            while (num2-- > 0U)
            {
                //uint32_2 -= (uint)(((int)uint32_1 << 4 ^ (int)(uint32_1 >> 5)) + (int)uint32_1 ^ (int)num1 + (int)this._realedKey[(IntPtr)(num1 >> 11 & 3U)]);
                //num1 -= 2654435769U;
                //uint32_1 -= (uint)(((int)uint32_2 << 4 ^ (int)(uint32_2 >> 5)) + (int)uint32_2 ^ (int)num1 + (int)this._realedKey[(IntPtr)(num1 & 3U)]);
            }
            return(new BlockCipher((DWord)uint32_1, (DWord)uint32_2));
        }
Esempio n. 22
0
        /// <inheritdoc />
        internal override int ProcessBlockInternal(byte[] input, int inOff, byte[] output, int outOff)
        {
            BlockCipher.ProcessBlock(_counter, 0, _counterOut, 0);

            // XOR the counterOut with the plaintext producing the cipher text
            input.XorInternal(inOff, _counterOut, 0, output, outOff, CipherBlockSize);

            // Increment the counter
            int j = CipherBlockSize;

            while (--j >= 0 && ++_counter[j] == 0)
            {
            }

            return(CipherBlockSize);
        }
Esempio n. 23
0
        /// <summary>
        ///     Creates a Poly1305 primitive using a symmetric block cipher primitive (cipher must have a block size of 128 bits).
        ///     If salt is used, it is applied as: salt||message, where || is concatenation.
        /// </summary>
        /// <param name="cipherEnum">Cipher primitive to use as the basis for the Poly1305 construction.</param>
        /// <param name="key">Cryptographic key to use in the MAC operation.</param>
        /// <param name="nonce">Initialisation vector/nonce. Required.</param>
        /// <param name="salt">Cryptographic salt to use in the MAC operation, if any.</param>
        /// <returns>Pre-initialised Poly1305 MAC primitive as a <see cref="IMac" />.</returns>
        public static IMac CreatePoly1305Primitive(BlockCipher cipherEnum, byte[] key, byte[] nonce, byte[] salt = null)
        {
            if (Athena.Cryptography.BlockCiphers[cipherEnum].DefaultBlockSizeBits != 128)
            {
                throw new NotSupportedException();
            }

            var macObj = new Poly1305Mac(CipherFactory.CreateBlockCipher(cipherEnum));

            macObj.Init(key, nonce);
            if (salt.IsNullOrZeroLength() == false)
            {
                macObj.BlockUpdate(salt, 0, salt.Length);
            }

            return(macObj);
        }
Esempio n. 24
0
        /// <summary>
        ///     Creates a CMAC primitive using a symmetric block cipher primitive configured with default block size.
        ///     Default block sizes (and so, output sizes) can be found by querying <see cref="Athena" />.
        /// </summary>
        /// <param name="cipherEnum">
        ///     Cipher primitive to use as the basis for the CMAC construction. Block size must be 64 or 128
        ///     bits.
        /// </param>
        /// <param name="key">Cryptographic key to use in the MAC operation.</param>
        /// <param name="salt">Cryptographic salt to use in the MAC operation, if any.</param>
        /// <returns>Pre-initialised CMAC primitive as a <see cref="IMac" />.</returns>
        public static IMac CreateCmacPrimitive(BlockCipher cipherEnum, byte[] key, byte[] salt = null)
        {
            int?defaultBlockSize = Athena.Cryptography.BlockCiphers[cipherEnum].DefaultBlockSizeBits;

            if (defaultBlockSize != 64 && defaultBlockSize != 128)
            {
                throw new NotSupportedException("CMAC/OMAC1 only supports ciphers with 64 / 128 bit block sizes.");
            }
            var macObj = new CMac(CipherFactory.CreateBlockCipher(cipherEnum, null));

            macObj.Init(key);
            if (salt.IsNullOrZeroLength() == false)
            {
                macObj.BlockUpdate(salt, 0, salt.Length);
            }

            return(macObj);
        }
Esempio n. 25
0
        /**
         * create a standard MAC based on a block cipher with the size of the
         * MAC been given in bits. This class uses CBC mode as the basis for the
         * MAC generation.
         * <p>
         * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
         * or 16 bits if being used as a data authenticator (FIPS Publication 113),
         * and in general should be less than the size of the block cipher as it reduces
         * the chance of an exhaustive attack (see Handbook of Applied Cryptography).
         *
         * @param cipher the cipher to be used as the basis of the MAC generation.
         * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
         * @param padding the padding to be used to complete the last block.
         */
        public CBCBlockCipherMac(
            BlockCipher cipher,
            int macSizeInBits,
            BlockCipherPadding padding)
        {
            if ((macSizeInBits % 8) != 0)
            {
                throw new ArgumentException("MAC size must be multiple of 8");
            }

            this.cipher  = new CBCBlockCipher(cipher);
            this.padding = padding;
            this.macSize = macSizeInBits / 8;

            mac = new byte[cipher.getBlockSize()];

            buf    = new byte[cipher.getBlockSize()];
            bufOff = 0;
        }
Esempio n. 26
0
        private int EncryptBlock(
            byte[] input,
            int inOff,
            byte[] outBytes,
            int outOff)
        {
            /*
             * XOR the cbcV and the input,
             * then encrypt the cbcV
             */
            _cbcV.XorInPlaceInternal(0, input, inOff, CipherBlockSize);

            int length = BlockCipher.ProcessBlock(_cbcV, 0, outBytes, outOff);

            /*
             * copy ciphertext to cbcV
             */
            outBytes.DeepCopy_NoChecks(outOff, _cbcV, 0, _cbcV.Length);

            return(length);
        }
Esempio n. 27
0
 private void btnDecrypt_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         CipherMode mode = CipherMode.CBC;
         if ((bool)rbEncryptionModeCBC.IsChecked)
         {
             mode = CipherMode.CBC;
         }
         else if ((bool)rbEncryptionModeECB.IsChecked)
         {
             mode = CipherMode.ECB;
         }
         Drawing.Image decryptedImg = BlockCipher.DecryptImage(_encryptedBitmap, mode);
         SetWpfImageFromImage(decryptedImg, imgDisplay);
         btnDecrypt.IsEnabled = false;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 28
0
 private void btnEncrypt_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         CipherMode mode = CipherMode.CBC;
         if ((bool)rbEncryptionModeCBC.IsChecked)
         {
             mode = CipherMode.CBC;
         }
         else if ((bool)rbEncryptionModeECB.IsChecked)
         {
             mode = CipherMode.ECB;
         }
         _encryptedBitmap = BlockCipher.EncryptImage(_blockFilePath, mode);
         SetWpfImageFromImage(_encryptedBitmap, imgDisplay);
         btnDecrypt.IsEnabled = true;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 29
0
        protected override BlockCipher DecryptBlock(BlockCipher block)
        {
            uint uint32_1 = BitConverter.ToUInt32(block.ToBytesArray(), 0);
            uint uint32_2 = BitConverter.ToUInt32(block.ToBytesArray(), 4);
            uint ui1      = uint32_1 ^ this._pBox[17];
            uint ui2      = uint32_2 ^ (this.F(ui1) ^ this._pBox[16]);
            uint ui3      = ui1 ^ (this.F(ui2) ^ this._pBox[15]);
            uint ui4      = ui2 ^ (this.F(ui3) ^ this._pBox[14]);
            uint ui5      = ui3 ^ (this.F(ui4) ^ this._pBox[13]);
            uint ui6      = ui4 ^ (this.F(ui5) ^ this._pBox[12]);
            uint ui7      = ui5 ^ (this.F(ui6) ^ this._pBox[11]);
            uint ui8      = ui6 ^ (this.F(ui7) ^ this._pBox[10]);
            uint ui9      = ui7 ^ (this.F(ui8) ^ this._pBox[9]);
            uint ui10     = ui8 ^ (this.F(ui9) ^ this._pBox[8]);
            uint ui11     = ui9 ^ (this.F(ui10) ^ this._pBox[7]);
            uint ui12     = ui10 ^ (this.F(ui11) ^ this._pBox[6]);
            uint ui13     = ui11 ^ (this.F(ui12) ^ this._pBox[5]);
            uint ui14     = ui12 ^ (this.F(ui13) ^ this._pBox[4]);
            uint ui15     = ui13 ^ (this.F(ui14) ^ this._pBox[3]);
            uint ui16     = ui14 ^ (this.F(ui15) ^ this._pBox[2]);
            uint num      = ui15 ^ (this.F(ui16) ^ this._pBox[1]);

            return(new BlockCipher((DWord)(ui16 ^ this._pBox[0]), (DWord)num));
        }
Esempio n. 30
0
        public void TestTransform()
        {
            BlockCipher cipher1 = new BlockCipher();
            BlockCipher cipher2 = new BlockCipher();

            byte[] bytes1 = cipher1.InitializeHandshake();
            byte[] bytes2 = cipher2.InitializeHandshake();
            bytes1 = cipher2.Handshake(bytes1);
            bytes2 = cipher1.Handshake(bytes2);
            cipher1.FinalizeHandshake(bytes1);
            cipher2.FinalizeHandshake(bytes2);

            var buffer = new x2net.Buffer();

            string text = new String('x', 5300);

            Assert.Equal(5300, text.Length);

            /*
             * buffer.Write(1);
             * buffer.Write(text);
             * buffer.Shrink(1);
             */

            cipher1.Transform(buffer, (int)buffer.Length);
            cipher2.InverseTransform(buffer, (int)buffer.Length);

            buffer.Rewind();

            /*
             * string result;
             * buffer.Read(out result);
             *
             * Assert.AreEqual(text, result);
             */
        }
Esempio n. 31
0
 /// <summary>
 /// Initializes the specified cipher mode.
 /// </summary>
 /// <param name="cipher">The cipher.</param>
 internal void Init(BlockCipher cipher)
 {
     this.Cipher = cipher;
     this._blockSize = cipher.BlockSize;
     this.IV = this.IV.Take(this._blockSize).ToArray();
 }
Esempio n. 32
0
 /// <summary>
 /// Initializes the specified cipher mode.
 /// </summary>
 /// <param name="cipher">The cipher.</param>
 internal void Init(BlockCipher cipher)
 {
     Cipher = cipher;
     _blockSize = cipher.BlockSize;
     IV = IV.Take(_blockSize);
 }
Esempio n. 33
0
 public IBlockCipher GetBlockCipher(BlockCipher cipher)
 {
     return BlockCipherBuilders[cipher].Build();
 }