public static string SaltPassword(string password, byte[] salt = null)
        {
            if (salt == null)
            {
                salt = Secure.Rand(PasswordSaltSize);
            }

            byte[] pw  = password.NonNull().GetBytes_UTF8();
            byte[] src = pw;

            for (int i = 0; i < PasswordIterations; i++)
            {
                src = Secure.HashSHA256(src.CombineByte(salt));
            }

            return(src.CombineByte(salt).GetHexString());
        }
        // ファイルから読み込み (ハッシュ調べる)
        public static Buf ReadFromFileWithHash(string filename)
        {
            byte[] filedata = IO.ReadFile(filename);
            if (filedata.Length < 20)
            {
                throw new ApplicationException("filedata.Length < 20");
            }
            byte[] hash  = Util.CopyByte(filedata, 0, 20);
            byte[] data  = Util.CopyByte(filedata, 20);
            byte[] hash2 = Secure.HashSHA1(data);

            if (Util.CompareByte(hash, hash2) == false)
            {
                throw new ApplicationException("hash mismatch");
            }

            return(new Buf(data));
        }
Beispiel #3
0
        public static string GeneratePacket(Pack pack, Cert cert, Rsa key)
        {
            Buf b = new Buf();

            byte[] pack_data = pack.WriteToBuf().ByteData;
            WpcEntry.AddDataEntry(b, "PACK", pack_data);

            byte[] hash = Secure.HashSHA1(pack_data);
            WpcEntry.AddDataEntry(b, "HASH", hash);

            if (cert != null && key != null)
            {
                WpcEntry.AddDataEntry(b, "CERT", cert.ByteData);
                WpcEntry.AddDataEntry(b, "SIGN", key.SignData(hash));
            }

            return(Str.AsciiEncoding.GetString(b.ByteData));
        }
        public async Task TranAsync(IsolationLevel iso, DeadlockRetryConfig retry_config, TransactionalTaskAsync task)
        {
            await EnsureOpenAsync();

            if (retry_config == null)
            {
                retry_config = this.DeadlockRetryConfig;
            }

            int num_retry = 0;

LABEL_RETRY:
            try
            {
                using (UsingTran u = this.UsingTran(iso))
                {
                    if (await task())
                    {
                        u.Commit();
                    }
                }
            }
            catch (SqlException sqlex)
            {
                if (sqlex.Number == 1205)
                {
                    // デッドロック発生
                    num_retry++;
                    if (num_retry <= retry_config.RetryCount)
                    {
                        await Task.Delay(Secure.Rand31i() % retry_config.RetryAverageInterval);

                        goto LABEL_RETRY;
                    }

                    throw;
                }
                else
                {
                    throw;
                }
            }
        }
        public void Tran(IsolationLevel iso, DeadlockRetryConfig retry_config, TransactionalTask task)
        {
            EnsureOpen();
            if (retry_config == null)
            {
                retry_config = this.DeadlockRetryConfig;
            }

            int num_retry = 0;

LABEL_RETRY:
            try
            {
                using (UsingTran u = this.UsingTran(iso))
                {
                    if (task())
                    {
                        u.Commit();
                    }
                }
            }
            catch (SqlException sqlex)
            {
                if (sqlex.Number == 1205)
                {
                    // デッドロック発生
                    num_retry++;
                    if (num_retry <= retry_config.RetryCount)
                    {
                        Kernel.SleepThread(Secure.Rand31i() % retry_config.RetryAverageInterval);

                        goto LABEL_RETRY;
                    }

                    throw;
                }
                else
                {
                    throw;
                }
            }
        }
        public static FullRouteIPInfoCache LoadFromBuf(Buf b)
        {
            b.Seek(b.Size - 20, SeekOrigin.Begin);
            byte[] hash = b.Read(20);
            b.SeekToBegin();
            byte[] hash2 = Secure.HashSHA1(Util.CopyByte(b.ByteData, 0, (int)b.Size - 20));

            if (Util.CompareByte(hash, hash2) == false)
            {
                throw new ApplicationException("Invalid Hash");
            }

            FullRouteIPInfoCache ret = new FullRouteIPInfoCache();

            ret.TimeStamp = new DateTime((long)b.ReadInt64());
            int num = (int)b.ReadInt();

            int i;

            for (i = 0; i < num; i++)
            {
                FullRouteIPInfoEntry e = new FullRouteIPInfoEntry();
                e.From        = b.ReadInt();
                e.To          = b.ReadInt();
                e.Registry    = b.ReadStr();
                e.Assigned    = b.ReadInt();
                e.Country2    = b.ReadStr();
                e.Country3    = b.ReadStr();
                e.CountryFull = DeleteSemi(b.ReadStr());
                ret.EntryList.Add(e);
            }

            ret.EntryList.Sort();

            ret.build_country_code_to_name_db();

            return(ret);
        }
        // PKCS パディング
        public static byte[] PkcsPadding(byte[] srcData, int destSize)
        {
            int srcSize = srcData.Length;

            if ((srcSize + 11) > destSize)
            {
                throw new OverflowException();
            }

            int randSize = destSize - srcSize - 3;

            byte[] rand = Secure.Rand((uint)randSize);

            Buf b = new Buf();

            b.WriteByte(0x00);
            b.WriteByte(0x02);
            b.Write(rand);
            b.WriteByte(0x00);
            b.Write(srcData);

            return(b.ByteData);
        }
        public Buf SaveToBuf()
        {
            Buf b = new Buf();

            b.WriteInt64((ulong)this.TimeStamp.Ticks);
            b.WriteInt((uint)this.EntryList.Count);

            foreach (FullRouteIPInfoEntry e in this.EntryList)
            {
                b.WriteInt(e.From);
                b.WriteInt(e.To);
                b.WriteStr(e.Registry);
                b.WriteInt(e.Assigned);
                b.WriteStr(e.Country2);
                b.WriteStr(e.Country3);
                b.WriteStr(e.CountryFull);
            }

            b.Write(Secure.HashSHA1(b.ByteData));

            b.SeekToBegin();

            return(b);
        }
