Пример #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));
            }
        }
Пример #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));
            }
        }
Пример #3
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);
        }
Пример #4
0
        /// <summary>
        /// Decrypt stream with Blowfish-CBC
        /// </summary>
        /// <param name="input">Input stream to decrypt</param>
        /// <param name="output">Output stream</param>
        /// <param name="key">Key</param>
        /// <param name="iv">IV</param>
        /// <param name="paddingStyle">Padding</param>
        /// <param name="notifyProgression">Notify progression method</param>
        /// <param name="bufferSize">Buffer size</param>
        public static void DecryptCBC(Stream input, Stream output, byte[] key, byte[] iv, PaddingStyle paddingStyle = PaddingStyle.Pkcs7, Action <int> notifyProgression = null, int bufferSize = 4096)
        {
            IBufferedCipher  cipher     = new BufferedBlockCipher(new CbcBlockCipher(new BlowfishEngine()));
            ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key, 0, key.Length), iv, 0, iv.Length);

            cipher.Init(false, parameters);

            byte[] backup = null;
            int    bytesRead;

            byte[] buffer = new byte[bufferSize];
            byte[] dec    = new byte[bufferSize];

            do
            {
                bytesRead = input.Read(buffer, 0, bufferSize);

                if (bytesRead > 0)
                {
                    if (backup != null)
                    {
                        output.Write(backup, 0, backup.Length);
                        backup = null;
                    }

                    if (bytesRead == bufferSize)
                    {
                        cipher.ProcessBytes(buffer, dec, 0);
                        backup = new byte[bytesRead];
                        Array.Copy(dec, 0, backup, 0, bytesRead);
                    }
                    else
                    {
                        dec = new byte[bytesRead];
                        byte[] smallBuffer = new byte[bytesRead];
                        Array.Copy(buffer, 0, smallBuffer, 0, bytesRead);
                        cipher.ProcessBytes(smallBuffer, dec, 0);
                        byte[] unpadData = Padding.Unpad(dec, BLOCK_SIZE, paddingStyle);
                        output.Write(unpadData, 0, unpadData.Length);
                    }

                    if (notifyProgression != null)
                    {
                        notifyProgression(bytesRead);
                    }
                }
                else
                {
                    if (backup != null)
                    {
                        byte[] unpadData = Padding.Unpad(backup, BLOCK_SIZE, paddingStyle);
                        output.Write(unpadData, 0, unpadData.Length);
                    }
                }
            } while (bytesRead == bufferSize);
        }
Пример #5
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);
        }
Пример #6
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);
        }
Пример #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);
        }
Пример #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));
        }
Пример #9
0
        /// <summary>
        /// Fills each block with pseudorandom data and appends it to the result.
        /// Data used for the transformation is the counter changed into a byte array.
        /// </summary>
        protected virtual byte[] GenerateBlocks(int numberOfBlocks)
        {
            if (!state.Seeded)
            {
                throw new GeneratorSeedException("Generator not seeded");
            }

            var result          = new byte[numberOfBlocks * CipherBlockSize];
            int destArrayLength = 0;

            var encryptor = new BufferedBlockCipher(cipher);

            encryptor.Init(true, new KeyParameter(state.Key));

            for (int i = 0; i < numberOfBlocks; i++)
            {
                var plainText = state.TransformCounterToByteArray();
                encryptor.ProcessBytes(plainText, 0, plainText.Length, result, destArrayLength);

                destArrayLength += plainText.Length;
                state.Counter++;
            }

            encryptor.Reset();

            return(result);
        }
