Ejemplo n.º 1
0
        public override void PerformTest()
        {
            BufferedBlockCipher cipher = new BufferedBlockCipher(engine);

            cipher.Init(true, param);

            byte[] outBytes = new byte[input.Length];

            int len1 = cipher.ProcessBytes(input, 0, input.Length, outBytes, 0);

            cipher.DoFinal(outBytes, len1);

            if (!AreEqual(outBytes, output))
            {
                Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes));
            }

            cipher.Init(false, param);

            int len2 = cipher.ProcessBytes(output, 0, output.Length, outBytes, 0);

            cipher.DoFinal(outBytes, len2);

            if (!AreEqual(input, outBytes))
            {
                Fail("failed reversal got " + Hex.ToHexString(outBytes));
            }
        }
Ejemplo n.º 2
0
        public override void PerformTest()
        {
            BufferedBlockCipher cipher = new BufferedBlockCipher(engine);

            cipher.Init(true, param);

            byte[] outBytes = new byte[input.Length];

            int len1 = cipher.ProcessBytes(input, 0, input.Length, outBytes, 0);

            cipher.DoFinal(outBytes, len1);

            if (!AreEqual(outBytes, output))
            {
                Fail("failed." + "\nExpected " + Hex.ToHexString(output) + "\nGot      " + Hex.ToHexString(outBytes));
            }


            //Console.WriteLine("input  : " + Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(input));

            //Console.WriteLine("output : " + Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(output));



            cipher.Init(false, param);

            int len2 = cipher.ProcessBytes(output, 0, output.Length, outBytes, 0);

            cipher.DoFinal(outBytes, len2);

            if (!AreEqual(input, outBytes))
            {
                Fail("failed reversal got " + Hex.ToHexString(outBytes));
            }
        }
Ejemplo n.º 3
0
        private byte[] DecryptBlock(
            byte[]  in_enc,
            int inOff,
            int inLen,
            byte[]  z)
        {
            byte[]        M          = null;
            KeyParameter  macKey     = null;
            KdfParameters kParam     = new KdfParameters(z, param.GetDerivationV());
            int           macKeySize = param.MacKeySize;

            kdf.Init(kParam);

            inLen -= mac.GetMacSize();

            if (cipher == null)     // stream mode
            {
                byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));

                M = new byte[inLen];

                for (int i = 0; i != inLen; i++)
                {
                    M[i] = (byte)(in_enc[inOff + i] ^ Buffer[i]);
                }

                macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8));
            }
            else
            {
                int    cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
                byte[] Buffer        = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));

                cipher.Init(false, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));

                M = cipher.DoFinal(in_enc, inOff, inLen);

                macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8));
            }

            byte[] macIV = param.GetEncodingV();

            mac.Init(macKey);
            mac.BlockUpdate(in_enc, inOff, inLen);
            mac.BlockUpdate(macIV, 0, macIV.Length);
            mac.DoFinal(macBuf, 0);

            inOff += inLen;

            for (int t = 0; t < macBuf.Length; t++)
            {
                if (macBuf[t] != in_enc[inOff + t])
                {
                    throw (new InvalidCipherTextException("IMac codes failed to equal."));
                }
            }

            return(M);
        }
Ejemplo n.º 4
0
        // Encrypt/decrypt using the given key
        public byte[] encode(byte[] data)
        {
            _wkCipher.Init(true, this.key);
            byte[] outputBytes = new byte[_wkCipher.GetOutputSize(data.Length)];
            int    length      = _wkCipher.ProcessBytes(data, outputBytes, 0);

            _wkCipher.DoFinal(outputBytes, length); //Do the final block
            return(outputBytes);
        }
Ejemplo n.º 5
0
        private byte[] DecryptBlock(byte[] inEnc, int inOff, int inLen, byte[] z)
        {
            byte[]       m;
            KeyParameter macKey;
            var          kParam     = new KdfParameters(z, _param.Derivation);
            var          macKeySize = _param.MacKeySize;

            _kdf.Init(kParam);

            inLen -= _mac.GetMacSize();

            if (_cipher == null)     // stream mode
            {
                var buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));

                m = new byte[inLen];

                for (var i = 0; i != inLen; i++)
                {
                    m[i] = (byte)(inEnc[inOff + i] ^ buffer[i]);
                }

                macKey = new KeyParameter(buffer, inLen, (macKeySize / 8));
            }
            else
            {
                var cipherKeySize = ((IesWithCipherParameters)_param).CipherKeySize;
                var buffer        = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));

                _cipher.Init(false, new KeyParameter(buffer, 0, (cipherKeySize / 8)));

                m = _cipher.DoFinal(inEnc, inOff, inLen);

                macKey = new KeyParameter(buffer, (cipherKeySize / 8), (macKeySize / 8));
            }

            var macIV = _param.Encoding;

            _mac.Init(macKey);
            _mac.BlockUpdate(inEnc, inOff, inLen);
            _mac.BlockUpdate(macIV, 0, macIV.Length);
            _mac.DoFinal(_macBuf, 0);

            inOff += inLen;

            for (var t = 0; t < _macBuf.Length; t++)
            {
                if (_macBuf[t] != inEnc[inOff + t])
                {
                    throw (new InvalidCipherTextException("IMac codes failed to equal."));
                }
            }

            return(m);
        }
