Esempio n. 1
0
        /// <summary>
        /// 协议序列化,以及进行数据加密
        /// </summary>
        /// <param name="messageBase"></param>
        /// <returns></returns>
        public static byte[] Encode(MessageBase messageBase)
        {
            using (var memory = new MemoryStream())
            {
                // 将我们的协议类进行序列化转换为字节数组
                Serializer.Serialize(memory, messageBase);
                byte[] bytes  = memory.ToArray();
                string secret = ServerSocket.SecretKey;

                // 若果是请求进行加密,公钥加密
                if (messageBase is MessageSecret)
                {
                    secret = ServerSocket.PublicKey;
                }

                // 加密数据
                bytes = AES.AESEncrypt(bytes, secret);
                return(bytes);
            }
        }
Esempio n. 2
0
    public static void SaveData(Hashtable _hash)
    {
        if (_hash == null)
        {
            Debug.LogError("save data fail");
            return;
        }

        byte[] bytes = AES.AESEncrypt(JsonTools.jsonEncode(_hash));
        using (FileStream fs = new FileStream(PersistentDataPath, FileMode.OpenOrCreate, FileAccess.Write))
        {
            if (fs != null)
            {
                fs.Write(bytes, 0, bytes.Length);
                fs.Flush();
                fs.Dispose();
            }
            //Debug.Log("encrypt: " + bytes.Length + "  code: " + Encoding.UTF8.GetString(bytes));
        }
        //upload clould "Convert.ToBase64String(bytes)"
    }
Esempio n. 3
0
 /// <summary>
 /// Сохраняет открытый файл
 /// </summary>
 public void Save()
 {
     using (Stream stream = new FileStream(FileName, FileMode.Create, FileAccess.Write))
     {
         using (BinaryWriter binwr = new BinaryWriter(stream))
         {
             binwr.Write(Header.BaseSignature);
             binwr.Write(Header.VersionSignature);
             binwr.Write(_header.MasterSeed);
             byte[] jsonDecrypted, jsonEncrypted;
             using (MemoryStream ms = new MemoryStream())
             {
                 _jsonFormatter.WriteObject(ms, Root);
                 ms.Position   = 0;
                 jsonDecrypted = new byte[ms.Length];
                 ms.Read(jsonDecrypted, 0, (int)ms.Length);
             }
             jsonEncrypted = AES.AESEncrypt(jsonDecrypted, Encoding.Unicode.GetBytes(Password), _header.MasterSeed);
             binwr.Write(AES.AESEncrypt(jsonDecrypted, Encoding.Unicode.GetBytes(Password), _header.MasterSeed));
         }
     }
 }
Esempio n. 4
0
    private static void EncryptFile(string file)
    {
        if (!File.Exists(file))
        {
            Debug.LogError("加密文件不存在---");
            return;
        }

        string subPath    = file.Replace(resDir, string.Empty);
        string targetFile = targetDir + file.Replace(resDir, string.Empty);

        if (File.Exists(targetFile))
        {
            File.Delete(targetFile);
        }

        string dir = Path.GetDirectoryName(targetFile);

        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }

        FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);

        byte[] buff = new byte[fs.Length];
        fs.Read(buff, 0, (int)fs.Length);
        fs.Close();

        byte[]     encryptBuff = AES.AESEncrypt(buff, identifier);
        FileStream newFile     = new FileStream(targetFile, FileMode.Create);

        newFile.Write(encryptBuff, 0, encryptBuff.Length);
        newFile.Close();

        buff        = null;
        encryptBuff = null;
    }
Esempio n. 5
0
    private static void EncryptFile(string file)
    {
        Debug.Log("encrypt file:" + file);

        FileStream fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite);

        int numBytesToRead = (int)fs.Length;
        int numBytesRead   = 0;

        byte[] readByte = new byte[fs.Length];
        //读取字节
        while (numBytesToRead > 0)
        {
            // Read may return anything from 0 to numBytesToRead.
            int n = fs.Read(readByte, numBytesRead, numBytesToRead);

            // Break when the end of the file is reached.
            if (n == 0)
            {
                break;
            }

            numBytesRead   += n;
            numBytesToRead -= n;
        }
        fs.Close();

        //加密
        byte[] newBuff = AES.AESEncrypt(readByte);

        // 保存
        FileStream cfs = new FileStream(file + ".data", FileMode.Create);

        cfs.Write(newBuff, 0, newBuff.Length);
        newBuff = null;
        cfs.Close();
    }
