Ejemplo n.º 1
0
        private Result GetDecryptor(out ICipher decryptor, long offset)
        {
            if (offset == 0)
            {
                // Use the IV directly
                decryptor = Aes.CreateCbcDecryptor(_key, _iv);
                return(Result.Success);
            }

            decryptor = default;

            // Need to get the output of the previous block
            Span <byte> prevBlock = stackalloc byte[BlockSize];
            Result      rc        = BaseStorage.Read(offset - BlockSize, prevBlock);

            if (rc.IsFailure())
            {
                return(rc);
            }

            ICipher tmpDecryptor = Aes.CreateCbcDecryptor(_key, _iv);

            tmpDecryptor.Transform(prevBlock, prevBlock);

            decryptor = tmpDecryptor;
            return(Result.Success);
        }
Ejemplo n.º 2
0
        public byte[] ToByteArray(bool uhash, ICipher cipher)
        {
            using (MemoryStream data = new MemoryStream())
            {
                using (BinaryWriter data_writer = new BinaryWriter(data))
                {
                    byte[] body = stream.ToArray();
                    if (cipher != null)
                    {
                        cipher.Decrypt(ref body, body.Length);
                    }

                    data_writer.Write(CodePacketType(type, body.Length));
                    data_writer.Write((ushort)body.Length);
                    data_writer.Write((uint)sequence);
                    if (uhash)
                    {
                        data_writer.Write((int)this.uhash);
                    }
                    data_writer.Write(body, 0, body.Length);

                    return(data.ToArray());
                }
            }
        }
 public override void Stash()
 {
     base.Stash();
     this.cipher?.Dispose();
     this.cipher = null;
     this.dh     = null;
 }