Пример #10
0
        public static string GenEncrypedPin(string pin, string pinToken, string sessionId, RsaPrivateCrtKeyParameters rsa, ulong it)
        {
            ulong time = (ulong)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            var bPinToken = Convert.FromBase64String(pinToken);


            IAsymmetricBlockCipher cipherRsa = new RsaBlindedEngine();

            cipherRsa = new OaepEncoding(cipherRsa, new Sha256Digest(), new Sha256Digest(), Encoding.ASCII.GetBytes(sessionId));
            BufferedAsymmetricBlockCipher cipher = new BufferedAsymmetricBlockCipher(cipherRsa);

            cipher.Init(false, rsa);
            cipher.ProcessBytes(bPinToken, 0, bPinToken.Length);
            var key = cipher.DoFinal();


            var bPin      = Encoding.ASCII.GetBytes(pin);
            var btime     = BitConverter.GetBytes(time);
            var biterator = BitConverter.GetBytes(it);


            int len = bPin.Length + btime.Length + biterator.Length;

            IBlockCipher cipherAes    = new AesEngine();
            int          bsize        = cipherAes.GetBlockSize();
            KeyParameter keyParameter = new KeyParameter(key);


            int nPadding = bsize - len % bsize;
            var bPadding = new byte[nPadding];

            len += (len % bsize == 0 ? 0 : nPadding);


            var blocks = new byte[len];

            Array.Copy(bPin, blocks, bPin.Length);
            Array.Copy(btime, 0, blocks, bPin.Length, btime.Length);
            Array.Copy(biterator, 0, blocks, bPin.Length + btime.Length, biterator.Length);
            Array.Copy(bPadding, 0, blocks, bPin.Length + btime.Length + biterator.Length, nPadding);

            var iv = new byte[bsize];

            random.NextBytes(iv);

            CbcBlockCipher   cbcBc            = new CbcBlockCipher(cipherAes);
            ParametersWithIV parametersWithIV = new ParametersWithIV(keyParameter, iv);

            BufferedBlockCipher bc = new BufferedBlockCipher(cbcBc);

            bc.Init(true, parametersWithIV);
            var bOut = bc.ProcessBytes(blocks);
            var rz   = new byte[bOut.Length + bsize];

            Array.Copy(iv, rz, iv.Length);
            Array.Copy(bOut, 0, rz, iv.Length, bOut.Length);

            return(Convert.ToBase64String(rz));
        }
Пример #11
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());
                }
            }
        }
Пример #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);
        }
Пример #13
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);
        }
Пример #14
0
        private byte[] EncryptBlock(
            byte[]  input,
            int inOff,
            int inLen,
            byte[]  z)
        //throws InvalidCipherTextException
        {
            byte[]        C             = null;
            KeyParameter  macKey        = null;
            KdfParameters kParam        = new KdfParameters(z, param.GetDerivationV());
            int           c_text_length = 0;
            int           macKeySize    = param.MacKeySize;

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

                C             = new byte[inLen + mac.GetMacSize()];
                c_text_length = inLen;

                for (int i = 0; i != inLen; i++)
                {
                    C[i] = (byte)(input[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(true, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));

                c_text_length = cipher.GetOutputSize(inLen);
                byte[] tmp = new byte[c_text_length];

                int len = cipher.ProcessBytes(input, inOff, inLen, C, 0);
                len += cipher.DoFinal(tmp, len);

                C             = new byte[len + mac.GetMacSize()];
                c_text_length = len;

                Array.Copy(tmp, 0, C, 0, len);

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

            byte[] macIV = param.GetEncodingV();

            mac.Init(macKey);
            mac.BlockUpdate(C, 0, c_text_length);
            mac.BlockUpdate(macIV, 0, macIV.Length);
            //
            // return the message and it's MAC
            //
            mac.DoFinal(C, c_text_length);
            return(C);
        }
Пример #15
0
        private byte[] DecryptBytes(byte[] p_key, byte[] p_data)
        {
            BufferedBlockCipher cipher = new BufferedBlockCipher(new BlowfishEngine());

            cipher.Init(false, new KeyParameter(p_key));

            return(cipher.ProcessBytes(p_data));
        }
Пример #16
0
        /// <summary>
        /// Encrypt stream with Blowfish-CBC
        /// </summary>
        /// <param name="input">Input stream to encrypt</param>
        /// <param name="output">Output stream</param>
        /// <param name="key">Key</param>
        /// <param name="iv">IV</param>
        /// <param name="paddingStyle">Padding</param>
        /// <param name="notifyProgression">Notify progression method</param>
        /// <param name="bufferSize">Buffer size</param>
        public static void EncryptCBC(Stream input, Stream output, byte[] key, byte[] iv, PaddingStyle paddingStyle = PaddingStyle.Pkcs7, Action <int> notifyProgression = null, int bufferSize = 4096)
        {
            IBufferedCipher  cipher     = new BufferedBlockCipher(new CbcBlockCipher(new BlowfishEngine()));
            ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key, 0, key.Length), iv, 0, iv.Length);

            cipher.Init(true, parameters);

            bool padDone = false;
            int  bytesRead;

            byte[] buffer = new byte[bufferSize];
            byte[] enc    = new byte[bufferSize];

            do
            {
                bytesRead = input.Read(buffer, 0, bufferSize);

                if (bytesRead == bufferSize)
                {
                    cipher.ProcessBytes(buffer, enc, 0);
                    output.Write(enc, 0, bytesRead);
                }
                else if (bytesRead > 0)
                {
                    byte[] smallBuffer = new byte[bytesRead];
                    Array.Copy(buffer, 0, smallBuffer, 0, bytesRead);
                    byte[] padData = Padding.Pad(smallBuffer, BLOCK_SIZE, paddingStyle);
                    cipher.ProcessBytes(padData, enc, 0);
                    output.Write(enc, 0, padData.Length);
                    padDone = true;
                }

                if (notifyProgression != null && bytesRead > 0)
                {
                    notifyProgression(bytesRead);
                }
            } while (bytesRead == bufferSize);

            if (!padDone)
            {
                buffer = new byte[0];
                byte[] padData = Padding.Pad(buffer, BLOCK_SIZE, paddingStyle);
                cipher.ProcessBytes(padData, enc, 0);
                output.Write(enc, 0, padData.Length);
            }
        }
        public int Read(byte[] buffer, int offset, int count)
        {
            var length    = _baseStream.Read(buffer, offset, count);
            var decrypted = _decryptCipher.ProcessBytes(buffer, offset, length);

            Buffer.BlockCopy(decrypted, 0, buffer, offset, decrypted.Length);
            return(length);
        }
