コード例 #1
0
        private static string DecryptContent004(string encContent, string encItemKey, Guid?itemsKeyID, StandardNoteData dat)
        {
            StandardNoteAPI.Logger.TraceExt(StandardNotePlugin.Name, "Decrypt content with schema [002]",
                                            ("encContent", encContent),
                                            ("encItemKey", encItemKey),
                                            ("itemsKeyID", itemsKeyID?.ToString() ?? "NULL"));

            var keyOuter = dat.SessionData.RootKey_MasterKey;

            if (itemsKeyID != null)
            {
                var itemskey = dat.ItemsKeys.FirstOrDefault(p => p.UUID == itemsKeyID);
                if (itemskey == null)
                {
                    throw new StandardNoteAPIException($"Could not decrypt item (Key {itemsKeyID} not found)");
                }

                StandardNoteAPI.Logger.TraceExt(StandardNotePlugin.Name, $"Found itemskey: {itemskey.UUID}",
                                                ("itemskey.IsDefault", itemskey.IsDefault.ToString()),
                                                ("itemskey.Version", itemskey.Version),
                                                ("itemskey.Key", EncodingConverter.ByteToHexBitFiddleLowercase(itemskey.Key)));

                keyOuter = itemskey.Key;
            }

            var keyInner = Decrypt004(encItemKey, keyOuter);

            return(Decrypt004(encContent, EncodingConverter.StringToByteArrayCaseInsensitive(keyInner)));
        }
コード例 #2
0
        public string ReadString(int length)
        {
            int offset = _offset;

            this._offset += length;
            return(EncodingConverter.GetString(_buffer, offset, length));
        }
コード例 #3
0
ファイル: SessionManager.cs プロジェクト: brragul/Notepads
 /// <summary>
 /// Do not call this constructor directly. Use <see cref="SessionUtility.GetSessionManager(INotepadsCore)" instead./>
 /// </summary>
 public SessionManager(INotepadsCore notepadsCore)
 {
     _notepadsCore      = notepadsCore;
     _semaphoreSlim     = new SemaphoreSlim(1, 1);
     _encodingConverter = new EncodingConverter();
     _loaded            = false;
 }
コード例 #4
0
        public static string RandomSeed(int len)
        {
            byte[] seed = new byte[len];
            RNG.GetBytes(seed);

            return(EncodingConverter.ByteToHexBitFiddleLowercase(seed));
        }
コード例 #5
0
        protected override int Execute()
        {
            var config = FindConfig();

            if (config.Selected.IPAddress == null)
            {
                return(WriteError("No IP address specified"));
            }

            WriteDebug($"Target IP address is {config.Selected.IPAddress}");
            WriteDebug();

            try
            {
                var mac    = ExecuteDirect(config.Selected.IPAddressRaw);
                var strmac = EncodingConverter.ByteArrayToHexDump(mac, ":", -1, string.Empty, true);
                return(WriteInfoOutput(strmac, $"The MAC address of {config.Selected.IPAddress} is {strmac}"));
            }
            catch (TaskException)
            {
                throw;
            }
            catch (Exception e)
            {
                return(WriteError($"An error occured while sending ARP package: {e.Message}", e));
            }
        }
コード例 #6
0
        public static (byte[] pw, byte[] mk, string reqpw) CreateAuthData001(StandardNoteAPI.APIResultAuthParams apiparams, string mail, string uip)
        {
            if (apiparams.pw_func != StandardNoteAPI.PasswordFunc.pbkdf2)
            {
                throw new Exception("Unsupported pw_func: " + apiparams.pw_func);
            }

            byte[] bytes;

            if (apiparams.pw_alg == StandardNoteAPI.PasswordAlg.sha512)
            {
                bytes = PBKDF2.GenerateDerivedKey(apiparams.pw_key_size / 8, Encoding.UTF8.GetBytes(uip), Encoding.UTF8.GetBytes(apiparams.pw_salt), apiparams.pw_cost, PBKDF2.HMACType.SHA512);
            }
            else if (apiparams.pw_alg == StandardNoteAPI.PasswordAlg.sha512)
            {
                bytes = PBKDF2.GenerateDerivedKey(apiparams.pw_key_size / 8, Encoding.UTF8.GetBytes(uip), Encoding.UTF8.GetBytes(apiparams.pw_salt), apiparams.pw_cost, PBKDF2.HMACType.SHA512);
            }
            else
            {
                throw new Exception("Unknown pw_alg: " + apiparams.pw_alg);
            }

            var pw = bytes.Take(bytes.Length / 2).ToArray();
            var mk = bytes.Skip(bytes.Length / 2).ToArray();

            var reqpw = EncodingConverter.ByteToHexBitFiddleLowercase(pw);

            return(pw, mk, reqpw);
        }
        public void EncodingConverter_ConvertIsoBytesToUtf8String_EspanolSubstring()
        {
            var ec     = new EncodingConverter();
            var result = ec.ConvertIsoBytesToUtf8String(_espanolSubIsoBytes, 22, 10);

            Assert.AreEqual("español.ct", result);
        }