Esempio n. 6
0
    private byte[] Encode(PackageType type, byte[] body)
    {
        int length = HEADER_LENGTH;

        byte[] data = body;
        if (body != null)
        {
            if (isCompress)
            {
                data = ZlibMgr.compressBytes(body);
            }
            if (isEncrypt)
            {
                data = AES.AESEncrypt(data);
            }
            length += data.Length;
        }

        byte[] buf = new byte[length];

        int index = 0;

        buf[index++] = Convert.ToByte(1);
        buf[index++] = Convert.ToByte(data.Length >> 24 & 0xFF);
        buf[index++] = Convert.ToByte(data.Length >> 16 & 0xFF);
        buf[index++] = Convert.ToByte(data.Length >> 8 & 0xFF);
        buf[index++] = Convert.ToByte(data.Length & 0xFF);

        while (index < length)
        {
            buf[index] = data[index - HEADER_LENGTH];
            index++;
        }

        return(buf);
    }
Esempio n. 7
0
        static void AEStest()
        {
            BufferFormat fan = new BufferFormat(1000, new FDataExtraHandle((o) =>
            {
                return(AES.AESEncrypt(o, AESkeys, "hello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello word"));
            }));

            fan.AddItem(true);
            fan.AddItem("abc");
            fan.AddItem(123);

            byte[] data = fan.Finish();


            ReadBytes read = new ReadBytes(data, 4, -1, new RDataExtraHandle((o) =>
            {
                return(AES.AESDecrypt(o, AESkeys, "hello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello word"));
            }));

            int    lengt;
            int    cmd;
            bool   var1;
            string var2;
            int    var3;

            if (read.IsDataExtraSuccess &&
                read.ReadInt32(out lengt) &&
                lengt == read.Length &&
                read.ReadInt32(out cmd) &&
                read.ReadBoolean(out var1) &&
                read.ReadString(out var2) &&
                read.ReadInt32(out var3))
            {
                Console.WriteLine("This AES-> Length:{0} Cmd:{1} var1:{2} var2:{3} var3:{4}", lengt, cmd, var1, var2, var3);
            }
        }
Esempio n. 8
0
 public static byte[] nocompress_aes(byte[] data, byte[] key)
 {
     return(AES.AESEncrypt(data, key));
 }
Esempio n. 9
0
        public static byte[] compress_aes(byte[] data, byte[] key)
        {
            data = ZipUtils.compressBytes(data);

            return(AES.AESEncrypt(data, key));
        }
Esempio n. 10
0
 private void AESencrypt_Click(object sender, RoutedEventArgs e)
 {
     setrichtextboxtext(AES.AESEncrypt(getrichtextboxtext(AESText1), AESkey.Text), AESText2);
 }
