Beispiel #1
0
        //создание(true)/считывание(false) ключей
        private bool SetKeys(string myPublicKeyFileName, string myPrivateKeyFileName, string path)
        {
            var myId = AuthorizeService.Instance.CurrentUserId;

            if (File.Exists(path + "\\" + myPublicKeyFileName) && File.Exists(path + "\\" + myPrivateKeyFileName))
            {
                var reader = new StreamReader(path + "\\" + myPrivateKeyFileName);
                var line   = reader.ReadToEnd();
                if (line != string.Empty)
                {
                    _cryptTool.keyRSAPrivate = Convert.FromBase64String(line);
                    reader = new StreamReader(path + "\\" + myPublicKeyFileName);
                    line   = reader.ReadToEnd();
                    var data = line.Split(' ');
                    if (line != string.Empty && data.Length == 2)
                    {
                        int id;
                        if (int.TryParse(data[0], out id) && id == myId)
                        {
                            _cryptTool.keyRSAPublic = Convert.FromBase64String(data[1]);
                            reader.Dispose();
                            return(false);
                        }
                    }
                }
                reader.Dispose();
            }

            _cryptTool.CreateRSAKey();

            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            var settings  = config.AppSettings.Settings;
            var confName  = "public_key_id";
            var docIdPath = settings[confName];

            if (docIdPath != null)
            {
                settings.Remove(confName);
                config.Save(ConfigurationSaveMode.Modified);
            }

            var writer = new StreamWriter(path + "\\" + myPublicKeyFileName);

            writer.Write(myId + " " + Convert.ToBase64String(_cryptTool.keyRSAPublic));
            writer.Close();
            writer = new StreamWriter(path + "\\" + myPrivateKeyFileName);
            writer.Write(Convert.ToBase64String(_cryptTool.keyRSAPrivate));
            writer.Close();
            return(true);
        }