Пример #18
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);
        }
Пример #19
0
        private byte[] DecryptBytes(byte[] p_key, byte[] p_data)
        {
            BufferedBlockCipher cipher = new BufferedBlockCipher(new BlowfishEngine());

            // init using the given key
            cipher.Init(false, new KeyParameter(p_key));

            // decrypt the given data
            return(cipher.ProcessBytes(p_data));
        }
Пример #20
0
        private static DB readDB(byte[] telaraDBData, string outSQLDb, Action <String> progress)
        {
            Debug.Log("get new DB");

            DB db = new DB();

            try
            {
                byte[] key = System.Convert.FromBase64String("IoooW3zsQgm22XaVQ0YONAKehPyJqEyaoQ7sEqf1XDc=");

                BinaryReader reader = new BinaryReader(new MemoryStream(telaraDBData));
                Debug.Log("get page size");
                reader.BaseStream.Seek(16, SeekOrigin.Begin);
                UInt16 pageSize = (UInt16)IPAddress.NetworkToHostOrder(reader.readShort());
                Debug.Log("go page size:" + pageSize);

                reader.BaseStream.Seek(0, SeekOrigin.Begin);

                MemoryStream decryptedStream = new MemoryStream(telaraDBData.Length);

                int pageCount = telaraDBData.Length / pageSize;
                for (int i = 1; i < pageCount + 1; i++)
                {
                    byte[] iv = getIV(i);
                    BufferedBlockCipher cipher  = new BufferedBlockCipher(new OfbBlockCipher(new AesEngine(), 128));
                    ICipherParameters   cparams = new ParametersWithIV(new KeyParameter(key), iv);
                    cipher.Init(false, cparams);

                    byte[] bdata = reader.ReadBytes(pageSize);
                    byte[] ddata = new byte[pageSize];
                    cipher.ProcessBytes(bdata, 0, bdata.Length, ddata, 0);
                    // bytes 16-23 on the first page are NOT encrypted, so we need to replace them once we decrypt the page
                    if (i == 1)
                    {
                        for (int x = 16; x <= 23; x++)
                        {
                            ddata[x] = bdata[x];
                        }
                    }
                    decryptedStream.Write(ddata, 0, ddata.Length);
                    progress.Invoke("Decoding db " + i + "/" + pageCount);
                }
                decryptedStream.Seek(0, SeekOrigin.Begin);

                File.WriteAllBytes(outSQLDb, decryptedStream.ToArray());
                processSQL(db, outSQLDb, progress);
                Debug.Log("finished processing");
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
                throw ex;
            }
            return(db);
        }