Esempio n. 11
0
 private void OKBtn_Click(object sender, RoutedEventArgs e)
 {
     if (UseName.Text == "")
     {
         MessageBox.Show("请输入用户名");
     }
     else if (key1.Text == "" || key2.Text == "" || key3.Text == "" || key4.Text == "")
     {
         MessageBox.Show("请输入完整的注册号码!");
     }
     else
     {
         try
         {
             using (SqlConnection conn = new SqlConnection(conStr))
             {
                 conn.Open();
                 using (SqlCommand cmd = new SqlCommand("", conn))
                 {
                     string regID = key1.Text + key2.Text + key3.Text + key4.Text;
                     //string regID = "MMACS00500WH339GH68M";
                     byte[] bregID;
                     bregID          = AES.AESEncrypt(regID);
                     cmd.CommandText = "select * from RegTable where RegID=@RegID";
                     cmd.Parameters.Clear();
                     cmd.Parameters.AddWithValue("RegID", bregID);
                     SqlDataReader dr = cmd.ExecuteReader();
                     if (!dr.Read())
                     {
                         MessageBox.Show("输入的注册码不正确!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                     }
                     else
                     {
                         dr.Close();
                         cmd.CommandText = "select AutherPWD from AuthorTable where Name=@Name";
                         cmd.Parameters.Clear();
                         cmd.Parameters.AddWithValue("Name", UseName.Text);
                         dr = cmd.ExecuteReader();
                         if (!dr.Read())
                         {
                             MessageBox.Show("该用户不存在,请先注册或检查输入的用户名是否正确");
                         }
                         else
                         {
                             string pwd     = AES.AESDecrypt((byte[])dr[0]);
                             string message = "您的登录密码为:" + pwd;
                             MessageBox.Show(message);
                             UseName.Clear();
                             key1.Clear();
                             key2.Clear();
                             key3.Clear();
                             key4.Clear();
                         }
                     }
                 }
             }
         }
         catch
         {
             MessageBox.Show("无法连接数据库!");
             this.Close();
         }
     }
 }
Esempio n. 12
0
 public static void EcryptAssetBundle(string abPath)
 {
     byte[] bytes = File.ReadAllBytes(abPath);
     bytes = AES.AESEncrypt(bytes);  //AES加密
     File.WriteAllBytes(abPath, bytes);
 }
Esempio n. 13
0
 private void regBtn_Click(object sender, RoutedEventArgs e)
 {
     if (username.Text == "" || (man.IsChecked == false && woman.IsChecked == false) || password1.Password == "" || password2.Password == "")
     {
         MessageBox.Show("请填写完整必要的信息", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
     }
     else if (password1.Password != password2.Password)
     {
         MessageBox.Show("两次输入的密码不相等,请重新输入!");
     }
     else if (key1.Text == "" || key2.Text == "" || key3.Text == "" || key4.Text == "")
     {
         MessageBox.Show("请输入完整的注册号码");
     }
     else
     {
         try
         {
             using (SqlConnection conn = new SqlConnection(conStr))
             {
                 conn.Open();
                 using (SqlCommand cmd = new SqlCommand("", conn))
                 {
                     string regID = key1.Text + key2.Text + key3.Text + key4.Text;
                     byte[] bregID;
                     bregID          = AES.AESEncrypt(regID);
                     cmd.CommandText = "select * from RegTable where RegID=@RegID";
                     cmd.Parameters.Clear();
                     cmd.Parameters.AddWithValue("RegID", bregID);
                     SqlDataReader dr = cmd.ExecuteReader();
                     if (!dr.Read())
                     {
                         MessageBox.Show("输入的注册码不正确!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                     }
                     else
                     {
                         dr.Close();
                         string cipherpwd = password1.Password;
                         byte[] bcipherpwd;
                         bcipherpwd      = AES.AESEncrypt(cipherpwd);
                         cmd.CommandText = "insert into AuthorTable(Name,Sex,AutherPWD,RegTime) values(@Name,@Sex,@AutherPWD,@RegTime)";
                         cmd.Parameters.Clear();
                         cmd.Parameters.AddWithValue("Name", username.Text);
                         if (man.IsChecked == true)
                         {
                             cmd.Parameters.AddWithValue("Sex", "男");
                         }
                         else
                         {
                             cmd.Parameters.AddWithValue("Sex", "女");
                         }
                         cmd.Parameters.AddWithValue("AutherPWD", bcipherpwd);
                         cmd.Parameters.AddWithValue("RegTime", DateTime.Now);
                         cmd.ExecuteNonQuery();
                         MessageBox.Show("注册成功!欢迎使用数模助理");
                         username.Clear();
                         man.IsChecked   = false;
                         woman.IsChecked = false;
                         password1.Clear();
                         password2.Clear();
                         key1.Clear();
                         key2.Clear();
                         key3.Clear();
                         key4.Clear();
                     }
                 }
             }
         }
         catch
         {
             MessageBox.Show("无法连接数据库!");
             this.Close();
         }
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Updated
        /// </summary>
        /// <returns></returns>
        public static bool Save()
        { // this will be saved at the end
            byte[] outputByte = null;

            if (TextEditor.current.fileName == "" || TextEditor.current.fileName == null || TextEditor.current.fileName == "New File")
            {
                bool result = chooseFileName();
                if (result)
                {
                    Save();
                }
            }
            else
            {
                // let's save the file
                TextEditor.current.isXml = true;
                if (TextEditor.current.isXml == true)
                {
                    MemoryStream file         = new MemoryStream();
                    StreamWriter outputString = new StreamWriter(file, Encoding.UTF8);


                    //create the document into a xml form

                    XmlDocument doc = new XmlDocument();

                    // root
                    XmlDeclaration XmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", "no");
                    XmlElement     root           = doc.DocumentElement;
                    doc.InsertBefore(XmlDeclaration, root);

                    // first stage
                    XmlElement document = doc.CreateElement(string.Empty, "Documents", string.Empty);
                    doc.AppendChild(document);


                    using (StringReader sr = new StringReader(TextEditor.current.UITbText.Text))
                    {
                        string line = "";
                        while ((line = sr.ReadLine()) != null)
                        {
                            // if the CryptFileMethod is set to file, nothing append because the text is saved in clear inside the file
                            // so we use the line variable without changing it
                            if (TextEditor.current.CryptFileMethod == Method.CryptFileMethod.content)
                            {
                                // =========================================
                                //            Crypt content
                                // =========================================

                                // intitialisation of the input and input
                                byte[] ByteInput  = Encoding.UTF8.GetBytes(line);
                                byte[] ByteOutput = new byte[ByteInput.Length];

                                // selecting the ouput
                                // custom
                                if (TextEditor.current.CryptMethod == Method.CryptMethod.custom)
                                {
                                    ByteOutput = cryptByte.crypt_code(ByteInput, TextEditor.current.augmentKey.ToArray());
                                }
                                // AES
                                else if (TextEditor.current.CryptMethod == Method.CryptMethod.AES)
                                {
                                    ByteOutput = AES.AESEncrypt(ByteInput, TextEditor.current.augmentKey.ToArray());
                                }
                                // clear, should not append
                                else if (TextEditor.current.CryptMethod == Method.CryptMethod.clear)
                                {
                                    // almost nothing to change here
                                    // because we use at the end the line variable and he is not changed
                                }

                                if (TextEditor.current.CryptMethod != Method.CryptMethod.clear)
                                {
                                    StringBuilder sw = new StringBuilder();
                                    foreach (byte we in ByteOutput)
                                    {
                                        sw.Append(Convert.ToInt32(we));
                                        sw.Append(" ");
                                    }
                                    line = sw.ToString();
                                }
                            }


                            XmlElement text      = doc.CreateElement(string.Empty, "Text", string.Empty);
                            XmlText    textValue = doc.CreateTextNode(line);
                            text.AppendChild(textValue);
                            document.AppendChild(text);
                        }

                        // release the string reader, we have stored all the text in the Xml Doxument
                    }

                    doc.Save(outputString);
                    file.Position = 0;


                    // handle different types of encryption

                    if (TextEditor.current.CryptFileMethod == Method.CryptFileMethod.file)
                    {
                        byte[] ByteInput = Encoding.UTF8.GetBytes(TextEditor.current.UITbText.ToString());

                        // custom
                        if (TextEditor.current.CryptMethod == Method.CryptMethod.custom)
                        {
                            outputByte = cryptByte.crypt_code(ByteInput, TextEditor.current.augmentKey.ToArray());
                        }
                        // AES
                        else if (TextEditor.current.CryptMethod == Method.CryptMethod.AES)
                        {
                            outputByte = AES.AESEncrypt(ByteInput, TextEditor.current.augmentKey.ToArray());
                        }
                        // if the text is clear
                        // should not append
                        else if (TextEditor.current.CryptMethod == Method.CryptMethod.clear)
                        {
                            outputByte = file.ToArray();
                        }
                    }
                    else
                    {
                        //if cryptfilemethod = content
                        outputByte = file.ToArray();
                    }
                }
                else
                {
                    // if the file isn't xml, it is save in plain text
                    //convert the textbox content in byte[]
                    outputByte = Encoding.UTF8.GetBytes(TextEditor.current.UITbText.Text);
                }

                // save the file
                File.WriteAllBytes(TextEditor.current.fileName, outputByte);

                //set the output :
                TextEditor.current.saved      = true;
                TextEditor.current.isModified = false;
                TextEditor.inputText.define();

                // exit the code, file save, ok
                return(true);
            }
            // retrun false because if the code here is executed, it mean that the file hasn't been saved.
            return(false);
        }
 public string AesEncrypt(string pass, string key)
 {
     return(AES.AESEncrypt(pass, key));
 }