Beispiel #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." + "\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));
            }
        }
Beispiel #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 - " + "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));
            }
        }
Beispiel #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);
        }
Beispiel #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);
        }
        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);
        }
Beispiel #6
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)
Beispiel #7
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);
        }
Beispiel #8
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);
        }
Beispiel #9
0
        /// <summary>
        /// Creates a symmetric encryptor/decryptor object using the specified key and initialization vector (IV) for OFB or CFB block cipher mode of operation.
        /// </summary>
        /// <param name="forEncryption">Flag used to determine what object, a symmetric encryptor or a symmetric decryptor method returns.</param>
        /// <returns>A symmetric encryptor/decryptor object used for OFB or CFB block cipher mode of operation.</returns>
        public IBufferedCipher CreateAesCipher(bool forEncryption)
        {
            IBufferedCipher cipher;
            var             keyParameter = new KeyParameter(Key);
            var             keyWithIv    = new ParametersWithIV(keyParameter, IV);

            switch (ModeSignature)
            {
            case "OFB":
            {
                cipher = new BufferedBlockCipher(new OfbBlockCipher(new AesEngine(), 16));
                cipher.Init(forEncryption, keyWithIv);
                return(cipher);
            }

            case "CFB":
            {
                cipher = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 16));
                cipher.Init(forEncryption, keyWithIv);
                return(cipher);
            }

            default:
            {
                throw new CryptographicException("Unknown block cipher mode '" + ModeSignature + "' used.");
            }
            }
        }
Beispiel #10
0
        public void Init(byte[] secretKey)
        {
            _enable = true;
            _key    = (byte[])secretKey.Clone();

            if (AesFastFastEngine.IsSupported)
            {
                _encrypt = new BufferedBlockCipher(new CfbBlockCipher(new AesFastFastEngine(), 8));
            }
            else
            {
                _encrypt = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8));
            }

            if (AesFastFastEngine.IsSupported)
            {
                _decrypt = new BufferedBlockCipher(new CfbBlockCipher(new AesFastFastEngine(), 8));
            }
            else
            {
                _decrypt = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8));
            }

            _encrypt.Init(true, new ParametersWithIV(new KeyParameter(secretKey), secretKey, 0, 16));
            _decrypt.Init(false, new ParametersWithIV(new KeyParameter(secretKey), secretKey, 0, 16));
        }
Beispiel #11
0
        private BufferedBlockCipher GenerateAES(byte[] key, bool forEncryption)
        {
            BufferedBlockCipher cipher = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8));

            cipher.Init(forEncryption, new ParametersWithIV(new KeyParameter(key), key));
            return(cipher);
        }
Beispiel #12
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());
                }
            }
        }
Beispiel #13
0
        public MessageDecryption(byte[] symmetricEncryptionKey)
        {
            var key = new KeyParameter(symmetricEncryptionKey);

            _cipher = new BufferedBlockCipher(new SicBlockCipher(new AesEngine()));
            _cipher.Init(false, new ParametersWithIV(key, EmptyIV));
        }
Beispiel #14
0
        /// <summary>
        /// Encapsulates the specified links into an RSDF container.
        /// </summary>
        /// <param name="links">The links.</param>
        /// <returns>
        /// Base-16-encoded RSDF container.
        /// </returns>
        public static string CreateRSDF(string[] links)
        {
            var aes = new AesEngine();
            var cfb = new CfbBlockCipher(aes, 8);
            var pad = new BufferedBlockCipher(cfb);
            var sb  = new StringBuilder();

            pad.Init(true, new ParametersWithIV(new KeyParameter(RSDFKey), RSDFIV));

            foreach (var link in links)
            {
                var input  = Encoding.UTF8.GetBytes(link);
                var output = new byte[input.Length];

                for (var i = 0; i < input.Length; i++)
                {
                    output[i] = pad.ProcessByte(input[i])[0];
                }

                sb.Append(Convert.ToBase64String(output));
                sb.Append(Environment.NewLine);
            }

            return(BitConverter.ToString(Encoding.ASCII.GetBytes(sb.ToString())).Replace("-", string.Empty));
        }