Beispiel #9
0
        // 初期化
        static Env()
        {
            FrameworkVersion = Environment.Version;
            if (FrameworkInfoString.StartsWith(".NET Core", StringComparison.InvariantCultureIgnoreCase))
            {
                IsDotNetCore = true;
            }
            OsInfo    = Environment.OSVersion;
            IsWindows = (OsInfo.Platform == PlatformID.Win32NT);
            if (IsUnix)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    IsLinux = true;
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    IsMac = true;
                }
            }

            PathSeparator = "" + Path.DirectorySeparatorChar;
            if (Str.IsEmptyStr(PathSeparator))
            {
                PathSeparator = "/";
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    PathSeparator = "\\";
                }
            }
            ExeFileName = IO.RemoveLastEnMark(getMyExeFileName());
            if (Str.IsEmptyStr(ExeFileName) == false)
            {
                AppRootDir = ExeFileDir = IO.RemoveLastEnMark(System.AppContext.BaseDirectory);
                // プログラムのあるディレクトリから 1 つずつ遡ってアプリケーションの root ディレクトリを取得する
                string tmp = ExeFileDir;
                while (true)
                {
                    try
                    {
                        tmp = Path.GetDirectoryName(tmp);
                        if (File.Exists(Path.Combine(tmp, "approot")) || File.Exists(Path.Combine(tmp, "appsettings.json")) || File.Exists(Path.Combine(tmp, "appsettings.Development.json")))
                        {
                            AppRootDir = tmp;
                            break;
                        }
                    }
                    catch
                    {
                        break;
                    }
                }
            }
            else
            {
                ExeFileName = "/tmp/dummyexe";
                ExeFileDir  = "/tmp";
                AppRootDir  = IO.RemoveLastEnMark(Environment.CurrentDirectory);
            }
            HomeDir = IO.RemoveLastEnMark(Kernel.GetEnvStr("HOME"));
            if (Str.IsEmptyStr(HomeDir))
            {
                HomeDir = IO.RemoveLastEnMark(Kernel.GetEnvStr("HOMEDRIVE") + Kernel.GetEnvStr("HOMEPATH"));
            }
            if (Str.IsEmptyStr(HomeDir) == false)
            {
                UnixMutantDir = Path.Combine(HomeDir, ".dnmutant");
            }
            else
            {
                HomeDir = AppRootDir;
                if (IsUnix)
                {
                    UnixMutantDir = Path.Combine("/tmp", ".dnmutant");
                }
            }
            if (IsWindows)
            {
                UnixMutantDir = "";
            }
            if (Str.IsEmptyStr(UnixMutantDir) == false)
            {
                IO.MakeDirIfNotExists(UnixMutantDir);
            }
            if (IsWindows)
            {
                // Windows
                SystemDir  = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.System));
                WindowsDir = IO.RemoveLastEnMark(Path.GetDirectoryName(SystemDir));
                TempDir    = IO.RemoveLastEnMark(Path.GetTempPath());
                WinTempDir = IO.RemoveLastEnMark(Path.Combine(WindowsDir, "Temp"));
                IO.MakeDir(WinTempDir);
                if (WindowsDir.Length >= 2 && WindowsDir[1] == ':')
                {
                    WindowsDir = WindowsDir.Substring(0, 2).ToUpper();
                }
                else
                {
                    WindowsDrive = "C:";
                }
            }
            else
            {
                // UNIX
                SystemDir    = "/bin";
                WindowsDir   = "/bin";
                WindowsDrive = "/";
                if (Str.IsEmptyStr(HomeDir) == false)
                {
                    TempDir = Path.Combine(HomeDir, ".dntmp");
                }
                else
                {
                    TempDir = "/tmp";
                }
                WinTempDir = TempDir;
            }
            ProgramFilesDir      = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
            PersonalStartMenuDir = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu));
            PersonalProgramsDir  = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.Programs));
            PersonalStartupDir   = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.Startup));
            PersonalAppDataDir   = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
            PersonalDesktopDir   = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
            MyDocumentsDir       = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            LocalAppDataDir      = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
            if (IsUnix)
            {
                // ダミーディレクトリ
                SystemDir            = "/bin";
                WindowsDir           = "/bin";
                WindowsDrive         = "/";
                ProgramFilesDir      = "/bin";
                PersonalStartMenuDir = Path.Combine(HomeDir, "dummy/starmenu");
                PersonalProgramsDir  = Path.Combine(HomeDir, "dummy/starmenu/programs");
                PersonalStartupDir   = Path.Combine(HomeDir, "dummy/starmenu/startup");
                LocalAppDataDir      = PersonalAppDataDir = Path.Combine(HomeDir, ".dnappdata");
                PersonalDesktopDir   = Path.Combine(HomeDir, "dummy/desktop");
                MyDocumentsDir       = HomeDir;
            }
            StartupCurrentDir = CurrentDir;
            UserName          = Environment.UserName;
            try
            {
                UserNameEx = Environment.UserDomainName + "\\" + UserName;
            }
            catch
            {
                UserNameEx = UserName;
            }
            MachineName    = Environment.MachineName;
            CommandLine    = initCommandLine(Environment.CommandLine);
            IsLittleEndian = BitConverter.IsLittleEndian;
            ProcessId      = System.Diagnostics.Process.GetCurrentProcess().Id;
            IsAdmin        = checkIsAdmin();

            // 自分用の temp ディレクトリの初期化
            try
            {
                deleteUnusedTempDir();
            }
            catch
            {
            }

            int num = 0;

            while (true)
            {
                byte[] rand = Secure.Rand(2);
                string tmp2 = Str.ByteToStr(rand);

                string tmp = Path.Combine(Env.TempDir, "NET_" + tmp2);

                if (IO.IsDirExists(tmp) == false && IO.MakeDir(tmp))
                {
                    Env.MyTempDir = tmp;

                    break;
                }

                if ((num++) >= 100)
                {
                    throw new SystemException();
                }
            }

            if (IsWindows)
            {
                UnixMutantDir = Env.MyTempDir;
            }

            // ロックファイルの作成
            string lockFileName = Path.Combine(Env.MyTempDir, "LockFile.dat");

            lockFile = IO.FileCreate(lockFileName, Env.IsUnix);
        }
 public bool VerifyData(byte[] data, byte[] sign)
 {
     byte[] hash = Secure.HashSHA1(data);
     return(VerifyHash(hash, sign));
 }
 public byte[] SignData(byte[] data)
 {
     byte[] hash = Secure.HashSHA1(data);
     return(SignHash(hash));
 }