Ejemplo n.º 6
0
        private byte[] EncryptBlock(byte[] input, int inOff, int inLen, byte[] macData)
        {
            // Block cipher mode.
            byte[] k1 = new byte[((IesWithCipherParameters)_iesParameters).CipherKeySize / 8];
            byte[] k2 = new byte[_iesParameters.MacKeySize / 8];
            byte[] k  = _kdfKey;

            Array.Copy(k, 0, k1, 0, k1.Length);
            Array.Copy(k, k1.Length, k2, 0, k2.Length);

            _cipher.Init(true, new ParametersWithIV(new KeyParameter(k1), _iv));

            byte[] c   = new byte[_cipher.GetOutputSize(inLen)];
            int    len = _cipher.ProcessBytes(input, inOff, inLen, c, 0);

            len += _cipher.DoFinal(c, len);

            // Convert the length of the encoding vector into a byte array.
            byte[] p2 = _iesParameters.GetEncodingV();

            // Apply the MAC.
            byte[] T = new byte[_mac.GetMacSize()];

            byte[] k2A = new byte[_hash.GetDigestSize()];
            _hash.Reset();
            _hash.BlockUpdate(k2, 0, k2.Length);
            _hash.DoFinal(k2A, 0);

            _mac.Init(new KeyParameter(k2A));
            _mac.BlockUpdate(_iv, 0, _iv.Length);
            _mac.BlockUpdate(c, 0, c.Length);
            if (p2 != null)
            {
                _mac.BlockUpdate(p2, 0, p2.Length);
            }

            if (macData != null)
            {
                _mac.BlockUpdate(macData, 0, macData.Length);
            }

            _mac.DoFinal(T, 0);

            // Output the double (C,T).
            byte[] output = new byte[len + T.Length];
            Array.Copy(c, 0, output, 0, len);
            Array.Copy(T, 0, output, len, T.Length);
            return(output);
        }
Ejemplo n.º 7
0
        private static MemoryStream DecryptAes(Stream inputStream, BufferedBlockCipher cipher, long length)
        {
            byte[] input  = new byte[length];
            byte[] output = new byte[cipher.GetOutputSize((int)length)];
            // TODO: Check that all input streams are correctly aligned with the block size.
            ////int blockSize = cipher.GetBlockSize();
            ////long inputLength = inputStream.Length;
            ////if (inputLength % blockSize > 0)
            ////{
            ////    inputLength += blockSize - inputLength % blockSize;
            ////}

            ////byte[] input = new byte[inputLength];
            ////byte[] output = new byte[cipher.GetOutputSize((int)inputLength)];

            inputStream.Read(input, 0, (int)length);

            int len = cipher.ProcessBytes(input, 0, input.Length, output, 0);

            cipher.DoFinal(output, len);

            MemoryStream outputStream = new MemoryStream();

            outputStream.Write(output, 0, input.Length);
            outputStream.Seek(0, SeekOrigin.Begin);
            return(outputStream);
        }