Beispiel #15
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);
        }
Beispiel #16
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));
        }
Beispiel #17
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);
        }
        private IBufferedCipher CreateRijndael(WinzipAesEncryptionData winzipAesEncryptionData)
        {
            var blockCipher = new BufferedBlockCipher(new RijndaelEngine());
            var param       = new KeyParameter(winzipAesEncryptionData.KeyBytes);

            blockCipher.Init(true, param);
            return(blockCipher);
        }
Beispiel #19
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));
        }
Beispiel #20
0
        public AesStream(byte[] data, byte[] key) : base(data)
        {
            EncryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 8));
            EncryptCipher.Init(true, new ParametersWithIV(new KeyParameter(key), key, 0, 16));

            DecryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 8));
            DecryptCipher.Init(false, new ParametersWithIV(new KeyParameter(key), key, 0, 16));
        }
            public EncryptorDecryptor(byte[] key)
            {
                EncryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 8));
                EncryptCipher.Init(true, new ParametersWithIV(new KeyParameter(key), key, 0, 16));

                DecryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 8));
                DecryptCipher.Init(false, new ParametersWithIV(new KeyParameter(key), key, 0, 16));
            }
Beispiel #22
0
        private static BufferedBlockCipher CreateAesEcbCipher(byte[] key)
        {
            AesEngine           engine    = new AesEngine();
            KeyParameter        parameter = new KeyParameter(key);
            BufferedBlockCipher cipher    = new BufferedBlockCipher(engine);

            cipher.Init(false, parameter);
            return(cipher);
        }
    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);
    }
Beispiel #24
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);
        }
Beispiel #25
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));
        }
Beispiel #26
0
 public AesStream(Stream stream, byte[] key)
 {
     BaseStream    = stream;
     encryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8));
     encryptCipher.Init(true, new ParametersWithIV(
                            new KeyParameter(key), key, 0, 16));
     decryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8));
     decryptCipher.Init(false, new ParametersWithIV(
                            new KeyParameter(key), key, 0, 16));
 }
Beispiel #27
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);
        }
Beispiel #28
0
        public static byte[] DecryptAesCtr(Stream inputStream, byte[] key, byte[] iv)
        {
            AesEngine         engine       = new AesEngine();
            KeyParameter      keyParameter = new KeyParameter(key);
            ICipherParameters parameters   = new ParametersWithIV(keyParameter, iv);

            BufferedBlockCipher cipher = new BufferedBlockCipher(new SicBlockCipher(engine));

            cipher.Init(false, parameters);
            return(DecryptAes(inputStream, cipher, inputStream.Length));
        }
        private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, ICipherParameters parameters)
        {
            try {
                cipher.Init(forEncrypt, parameters);

                return(this.cipher.DoFinal(input));
            }
            catch (CryptoException) {
                throw;
            }
        }
Beispiel #30
0
        public void EncriptChannel(byte[] secretKey)
        {
            var output = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8));

            output.Init(true, new ParametersWithIV(new KeyParameter(secretKey), secretKey, 0, 16));
            var input = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8));

            input.Init(false, new ParametersWithIV(new KeyParameter(secretKey), secretKey, 0, 16));
            var cipherStream = new CipherStream(client.GetStream(), input, output);

            streamWrapper = new StreamWrapper(cipherStream);
        }
		private IBufferedCipher createCipher(bool forEncryption)
		{
//			IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CFB/NoPadding");

			IBlockCipher blockCipher = new AesEngine();
			int bits = 8 * blockCipher.GetBlockSize(); // TODO Is this right?
			blockCipher = new CfbBlockCipher(blockCipher, bits);
			IBufferedCipher cipher = new BufferedBlockCipher(blockCipher);

//			SecureRandom random = new SecureRandom();
			byte[] keyBytes = new byte[32];
			//random.NextBytes(keyBytes);
			KeyParameter key = new KeyParameter(keyBytes);

			byte[] iv = new byte[cipher.GetBlockSize()];
			//random.NextBytes(iv);

			cipher.Init(forEncryption, new ParametersWithIV(key, iv));

			return cipher;
		}
Beispiel #32
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));
				}
			}
		}