Beispiel #12
0
        public static WpcPacket ParsePacket(string recvStr)
        {
            List <WpcEntry> o = WpcEntry.ParseDataEntry(recvStr);

            WpcEntry e;

            try
            {
                e = WpcEntry.FindEntry(o, "PACK");
                if (e != null)
                {
                    byte[] hash = Secure.HashSHA1(e.Data);
                    Pack   pack = null;

                    pack = Pack.CreateFromBuf(new Buf(e.Data));

                    e = WpcEntry.FindEntry(o, "HASH");

                    if (e != null)
                    {
                        byte[] hash2 = e.Data;

                        if (Util.CompareByte(hash, hash2))
                        {
                            e = WpcEntry.FindEntry(o, "CERT");
                            if (e != null)
                            {
                                Cert cert;

                                try
                                {
                                    cert = new Cert(e.Data);
                                }
                                catch
                                {
                                    return(null);
                                }

                                e = WpcEntry.FindEntry(o, "SIGN");
                                if (e != null)
                                {
                                    byte[] sign = e.Data;

                                    if (cert.RsaPublicKey.VerifyData(hash2, sign))
                                    {
                                        return(new WpcPacket(pack, hash2, cert, sign));
                                    }
                                }
                            }
                            else
                            {
                                return(new WpcPacket(pack, hash2));
                            }
                        }
                    }
                }
            }
            catch (OverflowException)
            {
                return(null);
            }

            return(null);
        }