Ejemplo n.º 8
0
        public Packet ChannelDecrypt(ICipherSetRemoteInfo channelInfo, Packet outer)
        {
            // We gotta have the primary components and something to decrypt
            if (outer.Body.Length < 25)
            {
                return(null);
            }

            var ci = (CS1ARemoteInfo)channelInfo;

            // Rip apart our packet
            byte[] token         = outer.Body.Take(16).ToArray();
            byte[] iv            = outer.Body.Skip(16).Take(4).ToArray();
            byte[] encryptedData = outer.Body.Skip(20).Take(outer.Body.Length - 24).ToArray();
            byte[] dataMac       = outer.Body.Skip(outer.Body.Length - 4).Take(4).ToArray();

            // Make sure we're on the right channel
            if (!token.SequenceEqual(ci.Token))
            {
                return(null);
            }

            // Validate us some hmac
            byte[] hmacKey = new byte[20];
            Buffer.BlockCopy(ci.DecryptionKey, 0, hmacKey, 0, 16);
            Buffer.BlockCopy(iv, 0, hmacKey, 16, 4);

            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(hmacKey));
            hmac.BlockUpdate(encryptedData, 0, encryptedData.Length);
            byte[] mac = new byte[hmac.GetMacSize()];
            hmac.DoFinal(mac, 0);
            var foldedMac = Helpers.Fold(mac, 3);

            if (!foldedMac.SequenceEqual(dataMac))
            {
                // Get out of here with your bad data
                return(null);
            }

            // Everything seems ok.  Get it decrypted
            byte[] aesIV = new byte[16];
            Buffer.BlockCopy(iv, 0, aesIV, 0, 4);
            Array.Clear(aesIV, 4, 12);

            var cipher     = new SicBlockCipher(new AesFastEngine());
            var parameters = new ParametersWithIV(new KeyParameter(ci.DecryptionKey), aesIV);

            cipher.Init(false, parameters);

            var decryptedData = new byte[encryptedData.Length];
            BufferedBlockCipher bufferCipher = new BufferedBlockCipher(cipher);
            var offset = bufferCipher.ProcessBytes(encryptedData, decryptedData, 0);

            bufferCipher.DoFinal(decryptedData, offset);

            // Build a packet and ship it off
            return(Packet.DecodePacket(decryptedData));
        }
Ejemplo n.º 9
0
        public Packet MessageDecrypt(Packet outer)
        {
            byte[] remoteKeyData      = outer.Body.Take(21).ToArray();
            byte[] ivData             = outer.Body.Skip(21).Take(4).ToArray();
            byte[] innerEncryptedData = outer.Body.Skip(25).Take(outer.Body.Length - 29).ToArray();

            // Decode the body
            ECKeyPair remoteEphemeralKeys = ECKeyPair.LoadKeys(SecNamedCurves.GetByName("secp160r1"), remoteKeyData, null);

            var idAgreement = ECDHAgree(remoteEphemeralKeys.PublicKey, Key.PrivateKey);
            var agreedHash  = Helpers.SHA256Hash(Helpers.ToByteArray(idAgreement, 20));
            var aesKey      = Helpers.FoldOnce(agreedHash);

            // Pad out the IV
            byte[] aesIV = new byte[16];
            Array.Clear(aesIV, 0, 16);
            Buffer.BlockCopy(ivData, 0, aesIV, 0, 4);

            // Decrypt it
            var cipher     = new BufferedBlockCipher(new SicBlockCipher(new AesFastEngine()));
            var parameters = new ParametersWithIV(new KeyParameter(aesKey), aesIV);

            cipher.Init(false, parameters);
            byte[] decryptedBody = new byte[innerEncryptedData.Length];
            var    offset        = cipher.ProcessBytes(innerEncryptedData, decryptedBody, 0);

            cipher.DoFinal(decryptedBody, offset);

            Packet outPacket = Packet.DecodePacket(decryptedBody);

            return(outPacket);
        }
Ejemplo n.º 10
0
        public byte[] DecryptSessionKey()
        {
            //odkodowanie z pliku(klucz = skrot hasla)
            BufferedBlockCipher aes = new BufferedBlockCipher(new RC6Engine());

            aes.Init(true, new KeyParameter(PasswordHash));


            var privateKeyEncrypted = File.ReadAllBytes(@"C:\Users\ruchn\OneDrive\Obrazy\Private\" + Username + ".txt");
            var privateKey          = new byte[aes.GetOutputSize(privateKeyEncrypted.Length)];

            var length = aes.ProcessBytes(privateKeyEncrypted, 0, privateKeyEncrypted.Length, privateKey, 0);

            aes.DoFinal(privateKey, length);


            var privateKeyToString = Encoding.UTF8.GetString(privateKey);

            //odkodowanie klucza sesyjnego kluczem prywatnym
            using (var rsa = new RSACryptoServiceProvider(2048))
            {
                rsa.PersistKeyInCsp = false;
                try
                {
                    rsa.FromXmlString(privateKeyToString);
                    return(rsa.Decrypt(EncodedKey, false));
                }
                catch (Exception)
                {
                    IsPasswordValid = false;
                    return(PasswordHash.Take(KeySize / 8).ToArray());
                }
            }
        }
Ejemplo n.º 11
0
        private static MemoryStream DecryptAes(Stream inputStream, BufferedBlockCipher cipher, long length)
        {
            int blockSize    = cipher.GetBlockSize();
            int inputLength  = (int)length;
            int paddedLength = inputLength;

            if (paddedLength % blockSize > 0)
            {
                paddedLength += blockSize - paddedLength % blockSize;
            }

            byte[] input  = new byte[paddedLength];
            byte[] output = new byte[cipher.GetOutputSize(paddedLength)];

            inputStream.Read(input, 0, inputLength);
            int len = cipher.ProcessBytes(input, 0, input.Length, output, 0);

            cipher.DoFinal(output, len);

            MemoryStream outputStream = new MemoryStream();

            outputStream.Write(output, 0, inputLength);
            outputStream.Seek(0, SeekOrigin.Begin);
            return(outputStream);
        }
Ejemplo n.º 12
0
        public static byte[] AESDecrypt(byte[] Key, byte[] IV, byte[] cipherText)
        {
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            BufferedBlockCipher decryptCipher = new BufferedBlockCipher(new CbcBlockCipher(new AesEngine()));

            decryptCipher.Reset();
            ICipherParameters param = new ParametersWithIV(new KeyParameter(Key), IV);

            decryptCipher.Init(false, param);
            byte[] buf = new byte[decryptCipher.GetOutputSize(cipherText.Length)];
            int    len = decryptCipher.ProcessBytes(cipherText, 0, cipherText.Length, buf, 0);

            len += decryptCipher.DoFinal(buf, len);
            byte[] plainText = new byte[len];
            Array.Copy(buf, 0, plainText, 0, len);

            return(plainText);
        }
Ejemplo n.º 13
0
        private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, byte[] key, byte[] iv)
        {
            mode.Init(forEncrypt, new ParametersWithIV(new KeyParameter(key), iv));

            BufferedBlockCipher cipher = new BufferedBlockCipher(mode);

            return(cipher.DoFinal(input));
        }