Пример #21
0
        private byte[] EncryptBlock(byte[] input, int inOff, int inLen, byte[] z)
        {
            byte[]       c;
            KeyParameter macKey;
            var          kParam = new KdfParameters(z, _param.Derivation);
            int          cTextLength;
            var          macKeySize = _param.MacKeySize;

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

                c           = new byte[inLen + _mac.GetMacSize()];
                cTextLength = inLen;

                for (var i = 0; i != inLen; i++)
                {
                    c[i] = (byte)(input[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(true, new KeyParameter(buffer, 0, (cipherKeySize / 8)));

                cTextLength = _cipher.GetOutputSize(inLen);
                var tmp = new byte[cTextLength];

                var len = _cipher.ProcessBytes(input, inOff, inLen, tmp, 0);
                len += _cipher.DoFinal(tmp, len);

                c           = new byte[len + _mac.GetMacSize()];
                cTextLength = len;

                Array.Copy(tmp, 0, c, 0, len);

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

            var macIV = _param.Encoding;

            _mac.Init(macKey);
            _mac.BlockUpdate(c, 0, cTextLength);
            _mac.BlockUpdate(macIV, 0, macIV.Length);
            //
            // return the message and it's MAC
            //
            _mac.DoFinal(c, cTextLength);
            return(c);
        }
Пример #22
0
        /// <summary>
        /// Decrypt data with DES-CBC
        /// </summary>
        /// <param name="data">Data to decrypt</param>
        /// <param name="key">Key</param>
        /// <param name="iv">IV</param>
        /// <returns>Decrypted data</returns>
        public static byte[] DecryptCBC(byte[] data, byte[] key, byte[] iv)
        {
            byte[] dec = new byte[data.Length];

            IBufferedCipher  cipher     = new BufferedBlockCipher(new CbcBlockCipher(new DesEngine()));
            ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key, 0, key.Length), iv, 0, iv.Length);

            cipher.Init(false, parameters);
            cipher.ProcessBytes(data, dec, 0);

            return(dec);
        }
Пример #23
0
        public string GetEncryptedPassword(string encryptionKey)
        {
            // Encrypt password using Blowfish
            BufferedBlockCipher blowfishCipher = new BufferedBlockCipher(new BlowfishEngine());
            KeyParameter        blowfishKey    = new KeyParameter(Encoding.ASCII.GetBytes(encryptionKey));

            blowfishCipher.Init(true, blowfishKey);

            byte[] encryptedPasswordArray = blowfishCipher.ProcessBytes(Password);

            return(Convert.ToBase64String(encryptedPasswordArray));
        }
Пример #24
0
 public byte[] Decrypt(byte[] input, int offset, int length)
 {
     if (!_enable)
     {
         throw new InvalidOperationException("加密未开启。");
     }
     if (length < 1)
     {
         throw new ArgumentOutOfRangeException(nameof(length), $"{nameof(length)} 必须大于0");
     }
     return(_decrypt.ProcessBytes(input, offset, length));
 }
Пример #25
0
        /// <summary>
        /// Encrypt data with Blowfish-CBC
        /// </summary>
        /// <param name="data">Data to encrypt</param>
        /// <param name="key">Key</param>
        /// <param name="iv">IV</param>
        /// <returns>Encrypted data</returns>
        public static byte[] EncryptCBC(byte[] data, byte[] key, byte[] iv)
        {
            byte[] enc = new byte[data.Length];

            IBufferedCipher  cipher     = new BufferedBlockCipher(new CbcBlockCipher(new BlowfishEngine()));
            ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key, 0, key.Length), iv, 0, iv.Length);

            cipher.Init(true, parameters);
            cipher.ProcessBytes(data, enc, 0);

            return(enc);
        }
Пример #26
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);
        }
Пример #27
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)
Пример #28
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);
        }
Пример #29
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");
            }
        }
Пример #30
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);
        }
Пример #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));
				}
			}
		}