コード例 #8
0
ファイル: SessionManager.cs プロジェクト: ujuc/Notepads
        /// <summary>
        /// Do not call this constructor directly. Use <see cref="SessionUtility.GetSessionManager(INotepadsCore)" instead./>
        /// </summary>
        public SessionManager(INotepadsCore notepadsCore)
        {
            _notepadsCore = notepadsCore;
            _semaphoreSlim = new SemaphoreSlim(1, 1);
            _encodingConverter = new EncodingConverter();
            _sessionData = new ConcurrentDictionary<Guid, TextEditorSessionData>();
            _loaded = false;

            _notepadsCore.TextEditorLoaded += (sender, textEditor) =>
            {
                textEditor.TextChanging += RemoveTextEditorData;
                textEditor.EncodingChanged += RemoveTextEditorData;
                textEditor.LineEndingChanged += RemoveTextEditorData;
                textEditor.ChangeReverted += RemoveTextEditorData;
                textEditor.EditorModificationStateChanged += RemoveTextEditorData;
            };

            _notepadsCore.TextEditorUnloaded += (sender, textEditor) =>
            {
                textEditor.TextChanging -= RemoveTextEditorData;
                textEditor.EncodingChanged -= RemoveTextEditorData;
                textEditor.LineEndingChanged -= RemoveTextEditorData;
                textEditor.ChangeReverted -= RemoveTextEditorData;
                textEditor.EditorModificationStateChanged -= RemoveTextEditorData;
            };
        }
コード例 #9
0
        public string ReadLenString()
        {
            int offset = this._offset;
            int lenStr = ReadInt32();

            this._offset += lenStr;
            return(EncodingConverter.GetString(_buffer, offset + 4, lenStr));
        }
コード例 #10
0
 public static string SHA256Hex(string data)
 {
     using (var sha = SHA256.Create())
     {
         var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(data));
         return(EncodingConverter.ByteToHexBitFiddleLowercase(hash));
     }
 }