Ejemplo n.º 14
0
        private byte[] Decrypt(BufferedBlockCipher cipher, int byteCount)
        {
            var encrypted = ReadBytes(byteCount);
            var clear     = new byte[byteCount];
            var l1        = cipher.ProcessBytes(encrypted, 0, encrypted.Length, clear, 0);

            cipher.DoFinal(clear, l1);
            return(clear);
        }
Ejemplo n.º 15
0
    private byte[] DecryptBlock(byte[] in_enc, int inOff, int inLen, byte[] z)
    {
        byte[]        array         = null;
        KeyParameter  keyParameter  = null;
        KdfParameters kdfParameters = new KdfParameters(z, param.GetDerivationV());
        int           macKeySize    = param.MacKeySize;

        kdf.Init(kdfParameters);
        if (inLen < mac.GetMacSize())
        {
            throw new InvalidCipherTextException("Length of input must be greater than the MAC");
        }
        inLen -= mac.GetMacSize();
        if (cipher == null)
        {
            byte[] array2 = GenerateKdfBytes(kdfParameters, inLen + macKeySize / 8);
            array = new byte[inLen];
            for (int i = 0; i != inLen; i++)
            {
                array[i] = (byte)(in_enc[inOff + i] ^ array2[i]);
            }
            keyParameter = new KeyParameter(array2, inLen, macKeySize / 8);
        }
        else
        {
            int    cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
            byte[] key           = GenerateKdfBytes(kdfParameters, cipherKeySize / 8 + macKeySize / 8);
            cipher.Init(forEncryption: false, new KeyParameter(key, 0, cipherKeySize / 8));
            array        = cipher.DoFinal(in_enc, inOff, inLen);
            keyParameter = new KeyParameter(key, cipherKeySize / 8, macKeySize / 8);
        }
        byte[] encodingV = param.GetEncodingV();
        mac.Init(keyParameter);
        mac.BlockUpdate(in_enc, inOff, inLen);
        mac.BlockUpdate(encodingV, 0, encodingV.Length);
        mac.DoFinal(macBuf, 0);
        inOff += inLen;
        byte[] a = Arrays.CopyOfRange(in_enc, inOff, inOff + macBuf.Length);
        if (!Arrays.ConstantTimeAreEqual(a, macBuf))
        {
            throw new InvalidCipherTextException("Invalid MAC.");
        }
        return(array);
    }
Ejemplo n.º 16
0
 private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, byte[] key, byte[] iv)
 {
     try
     {
         this.mode.Init(forEncrypt, new ParametersWithIV(new KeyParameter(key), iv));
         BufferedBlockCipher cipher = new BufferedBlockCipher(this.mode);
         return(cipher.DoFinal(input));
     } catch (CryptoException)
     {
         throw;
     }
 }