Ejemplo n.º 4
0
        public static bool TryParseProtected(IAead aead, ICipher cipher, MemoryCursor cursor, out InitialPacket result)
        {
            result = new InitialPacket();

            var startOffset = cursor.AsOffset();
            var firstByte   = PacketFirstByte.Parse(cursor.Peek(1).Span[0]);

            if (!firstByte.IsInitialType())
            {
                return(false);
            }

            cursor.Move(1);

            var version = PacketVersion.Parse(cursor);
            var destinationConnectionId = PacketConnectionId.Parse(cursor);
            var sourceConnectionId      = PacketConnectionId.Parse(cursor);
            var token   = PacketToken.Parse(cursor);
            var payload = PacketPayload.SliceLongProtectedPacketBytes(cursor, aead, cipher, startOffset, firstByte, null, out var packetNumber);

            result = new InitialPacket(version,
                                       destinationConnectionId,
                                       sourceConnectionId,
                                       token,
                                       packetNumber,
                                       payload);

            return(true);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Decrypts the <paramref name="encrypted"/> data with the <paramref name="cipher"/>.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cipher">The cipher.</param>
        /// <param name="encrypted">The encrypted.</param>
        /// <returns>T.</returns>
        public static Nullable <T> DecryptNullable <T>(
            this ICipher cipher,
            byte[] encrypted) where T : struct
        {
            if (cipher == null)
            {
                throw new ArgumentNullException(nameof(cipher));
            }
            if (encrypted == null)
            {
                throw new ArgumentNullException(nameof(encrypted));
            }
            if (encrypted.Length < 2)
            {
                throw new ArgumentException(Resources.InvalidArgumentLength, nameof(encrypted));
            }
            if (!EncryptTypedData.ContainsKey(typeof(T)))
            {
                throw new ArgumentException("The specified data type cannot be decrypted.");
            }

            var decrypted = cipher.Decrypt(encrypted);

            if (decrypted.Length < 2)
            {
                throw new ArgumentException("The argument is not a valid encrypted Nullable<T> value.");
            }

            return(FromByteArray.ToNullable <T>(decrypted));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// RPC调用
        /// </summary>
        /// <param name="name"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static object Action(string name, string val, ICipher algorithm = null)
        {
            if (algorithm == null)
            {
                algorithm = Program.AES;
            }

            var encData  = algorithm.Encrypt(val);
            var respJson = session.Post(UAC_API, new
            {
                action = name,
                data   = encData
            });

            if (respJson != null)
            {
                var jObj = respJson as JObject;
                if (jObj["data"][0] == null)
                {
                    return(null);
                }
                var rtData = algorithm.Decrypt(jObj["data"][0].ToString());
                var json   = Program.JsonParse(rtData);
                if (json == null)
                {
                    // 是字符串
                    return(rtData);
                }
                else
                {
                    return(json);
                }
            }
            return(null);
        }
Ejemplo n.º 7
0
        public static bool TryParseProtectedByConnectionId(IAead aead,
                                                           ICipher cipher,
                                                           MemoryCursor cursor,
                                                           PacketConnectionId connectionId,
                                                           PacketNumber largestAcknowledgedPacketNumber,
                                                           out ShortPacket result)
        {
            result = new ShortPacket();

            var startOffset = cursor.AsOffset();
            var firstByte   = PacketFirstByte.Parse(cursor.Peek(1).Span[0]);

            if (!firstByte.IsShortHeader())
            {
                return(false);
            }

            cursor.Move(1);

            if (!connectionId.TrySliceValue(cursor))
            {
                return(false);
            }

            var payload = PacketPayload.SliceShortProtectedPacketBytes(cursor, aead, cipher, startOffset, firstByte, largestAcknowledgedPacketNumber, out var packetNumber);

            result = new ShortPacket(connectionId, packetNumber, payload);

            return(true);
        }
Ejemplo n.º 8
0
        private void mi_typeencrypt_Click(object sender, RoutedEventArgs e)
        {

            WindowTypeEncrypt = new WindowTypeEncrypt();
            WindowTypeEncrypt.Owner = this;
            WindowTypeEncrypt.ShowDialog();
            if (WindowTypeEncrypt.DialogResult.HasValue && WindowTypeEncrypt.DialogResult.Value)
            {

                if (WindowTypeEncrypt.radioButton_cezar.IsChecked == true)
                    Cipher = new Cesar();
                else if (WindowTypeEncrypt.radioButton_tritemius.IsChecked == true)
                    Cipher = new Tritemius();
                else if (WindowTypeEncrypt.radioButton_xor.IsChecked == true)
                    Cipher = new XOR();
                else if (WindowTypeEncrypt.radioButton_Cycle.IsChecked == true)
                    Cipher = new Cycle("1 0 1 1");
                else if (WindowTypeEncrypt.radioButton_shtirl.IsChecked == true)
                    Cipher = new Shtirliz();
                else if (WindowTypeEncrypt.radioButton_des.IsChecked == true)
                    Cipher = new DES();
                else if (WindowTypeEncrypt.radioButton_RSA.IsChecked == true)
                    Cipher = new RSA();
                else if (WindowTypeEncrypt.radioButton_El_Gammal.IsChecked == true)
                    Cipher = new El_Gammal();
                Cipher.Alphabet = WindowTypeEncrypt.AlphabetString.ToArray();
            }
        }
Ejemplo n.º 9
0
        //sets AppOptions when crypting method changes
        public static void SetAppOptionsCryptingMethod(System.Windows.Controls.Label lbl, IntegerUpDown nud, int newValue)
        {
            ICipher checkMethod = GetCipher(newValue);

            if (checkMethod != null)
            {
                AppOptions.CryptingMethod = checkMethod;
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Setting crypting method failed");
                return;
            }
            if (((CipherBase)AppOptions.CryptingMethod).HasKey)
            {
                CipherKeyBase keyCipherMethod = (CipherKeyBase)AppOptions.CryptingMethod;
                lbl.Content = String.Format($"{keyCipherMethod.Name}" +
                                            $" method Key value ({keyCipherMethod.KeyMinConstraint}" +
                                            $" - {keyCipherMethod.KeyMaxConstraint}):");
                nud.Visibility = System.Windows.Visibility.Visible;
                nud.Minimum    = keyCipherMethod.KeyMinConstraint;
                nud.Maximum    = keyCipherMethod.KeyMaxConstraint;
            }
            else
            {
                lbl.Content    = String.Format($"{((CipherBase)AppOptions.CryptingMethod).Name} method don't use crypting key value");
                nud.Visibility = System.Windows.Visibility.Hidden;
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            /*
             * 3个角色:
             *      1 Context(环境类):环境类是使用算法的角色,它在解决某个问题(即实现某个给功能)时可以采用多种策略。
             *                           在环境类中维持一个对抽象策略类的引用实例,用于定义采用的策略
             *      2 Strategy(抽象策略类):抽象策略类为所支持的算法声明了抽象方法,是所有策略类的父类,它可以是抽象类或具体类,也可以是接口
             *      3 ConcreteStrategy(具体策略类):具体策略类实现了在抽象类中声明的算法,在运行时,具体策略类对象将覆盖在环境类中定义的抽象策略类引用,使用一种具体的算法实现某个业务功能。
             *
             */



            /* 某系统需要对用户的密码进行加密(凯撒加密,求模加密)  */

            //读取配置文件
            string value = Common.StringHelp.GetConfigValue("Ciphertype");

            //反射生产具体加密对象
            ICipher cipher = (ICipher)Assembly.Load("StrategyPattern").CreateInstance(value);

            DataOperation dataOperation = new DataOperation(cipher);

            dataOperation.ShowResult();

            Console.ReadLine();
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Encrypt the cleartext contents of a byte array
 /// </summary>
 /// <param name="cipher">The <see cref="ICipher"/> to use for encrypting the data</param>
 /// <param name="input">The cleartext data to encrypt</param>
 /// <returns>An array containing the encrypted data</returns>
 public static byte[] Encrypt(this ICipher cipher, byte[] input)
 {
     using (var ostream = new MemoryStream()) {
         cipher.Encrypt(input, ostream);
         return(ostream.ToArray());
     }
 }
Ejemplo n.º 12
0
        private void UpdateCipher(int?messageCipherType)
        {
            if (!messageCipherType.HasValue)
            {
                return;
            }
            switch ((CipherTypes)messageCipherType)
            {
            case CipherTypes.Cesar:
                _cipher = new CesarCipher();
                break;

            case CipherTypes.Des:
                _cipher = new DesCipher();
                break;

            case CipherTypes.TripleDes:
                _cipher = new TripleDes();
                break;

            case CipherTypes.TripleDesTwo:
                _cipher = new TripleDoubleKeyDes();
                break;
            }
        }
Ejemplo n.º 13
0
        private void Pack()
        {
            Packer packer = null;

            if (compressCheckBox.Checked && encryptCheckBox.Checked)
            {
                packer = new FullPacker();
            }
            else if (compressCheckBox.Checked)
            {
                packer = new CompressionPacker();
            }
            else if (encryptCheckBox.Checked)
            {
                packer = new EncryptionPacker();
            }

            packer.Compressor = GetCompressor();
            ICipher cipher = GetCipher();

            packer.Encryptor      = GetEncryptor(cipher);
            packer.StatusChanged += OnStatusChanged;
            packer.WorkFinished  += OnWorkFinished;

            SwitchControls(false);
            packer.PackAsync(_filePath);
        }
Ejemplo n.º 14
0
        }                                            // The lock for sending packets in sequence to the client.

        /// <summary>
        ///     This class contains the player's network passport information, which includes the remote client socket,
        ///     packet buffer, player's IP address, a collection of variables for processing packets from the client, and
        ///     methods used for sending and processing packets.
        /// </summary>
        /// <param name="server">The server the client is currently connected to.</param>
        /// <param name="socket">The client's remote socket.</param>
        /// <param name="cipher">The client's authentication cipher for packet processing.</param>
        public Passport(IAsynchronousSocket server, Socket socket, ICipher cipher)
        {
            Server    = server;
            Socket    = socket;
            IpAddress = (socket.RemoteEndPoint as IPEndPoint)?.Address.ToString();
            Cipher    = cipher;
            SendLock  = new object();
        }
Ejemplo n.º 15
0
        private void generator_checked(object sender, RoutedEventArgs e)
        {
            fileTB.IsEnabled      = false;
            openFileBTN.IsEnabled = false;
            modeGB.IsEnabled      = false;

            _cipher = lfsr;
        }
        protected override void OnConnectionClosed(ConnectionClosedEventArgs args)
        {
            this.cipher?.Dispose();
            this.cipher = null;
            this.dh     = null;

            base.OnConnectionClosed(args);
        }
 internal RpcUdpConnectionEncrypted(UdpPeer parent, ICipher cipher, IRpcPeer rpcPeer, RpcConfiguration configuration) : base(parent, rpcPeer, configuration)
 {
     if (cipher == null)
     {
         throw new ArgumentNullException(nameof(cipher));
     }
     this.cipher = cipher;
     this.dh     = new DiffieHellmanImpl(cipher);
 }
        private CmsEnvelopedData doGenerate(
            ICmsTypedData content,
            ICipherBuilderWithKey<AlgorithmIdentifier> contentEncryptor)
        {
            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();
            AlgorithmIdentifier encAlgId;
            Asn1OctetString encContent;

            MemoryOutputStream bOut = new MemoryOutputStream();

            try
            {
                ICipher cOut = contentEncryptor.BuildCipher(bOut);

                content.Write(cOut.Stream);

                cOut.Stream.Close();
            }
            catch (IOException e)
            {
                throw new CmsException(e.Message, e);
            }

            byte[] encryptedContent = bOut.ToArray();

            encAlgId = contentEncryptor.AlgorithmDetails;

            encContent = new BerOctetString(encryptedContent);

            ISymmetricKey encKey = contentEncryptor.Key;

            for (IEnumerator<IRecipientInfoGenerator> it = recipientInfoGenerators.GetEnumerator(); it.MoveNext();)
            {
                IRecipientInfoGenerator recipient = (IRecipientInfoGenerator)it.Current;

                recipientInfos.Add(recipient.Generate(encKey));
            }

            EncryptedContentInfo eci = new EncryptedContentInfo(
                            content.ContentType,
                            encAlgId,
                            encContent);

            Asn1Set unprotectedAttrSet = null;
            if (unprotectedAttributeGenerator != null)
            {
                Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(new Dictionary<string, object>());

                unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector());
            }

            ContentInfo contentInfo = new ContentInfo(
                    CmsObjectIdentifiers.EnvelopedData,
                    new EnvelopedData(originatorInfo, new DerSet(recipientInfos), eci, unprotectedAttrSet));

            return new CmsEnvelopedData(contentInfo);
        }
Ejemplo n.º 19
0
        internal static void CipherTestCore(byte[] inputData, byte[] expected, ICipher cipher)
        {
            byte[] transformBuffer = new byte[inputData.Length];
            Buffer.BlockCopy(inputData, 0, transformBuffer, 0, inputData.Length);

            cipher.Transform(transformBuffer, transformBuffer);

            Assert.Equal(expected, transformBuffer);
        }
Ejemplo n.º 20
0
        public void CipherPlainTextProperlyTest(ICipher cipher)
        {
            var plainText  = "Secret Text";
            var passPhrase = "password1";

            var cipherText = cipher.Encrypt(plainText, passPhrase);

            Assert.True(plainText != cipherText);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Encrypt the cleartext contents of a byte array
        /// </summary>
        /// <param name="cipher">The <see cref="ICipher"/> to use for encrypting the data</param>
        /// <param name="input">The cleartext data to encrypt</param>
        /// <returns>An array containing the encrypted data</returns>
        public static async Task <byte[]> EncryptAsync(this ICipher cipher, byte[] input)
        {
            using (var istream = new MemoryStream(input))
                using (var ostream = new MemoryStream()) {
                    await cipher.EncryptAsync(istream, ostream).ConfigureAwait(false);

                    return(ostream.ToArray());
                }
        }
Ejemplo n.º 22
0
        public Text(ICipher newCipher)
        {
            PlainText  = null;
            CipherText = null;

            PlainTextFilePath  = null;
            CipherTextFilePath = null;

            cipher = newCipher;
        }
Ejemplo n.º 23
0
        public XmlStorage(ICipher cipher, IBitmapSourceSerializer bitmapSourceSerializer)
        {
            _cipher = cipher;
            _bitmapSourceSerializer = bitmapSourceSerializer;

            if (!StorageExists())
            {
                CreateEmpty();
            }
        }
Ejemplo n.º 24
0
        public void CipherAndDecipherTextTest(ICipher cipher)
        {
            var plainText  = "Secret Text";
            var passPhrase = "password1";

            var cipherText   = cipher.Encrypt(plainText, passPhrase);
            var decipherText = cipher.Decrypt(cipherText, passPhrase);

            Assert.True(plainText == decipherText);
        }
Ejemplo n.º 25
0
        internal byte[] genKey(byte[] passphrase, byte[] iv)
        {
            if (cipher == null)
            {
                cipher = genCipher();
            }
            if (hash == null)
            {
                hash = genHash();
            }

            byte[] key   = new byte[cipher.getBlockSize()];
            int    hsize = hash.getBlockSize();

            byte[] hn = new byte[key.Length / hsize * hsize +
                                 (key.Length % hsize == 0 ? 0 : hsize)];
            try {
                byte[] tmp = null;
                if (vendor == VENDOR_OPENSSH)
                {
                    for (int index = 0; index + hsize <= hn.Length;)
                    {
                        if (tmp != null)
                        {
                            hash.update(tmp, 0, tmp.Length);
                        }
                        hash.update(passphrase, 0, passphrase.Length);
                        hash.update(iv, 0, iv.Length);
                        tmp = hash.digest();
                        Array.Copy(tmp, 0, hn, index, tmp.Length);
                        index += tmp.Length;
                    }
                    Array.Copy(hn, 0, key, 0, key.Length);
                }
                else if (vendor == VENDOR_FSECURE)
                {
                    for (int index = 0; index + hsize <= hn.Length;)
                    {
                        if (tmp != null)
                        {
                            hash.update(tmp, 0, tmp.Length);
                        }
                        hash.update(passphrase, 0, passphrase.Length);
                        tmp = hash.digest();
                        Array.Copy(tmp, 0, hn, index, tmp.Length);
                        index += tmp.Length;
                    }
                    Array.Copy(hn, 0, key, 0, key.Length);
                }
            }
            catch (Exception e) {
                Console.WriteLine(e);
            }
            return(key);
        }
Ejemplo n.º 26
0
        public static byte[] Encrypt(
            this ICipher cipher,
            ushort data)
        {
            if (cipher == null)
            {
                throw new ArgumentNullException(nameof(cipher));
            }

            return(cipher.Encrypt(ToByteArray.Convert(data)));
        }
Ejemplo n.º 27
0
 public static async Task <string> TryDecryptFileAsync(this ICipher cipher, string file)
 {
     try
     {
         return(await cipher.DecryptFileAsync(file));
     }
     catch (DecryptionFailedException)
     {
         return(null);
     }
 }
Ejemplo n.º 28
0
 public static Task EncryptToFileAsync(this ICipher cipher, string file, string text, bool writeBase64 = false)
 {
     if (writeBase64)
     {
         return(Task.Run(() => File.WriteAllText(file, cipher.EncryptToBase64(text))));
     }
     else
     {
         return(Task.Run(() => File.WriteAllBytes(file, cipher.Encrypt(text))));
     }
 }
Ejemplo n.º 29
0
 public static LongProtectedWritingContext StartLongProtectedPacketWriting(
     MemoryCursor cursor,
     IAead aead,
     ICipher cipher,
     int startPacketOffset,
     PacketFirstByte firstByte,
     PacketNumber packetNumber,
     PacketNumber?largestAcknowledgedPacketNumber)
 {
     return(new LongProtectedWritingContext(aead, cipher, cursor, startPacketOffset, cursor.AsOffset(), packetNumber, largestAcknowledgedPacketNumber, firstByte));
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Encrypts the <paramref name="data"/>.
        /// </summary>
        /// <param name="cipher">The cipher.</param>
        /// <param name="data">The data to be encrypted.</param>
        /// <returns>The encrypted text.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="cipher"/> is <see langword="null"/>.</exception>
        public static byte[] Encrypt(
            this ICipher cipher,
            int data)
        {
            if (cipher == null)
            {
                throw new ArgumentNullException(nameof(cipher));
            }

            return(cipher.Encrypt(BitConverter.GetBytes(data)));
        }
Ejemplo n.º 31
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _disposed = true;
                _readCipher?.Dispose();
                _readCipher = null;

                CipherLib?.Dispose();
                CipherLib = null;
            }
        }
        public string generateCipherText(IChromosome c, ICipher cipher)
        {
            char[] ciphertext = new char[cipher.Length];
            int i = 0;
            foreach (char allele in c.Alleles)
            {
                if (i < Cipher.Cipher.Count)
                {
                    foreach (int letter in Cipher.Cipher[i])
                    {
                        ciphertext[letter - 1] = allele;

                    }
                    i++;
                }
            }
            return new string(ciphertext);
        }
 public ReducedFitness(IChromosome[] population, ICipher cipher)
 {
     Population = population;
     Cipher = cipher;
 }
 public NGramFitness(IChromosome[] population, ICipher cipher)
 {
     Population = population;
     Cipher = cipher;
 }
Ejemplo n.º 35
0
        public TCPConnection(TCPManager iocp, Socket socket, INetworkHandler handler, Config.ConfigNet config)
        {
            m_config = config;
            m_iocp = iocp;
            m_networkHandler = handler;
            m_socket = socket;
            if (m_socket == null)
            {
                InitOutgoingSocket();
            }

            if (config.Encrypted)
            {
                m_encoding = new XRC4Cipher();
                m_decoding = new XRC4Cipher();
            }
            else
            {
                m_encoding = new XCipher();
                m_decoding = new XCipher();
            }
            m_encoding.SetKey("}h79q~B%al;k'y $E");
            m_decoding.SetKey("}h79q~B%al;k'y $E");

            m_readEventArgs = m_iocp.AcquireAsyncEvent();
            m_readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
            m_readEventArgs.UserToken = this;

            m_writeEventArgs = m_iocp.AcquireAsyncEvent();
            m_writeEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
            m_writeEventArgs.UserToken = this;

            m_readEventArgs.AcceptSocket = m_socket;
            m_writeEventArgs.AcceptSocket = m_socket;
        }
Ejemplo n.º 36
0
 public void AddCipher(ICipher cipher)
 {
     _cipherChain.AddLast(cipher);
 }