コード例 #11
0
        private static APIResultAuthorize Authenticate003(ISimpleJsonRest web, APIAuthParams apiparams, string mail, string uip, AlephLogger logger)
        {
            try
            {
                logger.Debug(StandardNotePlugin.Name, $"AutParams[version:{apiparams.version}, pw_cost:{apiparams.pw_cost}, pw_nonce:{apiparams.pw_nonce}]");

                if (apiparams.pw_cost < 100000)
                {
                    throw new StandardNoteAPIException($"Account pw_cost is too small ({apiparams.pw_cost})");
                }

                var    salt  = StandardNoteCrypt.SHA256(string.Join(":", mail, "SF", "003", apiparams.pw_cost.ToString(), apiparams.pw_nonce));
                byte[] bytes = PBKDF2.GenerateDerivedKey(768 / 8, Encoding.UTF8.GetBytes(uip), Encoding.UTF8.GetBytes(salt), apiparams.pw_cost, PBKDF2.HMACType.SHA512);

                var pw = bytes.Skip(0 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();
                var mk = bytes.Skip(1 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();
                var ak = bytes.Skip(2 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();

                var reqpw = EncodingConverter.ByteToHexBitFiddleUppercase(pw).ToLower();
                APIResultAuthorize tok;
                try
                {
                    tok = web.PostTwoWay <APIResultAuthorize>(new APIRequestUser {
                        email = mail, password = reqpw
                    }, "auth/sign_in");
                }
                catch (RestStatuscodeException e1)
                {
                    if (e1.StatusCode / 100 == 4 && !string.IsNullOrWhiteSpace(e1.HTTPContent))
                    {
                        var req = web.ParseJsonOrNull <APIBadRequest>(e1.HTTPContent);
                        if (req != null)
                        {
                            throw new StandardNoteAPIException($"Server returned status {e1.StatusCode}.\nMessage: '{req.error.message}'", e1);
                        }
                    }

                    throw;
                }

                tok.masterkey     = mk;
                tok.masterauthkey = ak;
                tok.version       = "003";
                return(tok);
            }
            catch (RestException)
            {
                throw;
            }
            catch (StandardNoteAPIException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new StandardNoteAPIException("Authentification with StandardNoteAPI failed.", e);
            }
        }
コード例 #12
0
        private static APIResultAuthorize Authenticate002(ISimpleJsonRest web, APIAuthParams apiparams, string mail, string password, IAlephLogger logger)
        {
            try
            {
                logger.Debug(StandardNotePlugin.Name, $"AutParams[version:2, pw_cost:{apiparams.pw_cost}]");

                if (apiparams.pw_func != PasswordFunc.pbkdf2)
                {
                    throw new Exception("Unknown pw_func: " + apiparams.pw_func);
                }

                byte[] bytes = PBKDF2.GenerateDerivedKey(768 / 8, Encoding.UTF8.GetBytes(password), Encoding.UTF8.GetBytes(apiparams.pw_salt), apiparams.pw_cost, PBKDF2.HMACType.SHA512);

                var pw = bytes.Skip(0 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();
                var mk = bytes.Skip(1 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();
                var ak = bytes.Skip(2 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();

                var reqpw = EncodingConverter.ByteToHexBitFiddleUppercase(pw).ToLower();
                APIResultAuthorize tok;
                try
                {
                    tok = web.PostTwoWay <APIResultAuthorize>(new APIRequestUser {
                        email = mail, password = reqpw
                    }, "auth/sign_in");
                }
                catch (RestStatuscodeException e1)
                {
                    if (e1.StatusCode / 100 == 4 && !string.IsNullOrWhiteSpace(e1.HTTPContent))
                    {
                        var req = web.ParseJsonOrNull <APIBadRequest>(e1.HTTPContent);
                        if (req != null)
                        {
                            throw new StandardNoteAPIException($"Server returned status {e1.StatusCode}.\nMessage: '{req.error.message}'", e1);
                        }
                    }

                    throw;
                }

                tok.masterkey     = mk;
                tok.masterauthkey = ak;
                tok.version       = "002";
                return(tok);
            }
            catch (RestException)
            {
                throw;
            }
            catch (StandardNoteAPIException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new StandardNoteAPIException("Authentification with StandardNoteAPI failed.", e);
            }
        }
コード例 #13
0
        private static string DecryptContent002(string encContent, string encItemKey, byte[] masterMK, byte[] masterAK)
        {
            var item_key = Decrypt002(encItemKey, masterMK, masterAK);

            var item_ek = item_key.Substring(0, item_key.Length / 2);
            var item_ak = item_key.Substring(item_key.Length / 2, item_key.Length / 2);

            return(Decrypt002(encContent, EncodingConverter.StringToByteArrayCaseInsensitive(item_ek), EncodingConverter.StringToByteArrayCaseInsensitive(item_ak)));
        }
コード例 #14
0
        /// <summary>
        /// 一次性读完包的字符串
        /// </summary>
        /// <returns></returns>
        public string ReadString()
        {
            int len = _dataCount - _offset;
            //string value = BitConverter.ToString(_buffer, _offset, len);//16进制标识的字符串
            string value = EncodingConverter.GetString(_buffer, _offset, len);

            _offset = Interlocked.Add(ref _offset, len);
            return(value);
        }
コード例 #15
0
        /// <summary>
        /// Adds an element with the provided key and value to the <see cref="IHeaderDictionary"/>.
        /// </summary>
        /// <param name="dic">The <see cref="IHeaderDictionary"/> to extend.</param>
        /// <param name="key">The string to use as the key of the element to add.</param>
        /// <param name="value">The string to use as the value of the element to add.</param>
        /// <param name="useAsciiEncodingConversion">if set to <c>true</c> an ASCII encoding conversion is applied to the <paramref name="value"/>.</param>
        public static void AddOrUpdateHeader(this IHeaderDictionary dic, string key, StringValues value, bool useAsciiEncodingConversion = true)
        {
            var headerValue = useAsciiEncodingConversion ? new StringValues(EncodingConverter.ToAsciiEncodedString(value)) : value;

            if (headerValue != StringValues.Empty)
            {
                dic.AddOrUpdate(key, headerValue.ToString().Where(c => !char.IsControl(c)).FromChars());
            }
        }
コード例 #16
0
 /// <summary>
 /// 文本全部转成UTF8,UTF8兼容性好 0标志写入结束
 /// </summary>
 public void WriteString0(string value)
 {
     if (value.IsNullEmpty())
     {
         return;
     }
     byte[] tmpBuffer = EncodingConverter.GetBytes(value);
     WriteBuffer(tmpBuffer);
     WriteSByte(0);//结束标识
 }
コード例 #17
0
        private static string DecryptContent001(string encContent, string encItemKey, string authHash, StandardNoteData dat)
        {
            StandardNoteAPI.Logger.TraceExt(StandardNotePlugin.Name, "Decrypt content with schema [001]",
                                            ("encContent", encContent),
                                            ("encItemKey", encItemKey),
                                            ("authHash", authHash));

            byte[] masterkey;

            if (dat.SessionData.Version == "001" || dat.SessionData.Version == "002" || dat.SessionData.Version == "003")
            {
                masterkey = dat.SessionData.RootKey_MasterKey;

                StandardNoteAPI.Logger.Trace(StandardNotePlugin.Name, "Use masterkey from session");
            }
            else
            {
                var itemskey = dat.ItemsKeys.FirstOrDefault(p => p.Version == "001");
                if (itemskey == null)
                {
                    throw new StandardNoteAPIException($"Could not decrypt item (Key for 002 not found)");
                }

                StandardNoteAPI.Logger.TraceExt(StandardNotePlugin.Name, $"Found itemskey: {itemskey.UUID}",
                                                ("itemskey.IsDefault", itemskey.IsDefault.ToString()),
                                                ("itemskey.Version", itemskey.Version),
                                                ("itemskey.Key", EncodingConverter.ByteToHexBitFiddleLowercase(itemskey.Key)),
                                                ("itemskey.AuthKey", EncodingConverter.ByteToHexBitFiddleLowercase(itemskey.AuthKey)));

                masterkey = itemskey.Key;
            }

            var itemKey = EncodingConverter.StringToByteArrayCaseInsensitive(Encoding.ASCII.GetString(AESEncryption.DecryptCBC256(Convert.FromBase64String(encItemKey), masterkey, new byte[16])));

            var ek = itemKey.Take(itemKey.Length / 2).ToArray();
            var ak = itemKey.Skip(itemKey.Length / 2).ToArray();

            var realHash = EncodingConverter.ByteToHexBitFiddleLowercase(AuthSHA256(Encoding.UTF8.GetBytes(encContent), ak));

            if (authHash == null)
            {
                throw new ArgumentNullException(nameof(authHash));
            }
            if (realHash.ToLower() != authHash.ToLower())
            {
                throw new StandardNoteAPIException("Decrypting content failed - hash mismatch");
            }

            var c = AESEncryption.DecryptCBC256(Convert.FromBase64String(encContent.Substring(3)), ek, null);

            return(Encoding.UTF8.GetString(c));
        }
コード例 #18
0
        /// <summary>
        /// 并行下载歌词任务
        /// </summary>
        /// <param name="down">插件</param>
        /// <param name="list">待下载列表</param>
        private async void parallelDownLoadLryic(Dictionary <int, MusicInfoModel> list, IPlug_Lrc down)
        {
            setBottomStatusText(StatusHeadEnum.NORMAL, "正在下载歌词...");
            progress_DownLoad.Maximum = list.Count; progress_DownLoad.Value = 0;
            await Task.Run(() =>
            {
                disEnabledButton();
                Parallel.ForEach(list, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = SettingManager.SetValue.DownloadThreadNum
                }, (item) =>
                {
                    string _path = Path.GetDirectoryName(item.Value.Path) + @"\" + Path.GetFileNameWithoutExtension(item.Value.Path) + ".lrc";
                    if (SettingManager.SetValue.IsIgnoreExitsFile && File.Exists(_path))
                    {
                        listView_MusicInfos.Items[item.Key].SubItems[6].Text = "略过";
                    }
                    else
                    {
                        byte[] _lrcData;
                        if (down.DownLoad(item.Value.Artist, item.Value.SongName, out _lrcData, SettingManager.SetValue.IsDownTranslate))
                        {
                            string _lrcPath = null;

                            #region > 输出方式 <
                            if (SettingManager.SetValue.UserDirectory.Equals(string.Empty)) // 同目录
                            {
                                _lrcPath = Path.GetDirectoryName(item.Value.Path) + @"\" + Path.GetFileNameWithoutExtension(item.Value.Path) + ".lrc";
                            }
                            else // 自定义目录
                            {
                                _lrcPath = Path.Combine(SettingManager.SetValue.UserDirectory, Path.GetFileNameWithoutExtension(item.Value.Path) + ".lrc");
                            }
                            #endregion

                            EncodingConverter _convert = getEncodingConvert();
                            _lrcData = _convert.ConvertBytes(_lrcData, SettingManager.SetValue.EncodingName);

                            FileUtils.WriteFile(_lrcPath, _lrcData);
                            listView_MusicInfos.Items[item.Key].SubItems[6].Text = "成功";
                        }
                        else
                        {
                            listView_MusicInfos.Items[item.Key].SubItems[6].Text = "失败";
                        }
                    }
                    progress_DownLoad.Value += 1;
                });
                setBottomStatusText(StatusHeadEnum.SUCCESS, "歌词下载完成!");
                enabledButton();
            });
        }
コード例 #19
0
        public static (byte[] mk, byte[] sp, string reqpw) CreateAuthData004(StandardNoteAPI.APIResultAuthParams apiparams, string mail, string uip)
        {
            var salt = StandardNoteCrypt.SHA256Bytes(string.Join(":", apiparams.identifier, apiparams.pw_nonce)).Take(128 / 8).ToArray();

            var derivedKey = ANCrypt.Argon2(Encoding.UTF8.GetBytes(uip), salt, 5, 64 * 1024, 64);

            var masterKey      = derivedKey.Skip(00).Take(32).ToArray();
            var serverPassword = derivedKey.Skip(32).Take(32).ToArray();

            var requestPassword = EncodingConverter.ByteToHexBitFiddleLowercase(serverPassword);

            return(masterKey, serverPassword, requestPassword);
        }
コード例 #20
0
        private static string Encrypt003(string string_to_encrypt, Guid uuid, byte[] encryption_key, byte[] auth_key)
        {
            byte[] IV = new byte[128 / 8];
            RNG.GetBytes(IV);

            var ciphertext = AESEncryption.EncryptCBC256(Encoding.UTF8.GetBytes(string_to_encrypt), encryption_key, IV);

            var string_to_auth = $"003:{uuid:D}:{EncodingConverter.ByteToHexBitFiddleLowercase(IV)}:{Convert.ToBase64String(ciphertext)}";

            var auth_hash = EncodingConverter.ByteToHexBitFiddleLowercase(AuthSHA256(Encoding.UTF8.GetBytes(string_to_auth), auth_key));

            return($"003:{auth_hash}:{uuid:D}:{EncodingConverter.ByteToHexBitFiddleLowercase(IV)}:{Convert.ToBase64String(ciphertext)}");
        }
コード例 #21
0
ファイル: EncodingAttribute.cs プロジェクト: volt72/psmsi
        /// <summary>
        /// Transforms a string or integer to an <see cref="System.Text.Encoding"/>.
        /// </summary>
        /// <param name="engineIntrinsics">Provides access to the APIs for managing the transformation context.</param>
        /// <param name="inputData">The parameter argument that is to be transformed.</param>
        /// <returns>The transformed object.</returns>
        public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
        {
            if (null != inputData)
            {
                var converter = new EncodingConverter();
                if (converter.CanConvertFrom(inputData.GetType()))
                {
                    return(converter.ConvertFrom(inputData));
                }
            }

            return(inputData);
        }
コード例 #22
0
ファイル: EncodingAttribute.cs プロジェクト: heaths/psmsi
        /// <summary>
        /// Transforms a string or integer to an <see cref="System.Text.Encoding"/>.
        /// </summary>
        /// <param name="engineIntrinsics">Provides access to the APIs for managing the transformation context.</param>
        /// <param name="inputData">The parameter argument that is to be transformed.</param>
        /// <returns>The transformed object.</returns>
        public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
        {
            if (null != inputData)
            {
                var converter = new EncodingConverter();
                if (converter.CanConvertFrom(inputData.GetType()))
                {
                    return converter.ConvertFrom(inputData);
                }
            }

            return inputData;
        }
コード例 #23
0
        public XElement Serialize()
        {
            var x = new XElement("itemskey",
                                 new XAttribute("ID", UUID.ToString("P")),
                                 new XAttribute("Version", Version),
                                 new XAttribute("AuthKey", EncodingConverter.ByteToHexBitFiddleUppercase(AuthKey ?? new byte[0])),
                                 new XAttribute("Default", IsDefault),
                                 new XAttribute("CreationDate", CreationDate.ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz", CultureInfo.InvariantCulture)),
                                 new XAttribute("ModificationDate", ModificationDate.ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz", CultureInfo.InvariantCulture)),
                                 new XAttribute("AppData", RawAppData),
                                 EncodingConverter.ByteToHexBitFiddleUppercase(Key));

            return(x);
        }
コード例 #24
0
        public string ReadString0()
        {
            int offset = this._offset;

            try
            {
                while (_buffer[_offset++] != 0)
                {
                }
            }
            catch {
                _offset = _buffer.Length;
            }
            return(EncodingConverter.GetString(_buffer, offset, this._offset - offset - 1));
        }
コード例 #25
0
ファイル: SessionManager.cs プロジェクト: kephax/Notepads
        /// <summary>
        /// Do not call this constructor directly. Use <see cref="SessionUtility.GetSessionManager(INotepadsCore)" instead./>
        /// </summary>
        public SessionManager(INotepadsCore notepadsCore)
        {
            _notepadsCore      = notepadsCore;
            _semaphoreSlim     = new SemaphoreSlim(1, 1);
            _encodingConverter = new EncodingConverter();
            _sessionData       = new ConcurrentDictionary <Guid, TextEditorSessionData>();
            _loaded            = false;

            foreach (var editor in _notepadsCore.GetAllTextEditors())
            {
                BindEditorStateChangeEvent(this, editor);
            }

            _notepadsCore.TextEditorLoaded   += BindEditorStateChangeEvent;
            _notepadsCore.TextEditorUnloaded += UnbindEditorStateChangeEvent;
        }
コード例 #26
0
        public static (byte[] pw, byte[] mk, byte[] ak, string reqpw) CreateAuthData002(StandardNoteAPI.APIResultAuthParams apiparams, string uip)
        {
            if (apiparams.pw_func != StandardNoteAPI.PasswordFunc.pbkdf2)
            {
                throw new Exception("Unknown pw_func: " + apiparams.pw_func);
            }

            byte[] bytes = PBKDF2.GenerateDerivedKey(768 / 8, Encoding.UTF8.GetBytes(uip), Encoding.UTF8.GetBytes(apiparams.pw_salt), apiparams.pw_cost, PBKDF2.HMACType.SHA512);

            var pw = bytes.Skip(0 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();
            var mk = bytes.Skip(1 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();
            var ak = bytes.Skip(2 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();

            var reqpw = EncodingConverter.ByteToHexBitFiddleUppercase(pw).ToLower();

            return(pw, mk, ak, reqpw);
        }
        public void EncodingConverter_ConvertUtf8StringToIsoBytes_Espanol()
        {
            var ec     = new EncodingConverter();
            var result = ec.ConvertUtf8StringToIsoBytes("español.ct");

            Assert.AreEqual(_espanolIsoBytes.Length, result.Length);
            Assert.AreEqual(_espanolIsoBytes[0], result[0]);
            Assert.AreEqual(_espanolIsoBytes[1], result[1]);
            Assert.AreEqual(_espanolIsoBytes[2], result[2]);
            Assert.AreEqual(_espanolIsoBytes[3], result[3]);
            Assert.AreEqual(_espanolIsoBytes[4], result[4]);
            Assert.AreEqual(_espanolIsoBytes[5], result[5]);
            Assert.AreEqual(_espanolIsoBytes[6], result[6]);
            Assert.AreEqual(_espanolIsoBytes[7], result[7]);
            Assert.AreEqual(_espanolIsoBytes[8], result[8]);
            Assert.AreEqual(_espanolIsoBytes[9], result[9]);
        }
コード例 #28
0
        private static string DecryptContent001(string encContent, string encItemKey, string authHash, byte[] masterkey)
        {
            var itemKey = EncodingConverter.StringToByteArrayCaseInsensitive(Encoding.ASCII.GetString(AESEncryption.DecryptCBC256(Convert.FromBase64String(encItemKey), masterkey, new byte[16])));

            var ek = itemKey.Take(itemKey.Length / 2).ToArray();
            var ak = itemKey.Skip(itemKey.Length / 2).ToArray();

            var realHash = EncodingConverter.ByteToHexBitFiddleLowercase(AuthSHA256(Encoding.UTF8.GetBytes(encContent), ak));

            if (realHash.ToLower() != authHash.ToLower())
            {
                throw new StandardNoteAPIException("Decrypting content failed - hash mismatch");
            }

            var c = AESEncryption.DecryptCBC256(Convert.FromBase64String(encContent.Substring(3)), ek, null);

            return(Encoding.UTF8.GetString(c));
        }
コード例 #29
0
        private static string Decrypt004(string encContent, byte[] key)
        {
            var split = encContent.Split(':');

            var version            = split[0];
            var nonce              = EncodingConverter.StringToByteArrayCaseInsensitive(split[1]);
            var ciphertext         = Convert.FromBase64String(split[2]);
            var authenticated_data = Encoding.UTF8.GetBytes(split[3]);

            if (version != "004")
            {
                throw new StandardNoteAPIException($"Version must be 004 to decrypt 004 encrypted item (duh.)");
            }

            var plain = ANCrypt.XChaCha20Decrypt(ciphertext, nonce, key, authenticated_data);

            return(Encoding.UTF8.GetString(plain));
        }
コード例 #30
0
        public static StandardFileItemsKey Deserialize(XElement e)
        {
            var id      = XHelper.GetAttributeGuid(e, "ID");
            var version = XHelper.GetAttributeString(e, "Version");
            var defKey  = XHelper.GetAttributeBool(e, "Default");
            var cdate   = XHelper.GetAttributeDateTimeOffsetOrDefault(e, "CreationDate", DateTimeOffset.MinValue);
            var mdate   = XHelper.GetAttributeDateTimeOffsetOrDefault(e, "ModificationDate", DateTimeOffset.Now);
            var appdata = XHelper.GetAttributeString(e, "AppData");
            var key     = EncodingConverter.StringToByteArrayCaseInsensitive(e.Value);
            var authkey = EncodingConverter.StringToByteArrayCaseInsensitive(XHelper.GetAttributeStringOrDefault(e, "AuthKey", ""));

            if (authkey.Length == 0)
            {
                authkey = null;
            }

            return(new StandardFileItemsKey(id, version, cdate, mdate, key, authkey, defKey, appdata));
        }
コード例 #31
0
        public static (byte[] pw, byte[] mk, byte[] ak, string reqpw) CreateAuthData003(StandardNoteAPI.APIResultAuthParams apiparams, string mail, string uip)
        {
            if (apiparams.pw_cost < 100000)
            {
                throw new StandardNoteAPIException($"Account pw_cost is too small ({apiparams.pw_cost})");
            }

            var salt = StandardNoteCrypt.SHA256Hex(string.Join(":", mail, "SF", "003", apiparams.pw_cost.ToString(), apiparams.pw_nonce));

            byte[] bytes = PBKDF2.GenerateDerivedKey(768 / 8, Encoding.UTF8.GetBytes(uip), Encoding.UTF8.GetBytes(salt), apiparams.pw_cost, PBKDF2.HMACType.SHA512);

            var pw = bytes.Skip(0 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();
            var mk = bytes.Skip(1 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();
            var ak = bytes.Skip(2 * (bytes.Length / 3)).Take(bytes.Length / 3).ToArray();

            var reqpw = EncodingConverter.ByteToHexBitFiddleUppercase(pw).ToLower();

            return(pw, mk, ak, reqpw);
        }