Ejemplo n.º 17
0
        /// <summary>
        /// De/encrypt data via AES128-CBC without applying standarized
        /// padding (SmartGlass uses out-of-spec padding technique).
        /// </summary>
        /// <returns>The transformed data without padding.</returns>
        /// <param name="data">Data to transform.</param>
        /// <param name="initVector">Init vector.</param>
        /// <param name="encrypt">If set to <c>true</c> data is encrypted, <c>false</c> decrypts.</param>
        private byte[] UseAesCipherWithoutPadding(byte[] data, byte[] initVector, bool encrypt)
        {
            var aesCipher   = new AesEngine();
            var blockCipher = new CbcBlockCipher(aesCipher);
            var cipher      = new BufferedBlockCipher(blockCipher);

            var keyParams    = new KeyParameter(_cryptoKey);
            var paramsWithIv = new ParametersWithIV(keyParams, initVector);

            cipher.Init(encrypt, paramsWithIv);

            return(cipher.DoFinal(data));
        }
Ejemplo n.º 18
0
        public byte[] DecryptDES3(byte[] message, byte[] key)
        {
            DesEdeEngine        desedeEngine   = new DesEdeEngine();
            BufferedBlockCipher bufferedCipher = new BufferedBlockCipher(desedeEngine);

            // Create the KeyParameter for the DES3 key generated.
            KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DESEDE", key);

            byte[] output = new byte[bufferedCipher.GetOutputSize(message.Length)];
            bufferedCipher.Init(false, keyparam);
            output = bufferedCipher.DoFinal(message);
            return(output);
        }
Ejemplo n.º 19
0
        public byte[] Decrypt(byte[] key, byte[] iv, byte[] data)
        {
            //BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine, new ISO7816d4Padding());
            BufferedBlockCipher cipher = new BufferedBlockCipher(engine);

            //cipher.Init(false, new ParametersWithIV(new DesParameters(key), iv));
            cipher.Init(false, new DesEdeParameters(key));
            byte[] rv  = new byte[cipher.GetOutputSize(data.Length)];
            int    tam = cipher.ProcessBytes(data, 0, data.Length, rv, 0);

            cipher.DoFinal(rv, tam);

            return(rv);
        }
Ejemplo n.º 20
0
        public Packet ChannelEncrypt(ICipherSetRemoteInfo channelInfo, Packet inner)
        {
            var ci = (CS1ARemoteInfo)channelInfo;

            // TODO:  Validate we don't care about endianess of IV here

            // Setup and encrypt the actual data
            byte[] aesIV = new byte[16];
            Buffer.BlockCopy(BitConverter.GetBytes(ci.IV), 0, aesIV, 0, 4);
            Array.Clear(aesIV, 4, 12);

            var cipher     = new SicBlockCipher(new AesFastEngine());
            var parameters = new ParametersWithIV(new KeyParameter(ci.EncryptionKey), aesIV);

            cipher.Init(true, parameters);

            var encryptedInner = new byte[inner.FullPacket.Length];
            BufferedBlockCipher bufferCipher = new BufferedBlockCipher(cipher);
            var offset = bufferCipher.ProcessBytes(inner.FullPacket, encryptedInner, 0);

            bufferCipher.DoFinal(encryptedInner, offset);

            // Hmac the output
            byte[] hmacKey = new byte[20];
            Buffer.BlockCopy(ci.EncryptionKey, 0, hmacKey, 0, 16);
            Buffer.BlockCopy(BitConverter.GetBytes(ci.IV), 0, hmacKey, 16, 4);

            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(hmacKey));
            hmac.BlockUpdate(encryptedInner, 0, encryptedInner.Length);
            byte[] mac = new byte[hmac.GetMacSize()];
            hmac.DoFinal(mac, 0);
            var foldedMac = Helpers.Fold(mac, 3);

            // Create the outgoing packet
            Packet outPacket = new Packet();

            outPacket.Body = new byte[encryptedInner.Length + 24];
            Buffer.BlockCopy(ci.Token, 0, outPacket.Body, 0, 16);
            Buffer.BlockCopy(BitConverter.GetBytes(ci.IV), 0, outPacket.Body, 16, 4);
            Buffer.BlockCopy(encryptedInner, 0, outPacket.Body, 20, encryptedInner.Length);
            Buffer.BlockCopy(foldedMac, 0, outPacket.Body, outPacket.Body.Length - 4, 4);

            // Next IV next packet
            ++ci.IV;

            return(outPacket);
        }
Ejemplo n.º 21
0
        } //private byte[] encryptDesEde(byte[] plain)

        private byte[] encryptAES(byte[] plain, KeyChaining chaining = KeyChaining.CBC, bool doEncrypt = true, byte[] icv = null)
        {
            BufferedBlockCipher cipher = chaining == KeyChaining.CBC
                ? new BufferedBlockCipher(new CbcBlockCipher(new AesEngine()))   //CBC chaining
                : new BufferedBlockCipher(new AesEngine());                      //ECB chaining

            if (icv != null)
            {
                cipher.Init(doEncrypt, new ParametersWithIV(new KeyParameter(theKey), icv));
            }
            else
            {
                cipher.Init(doEncrypt, new KeyParameter(theKey));
            }

            MemoryStream dst = new MemoryStream();

            byte[] bin    = padded(plain, 24);
            byte[] result = new byte[bin.Length];

            int outL = cipher.ProcessBytes(bin, result, 0);

            if (outL > 0)
            {
                dst.Write(result, 0, outL);
            }

            if (outL < plain.Length)
            {
                outL = cipher.DoFinal(result, 0);
                if (outL > 0)
                {
                    dst.Write(result, 0, outL);
                }
            } //if (outL < plain.Length)

            dst.Position = 0;
            result       = dst.ToArray();
            dst.Close();

            if (result.Length > plain.Length)
            {
                byte[] res = new byte[plain.Length];
                System.Array.Copy(result, res, plain.Length);
                return(res);
            } //if (result.Length > plain.Length)

            return(result);
        } //private byte[] encryptAES(byte[] plain)
Ejemplo n.º 22
0
        public int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
        {
            if (output.Length - outOff < len + macSize)
            {
                throw new ArgumentException("output buffer is too short");
            }

            lambda_c = len * 8;

            //use alternative CTR cipher to produce output
            int outOff_;
            int resultLen;

            if (forEncryption)
            {
                outOff_   = outOff;
                resultLen = ctrCipher.ProcessBytes(input, inOff, len, output, outOff);

                ctrCipher.DoFinal(output, resultLen);

                CalculateMac(output, outOff_, len);
            }
            else
            {
                int inOff_ = inOff;

                CalculateMac(input, inOff_, len);

                resultLen = ctrCipher.ProcessBytes(input, inOff, len, output, outOff);
                ctrCipher.DoFinal(output, resultLen);
            }



            return(resultLen);
        }
Ejemplo n.º 23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] ComputeCbc3Des(this byte[] data, KeyParameter key)
        {
            IBlockCipher engine = new DesEdeEngine();
            var          cipher = new BufferedBlockCipher(new CbcBlockCipher(engine));

            cipher.Init(true, key);

            var cbc = new byte[cipher.GetOutputSize(data.Length)];

            var length = cipher.ProcessBytes(data, 0, data.Length, cbc, 0);

            cipher.DoFinal(cbc, length);

            return(cbc);
        }
Ejemplo n.º 24
0
        public override void PerformTest()
        {
            BufferedBlockCipher cipher = new BufferedBlockCipher(engine);

            cipher.Init(true, param);

            byte[] outBytes = new byte[input.Length];

            Array.Copy(input, 0, outBytes, 0, outBytes.Length);

            for (int i = 0; i != iterations; i++)
            {
                int len1 = cipher.ProcessBytes(outBytes, 0, outBytes.Length, outBytes, 0);

                cipher.DoFinal(outBytes, len1);
            }

            if (!AreEqual(outBytes, output))
            {
                Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes));
            }

            cipher.Init(false, param);

            for (int i = 0; i != iterations; i++)
            {
                int len1 = cipher.ProcessBytes(outBytes, 0, outBytes.Length, outBytes, 0);

                cipher.DoFinal(outBytes, len1);
            }

            if (!AreEqual(input, outBytes))
            {
                Fail("failed reversal");
            }
        }
Ejemplo n.º 25
0
        private Byte[] Decrypt(BufferedBlockCipher cipher, Byte[] data)
        {
            var size      = cipher.GetOutputSize(data.Length);
            var outBuffer = new Byte[size];

            //int off1 = cipher.ProcessBytes(content, 0, content.Length, outBuffer, 0);
            cipher.DoFinal(data, 0, data.Length, outBuffer, 0);
            //int off2 = cipher.DoFinal(outBuffer, off1);
            //int resultSize = off1 + off2;
            var result = new Byte[outBuffer.Length /*resultSize*/];

            Array.Copy(outBuffer, 0, result, 0, result.Length);

            //String asString = Encoding.ASCII.GetString(result);
            //Console.WriteLine(asString);

            return(result);
        }
        public byte[] Decrypt(byte[] value)
        {
            BufferedBlockCipher aes    = new BufferedBlockCipher(new OfbBlockCipher(new AesEngine(), AesBlockSizeInBytes * 8));
            ArraySegment <byte> iv     = new ArraySegment <byte>(value, 0, AesBlockSizeInBytes);
            ArraySegment <byte> secret = new ArraySegment <byte>(value, AesBlockSizeInBytes, value.Length - AesBlockSizeInBytes);

            ParametersWithIV ivAndKey = new ParametersWithIV(new KeyParameter(aesKey), iv.ToArray());

            aes.Init(false, ivAndKey);

            int maximumSize = aes.GetOutputSize(secret.Count);

            byte[] outputBuffer = new byte[maximumSize];
            int    length1      = aes.ProcessBytes(secret.ToArray(), 0, secret.Count, outputBuffer, 0);
            int    length2      = aes.DoFinal(outputBuffer, length1);

            return(new ArraySegment <byte>(outputBuffer, 0, length1 + length2).ToArray());
        }
Ejemplo n.º 27
0
        /*
         * No idea... doesnt work.. cant seem to fix it..
         *
         *
         */
        private static byte[] Transform(BufferedBlockCipher cipher, byte[] data)
        {
            var buf    = new byte[cipher.GetOutputSize(data.Length)];
            var length = cipher.ProcessBytes(data, 0, data.Length, buf, 0);

            try
            {
                length += cipher.DoFinal(buf, length);
            }
            catch (InvalidCipherTextException)
            {
                return(null);
            }
            var final = new byte[length];

            Array.Copy(buf, final, length);
            return(final);
        }
Ejemplo n.º 28
0
        public static byte[] Encrypt(string key, byte[] inBytes)
        {
            var cipher = new BufferedBlockCipher(new BlowfishEngine());

            cipher.Init(true, new KeyParameter(Encoding.UTF8.GetBytes(key)));

            inBytes = BSwap(inBytes);

            var outBytes = new byte[cipher.GetOutputSize(inBytes.Length)];

            var len2 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);

            cipher.DoFinal(outBytes, len2);

            outBytes = BSwap(outBytes);

            return(outBytes);
        }
Ejemplo n.º 29
0
        public byte[] Encrypt(byte[] key, byte[] iv, byte[] data)
        {
            //BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine, new ISO7816d4Padding());
            //BufferedBlockCipher cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new ISO7816d4Padding());
            BufferedBlockCipher cipher = new BufferedBlockCipher(engine);

            //cipher.Init(true, new ParametersWithIV(new DesParameters(key), iv));
            cipher.Init(true, new DesEdeParameters(key));
            byte[] rv  = new byte[cipher.GetOutputSize(data.Length)];
            int    tam = cipher.ProcessBytes(data, 0, data.Length, rv, 0);

            cipher.DoFinal(rv, tam);

            //BufferedBlockCipher bufferedCipher = new BufferedBlockCipher(desedeEngine);

            // Create the KeyParameter for the DES3 key generated.   KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DESEDE", keyDES3);  byte[] output = new byte[bufferedCipher.GetOutputSize(message.Length)];  bufferedCipher.Init(true, keyparam);  output = bufferedCipher.DoFinal(message);

            return(rv);
        }
        //this method is used to replace _NewEncryptor method.
        public byte[] EncryptData(byte[] data, int offset, int length, byte[] key, byte[] iv)
        {
            try
            {
                var desEngine           = new DesEngine();
                var cbcBlockCipher      = new CbcBlockCipher(desEngine);
                var bufferedBlockCipher = new BufferedBlockCipher(cbcBlockCipher);

                bufferedBlockCipher.Init(true, new ParametersWithIV(new KeyParameter(key), iv));

                var cipherData = new byte[bufferedBlockCipher.GetOutputSize(length - offset)];

                var outputLength = bufferedBlockCipher.ProcessBytes(data, offset, length, cipherData, 0);

                bufferedBlockCipher.DoFinal(cipherData, outputLength);

                return(cipherData);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Ejemplo n.º 31
0
		public override void PerformTest()
		{
			base.PerformTest();

			//advanced tests with Gost28147KeyGenerator:
			//encrypt on hesh message; ECB mode:
			byte[] inBytes = Hex.Decode("4e6f77206973207468652074696d6520666f7220616c6c20");
			byte[] output = Hex.Decode("8ad3c8f56b27ff1fbd46409359bdc796bc350e71aac5f5c0");
			byte[] outBytes = new byte[inBytes.Length];

			byte[] key = generateKey(Hex.Decode("0123456789abcdef"));  //!!! heshing start_key - get 256 bits !!!
	//        System.out.println(new string(Hex.Encode(key)));
			ICipherParameters  param = new ParametersWithSBox(new KeyParameter(key), Gost28147Engine.GetSBox("E-A"));
			//CipherParameters  param = new Gost28147Parameters(key,"D-Test");
			BufferedBlockCipher cipher = new BufferedBlockCipher(new Gost28147Engine());

			cipher.Init(true, param);
			int len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);
			try
			{
				cipher.DoFinal(outBytes, len1);
			}
			catch (CryptoException e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			if (outBytes.Length != output.Length)
			{
				Fail("failed - "
					+ "expected " + Hex.ToHexString(output) + " got "
					+ Hex.ToHexString(outBytes));
			}

			for (int i = 0; i != outBytes.Length; i++)
			{
				if (outBytes[i] != output[i])
				{
					Fail("failed - "
						+ "expected " + Hex.ToHexString(output)
						+ " got " + Hex.ToHexString(outBytes));
				}
			}


			//encrypt on hesh message; CFB mode:
			inBytes = Hex.Decode("bc350e71aac5f5c2");
			output = Hex.Decode("0ebbbafcf38f14a5");
			outBytes = new byte[inBytes.Length];

			key = generateKey(Hex.Decode("0123456789abcdef"));  //!!! heshing start_key - get 256 bits !!!
			param = new ParametersWithIV(
				new ParametersWithSBox(
					new KeyParameter(key), //key
					Gost28147Engine.GetSBox("E-A")), //type S-box
				Hex.Decode("1234567890abcdef")); //IV

			cipher = new BufferedBlockCipher(new CfbBlockCipher(new Gost28147Engine(), 64));

			cipher.Init(true, param);
			len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);
			try
			{
				cipher.DoFinal(outBytes, len1);
			}
			catch (CryptoException e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}
			if (outBytes.Length != output.Length)
			{
				Fail("failed - "
					+ "expected " + Hex.ToHexString(output)
					+ " got " + Hex.ToHexString(outBytes));
			}
			for (int i = 0; i != outBytes.Length; i++)
			{
				if (outBytes[i] != output[i])
				{
					Fail("failed - "
						+ "expected " + Hex.ToHexString(output)
						+ " got " + Hex.ToHexString(outBytes));
				}
			}


			//encrypt on hesh message; CFB mode:
			inBytes = Hex.Decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f");
			output = Hex.Decode("64988982819f0a1655e226e19ecad79d10cc73bac95c5d7da034786c12294225");
			outBytes = new byte[inBytes.Length];

			key = generateKey(Hex.Decode("aafd12f659cae63489b479e5076ddec2f06cb58faafd12f659cae63489b479e5"));  //!!! heshing start_key - get 256 bits !!!
			param = new ParametersWithIV(
				new ParametersWithSBox(
					new KeyParameter(key), //key
					Gost28147Engine.GetSBox("E-A")), //type S-box
				Hex.Decode("aafd12f659cae634")); //IV

			cipher = new BufferedBlockCipher(new CfbBlockCipher(new Gost28147Engine(), 64));

			cipher.Init(true, param);
			len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);

			cipher.DoFinal(outBytes, len1);

			if (outBytes.Length != output.Length)
			{
				Fail("failed - "
					+ "expected " + Hex.ToHexString(output)
					+ " got " + Hex.ToHexString(outBytes));
			}

			for (int i = 0; i != outBytes.Length; i++)
			{
				if (outBytes[i] != output[i])
				{
					Fail("failed - "
						+ "expected " + Hex.ToHexString(output)
						+ " got " + Hex.ToHexString(outBytes));
				}
			}

			//encrypt on hesh message; OFB mode:
			inBytes = Hex.Decode("bc350e71aa11345709acde");
			output = Hex.Decode("1bcc2282707c676fb656dc");
			outBytes = new byte[inBytes.Length];

			key = generateKey(Hex.Decode("0123456789abcdef"));  //!!! heshing start_key - get 256 bits !!!
			param = new ParametersWithIV(
				new ParametersWithSBox(
					new KeyParameter(key), //key
					Gost28147Engine.GetSBox("E-A")), //type S-box
				Hex.Decode("1234567890abcdef")); //IV

			cipher = new BufferedBlockCipher(new GOfbBlockCipher(new Gost28147Engine()));

			cipher.Init(true, param);
			len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0);

			cipher.DoFinal(outBytes, len1);

			if (outBytes.Length != output.Length)
			{
				Fail("failed - "
					+ "expected " + Hex.ToHexString(output)
					+ " got " + Hex.ToHexString(outBytes));
			}

			for (int i = 0; i != outBytes.Length; i++)
			{
				if (outBytes[i] != output[i])
				{
					Fail("failed - "
						+ "expected " + Hex.ToHexString(output)
						+ " got " + Hex.ToHexString(outBytes));
				}
			}
		}