Exemplo n.º 1
0
        public static long HashSHA1AsLong(ReadOnlySpan <byte> src)
        {
            byte[] hash = Secure.HashSHA1(src);
            long   ret  = hash._GetSInt64();

            if (ret == 0)
            {
                ret = 1;
            }
            return(ret);
        }
Exemplo n.º 2
0
        public static int HashSHA1AsSInt31(ReadOnlySpan <byte> src)
        {
            byte[] hash = Secure.HashSHA1(src);
            int    ret  = (int)(hash._GetSInt64() & 0x7fffffffL);

            if (ret == 0)
            {
                ret = 1;
            }
            return(ret);
        }
Exemplo n.º 3
0
        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());
        }
Exemplo n.º 4
0
        public CertificateOptions(PkiAlgorithm algorithm, string?cn = null, string?o = null, string?ou = null, string?c = null,
                                  string?st            = null, string?l = null, string?e = null,
                                  Memory <byte> serial = default, DateTimeOffset?expires     = null, string[]?subjectAltNames = null, PkiShaSize shaSize = PkiShaSize.SHA256,
                                  int keyUsages        = 0, KeyPurposeID[]?extendedKeyUsages = null)
        {
            this.Algorithm = algorithm;
            this.CN        = cn._NonNullTrim();
            this.O         = o._NonNullTrim();
            this.OU        = ou._NonNullTrim();
            this.C         = c._NonNullTrim();
            this.ST        = st._NonNullTrim();
            this.L         = l._NonNullTrim();
            this.E         = e._NonNullTrim();
            this.Serial    = serial._CloneMemory();
            this.ShaSize   = shaSize;
            if (this.Serial.IsEmpty)
            {
                this.Serial         = Secure.Rand(16);
                this.Serial.Span[0] = (byte)(this.Serial.Span[0] & 0x7f);
            }
            this.Expires = expires ?? Util.MaxDateTimeOffsetValue;
            this.SubjectAlternativeNames.Add(this.CN);


            if (keyUsages == 0)
            {
                keyUsages = KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyEncipherment | KeyUsage.DataEncipherment | KeyUsage.KeyCertSign | KeyUsage.CrlSign;
            }

            this.KeyUsages = keyUsages;


            if (extendedKeyUsages == null)
            {
                extendedKeyUsages = new KeyPurposeID[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPCodeSigning, KeyPurposeID.IdKPEmailProtection,
                                                         KeyPurposeID.IdKPIpsecEndSystem, KeyPurposeID.IdKPIpsecTunnel, KeyPurposeID.IdKPIpsecUser, KeyPurposeID.IdKPTimeStamping, KeyPurposeID.IdKPOcspSigning };
            }
            this.ExtendedKeyUsages = extendedKeyUsages;


            if (subjectAltNames != null)
            {
                subjectAltNames.Where(x => x._IsEmpty() == false)._DoForEach(x => this.SubjectAlternativeNames.Add(x.Trim()));
            }
        }
Exemplo n.º 5
0
        public static string JavaScriptEasyStrEncrypt(string?srcString, string?password)
        {
            srcString = srcString._NonNull();
            password  = password._NonNull();

            using var aes = Aes.Create();
            aes.Mode      = CipherMode.CBC;
            aes.KeySize   = 256;
            aes.BlockSize = 128;
            aes.Padding   = PaddingMode.PKCS7;
            aes.IV        = Secure.HashSHA256(("1" + password)._GetBytes_UTF8()).AsSpan(0, 128 / 8).ToArray();
            aes.Key       = Secure.HashSHA256(("2" + password)._GetBytes_UTF8()).AsSpan(0, 256 / 8).ToArray();

            using var mem    = new MemoryStream();
            using var enc    = aes.CreateEncryptor();
            using var stream = new CryptoStream(mem, enc, CryptoStreamMode.Write);

            stream.Write(srcString._GetBytes_UTF8());
            stream.FlushFinalBlock();

            return(mem.ToArray()._GetHexString()._JavaScriptSafeStrEncode());
        }
Exemplo n.º 6
0
        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.MemEquals(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);
        }
Exemplo n.º 7
0
        // 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(randSize);

            Buf b = new Buf();

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

            return(b.ByteData);
        }
Exemplo n.º 8
0
        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);
        }
Exemplo n.º 9
0
        public PalX509Certificate(ReadOnlySpan <byte> pkcs12Data, string?password = null)
        {
            NativeCertificate = Secure.LoadPkcs12(pkcs12Data.ToArray(), password);

            InitFields();
        }
Exemplo n.º 10
0
        // リアルタイムバッファ監視タスク
        async Task EasyRealtimeBufferMainteTaskAsync(CancellationToken cancel)
        {
            // delay time
            int delay = this.Options.EasyRealtimeRecvBufCallbackDelayTickMsecs;

            delay = Math.Max(delay, 10);

            int interval = Math.Max(delay / 10, 1);

            long lastHash       = Secure.RandSInt64_Caution();
            long lastStableTick = 0;

            while (cancel.IsCancellationRequested == false && Proc.HasExited == false)
            {
                long currentHash;
                long currentTick;

                ReadOnlyMemory <byte> currentMemOutput;
                ReadOnlyMemory <byte> currentMemErr;

                lock (this.EasyRealtimeBufLock)
                {
                    MemoryBuffer <byte> tmp = new MemoryBuffer <byte>();
                    tmp.Write(this.EasyErrRealtimeBuf.Span);
                    tmp.WriteStr("----test----");
                    tmp.Write(this.EasyOutputRealtimeBuf.Span);
                    currentHash = Secure.HashSHA1AsLong(tmp.Span);
                    currentTick = this.EasyRealtimeBufLastWriteTick;

                    currentMemOutput = this.EasyOutputRealtimeBuf.Clone();
                    currentMemErr    = this.EasyErrRealtimeBuf.Clone();
                }

                bool exit = false;

                if (lastHash != currentHash)
                {
                    //Dbg.Where();
                    lastHash       = currentHash;
                    lastStableTick = currentTick;
                }
                else
                {
                    //Dbg.Where($"lastStableTick = {lastStableTick}, currentTick = {Time.Tick64}, lastHash = {lastHash}");
                    if ((lastStableTick + delay) <= Time.Tick64)
                    {
                        //Dbg.Where("**********");
                        try
                        {
                            bool ret = await this.Options.EasyRealtimeRecvBufCallbackAsync !(currentMemOutput, currentMemErr);
                            exit = ret;
                        }
                        catch (Exception ex)
                        {
                            ex._Debug();
                            exit = true;
                        }
                    }
                }

                if (exit)
                {
                    //Dbg.Where();
                    TaskUtil.StartAsyncTaskAsync(async() =>
                    {
                        await Task.Yield();
                        KillProcessInternal();
                        await Task.CompletedTask;
                    })._LaissezFaire(true);

                    return;
                }

                await cancel._WaitUntilCanceledAsync(interval);
            }
        }
Exemplo n.º 11
0
        public async Task StartWebSocketClientAsync(string uri, CancellationToken cancel = default)
        {
            if (Started.IsFirstCall() == false)
            {
                throw new ApplicationException("Already started.");
            }

            LowerStream.ReadTimeout  = Options.TimeoutOpen;
            LowerStream.WriteTimeout = Options.TimeoutOpen;

            Uri u = new Uri(uri);
            HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, uri);

            byte[] nonce      = Secure.Rand(16);
            string requestKey = Convert.ToBase64String(nonce);

            req.Headers.Add("Host", u.Host);
            req.Headers.Add("User-Agent", Options.UserAgent);
            req.Headers.Add("Accept", Consts.MimeTypes.Html);
            req.Headers.Add("Sec-WebSocket-Version", "13");
            req.Headers.Add("Origin", "null");
            req.Headers.Add("Sec-WebSocket-Key", requestKey);
            req.Headers.Add("Connection", "keep-alive, Upgrade");
            req.Headers.Add("Pragma", "no-cache");
            req.Headers.Add("Cache-Control", "no-cache");
            req.Headers.Add("Upgrade", "websocket");

            StringWriter tmpWriter = new StringWriter();

            tmpWriter.WriteLine($"{req.Method} {req.RequestUri.PathAndQuery} HTTP/1.1");
            tmpWriter.WriteLine(req.Headers.ToString());

            await LowerStream.WriteAsync(tmpWriter.ToString()._GetBytes_UTF8(), cancel);

            Dictionary <string, string> headers = new Dictionary <string, string>(StrComparer.IgnoreCaseComparer);
            int num          = 0;
            int responseCode = 0;

            StreamReader tmpReader = new StreamReader(LowerStream);

            while (true)
            {
                string line = await TaskUtil.DoAsyncWithTimeout((procCancel) => tmpReader.ReadLineAsync(),
                                                                timeout : Options.TimeoutOpen,
                                                                cancel : cancel);

                if (line == "")
                {
                    break;
                }

                if (num == 0)
                {
                    string[] tokens = line.Split(' ');
                    if (tokens[0] != "HTTP/1.1")
                    {
                        throw new ApplicationException($"Cannot establish the WebSocket Protocol. Response: \"{tokens}\"");
                    }
                    responseCode = int.Parse(tokens[1]);
                }
                else
                {
                    string[] tokens = line.Split(':');
                    string   name   = tokens[0].Trim();
                    string   value  = tokens[1].Trim();
                    headers[name] = value;
                }

                num++;
            }

            if (responseCode != 101)
            {
                throw new ApplicationException($"Cannot establish the WebSocket Protocol. Perhaps the destination host does not support WebSocket. Wrong response code: \"{responseCode}\"");
            }

            if (headers["Upgrade"].Equals("websocket", StringComparison.InvariantCultureIgnoreCase) == false)
            {
                throw new ApplicationException($"Wrong Upgrade header: \"{headers["Upgrade"]}\"");
            }

            string acceptKey  = headers["Sec-WebSocket-Accept"];
            string keyCalcStr = requestKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            SHA1   sha1       = new SHA1Managed();
            string acceptKey2 = Convert.ToBase64String(sha1.ComputeHash(keyCalcStr._GetBytes_Ascii()));

            if (acceptKey != acceptKey2)
            {
                throw new ApplicationException($"Wrong accept_key: \'{acceptKey}\'");
            }

            this.SendTask = SendLoopAsync();
            this.RecvTask = RecvLoopAsync();
        }
Exemplo n.º 12
0
        void InitFields()
        {
            byte[] publicKeyBytes = this.CertData.CertificateStructure.SubjectPublicKeyInfo.GetDerEncoded();

            this.PublicKey = new PubKey(publicKeyBytes);

            HashSet <string> dnsNames = new HashSet <string>();

            ICollection altNamesList = this.CertData.GetSubjectAlternativeNames();

            if (altNamesList != null)
            {
                try
                {
                    foreach (List <object>?altName in altNamesList)
                    {
                        if (altName != null)
                        {
                            try
                            {
                                int type = (int)altName[0];

                                if (type == GeneralName.DnsName)
                                {
                                    string value = (string)altName[1];

                                    dnsNames.Add(value.ToLower());
                                }
                            }
                            catch { }
                        }
                    }
                }
                catch { }
            }

            IList subjectKeyList    = this.CertData.SubjectDN.GetOidList();
            IList subjectValuesList = this.CertData.SubjectDN.GetValueList();

            if (subjectKeyList != null && subjectValuesList != null)
            {
                for (int i = 0; i < subjectKeyList.Count; i++)
                {
                    try
                    {
                        DerObjectIdentifier?key = (DerObjectIdentifier?)subjectKeyList[i];
                        string?value            = (string?)subjectValuesList[i];
                        if (key != null && value != null)
                        {
                            if (key.Equals(X509Name.CN))
                            {
                                dnsNames.Add(value.ToLower());
                            }
                        }
                    }
                    catch { }
                }
            }

            this.HostNameListInternal = new List <CertificateHostName>();

            foreach (string fqdn in dnsNames)
            {
                HostNameListInternal.Add(new CertificateHostName(fqdn));
            }

            byte[] der = this.CertData.GetEncoded();

            this.DigestSHA1Data = Secure.HashSHA1(der);
            this.DigestSHA1Str  = this.DigestSHA1Data._GetHexString();

            this.DigestSHA256Data = Secure.HashSHA256(der);
            this.DigestSHA256Str  = this.DigestSHA256Data._GetHexString();

            this.DigestSHA512Data = Secure.HashSHA512(der);
            this.DigestSHA512Str  = this.DigestSHA512Data._GetHexString();
        }
Exemplo n.º 13
0
 public SeedBasedRandomGenerator(ReadOnlySpan <byte> seed)
 {
     seedPlusSeqNo = new MemoryBuffer <byte>();
     seedPlusSeqNo.WriteSInt64(0);
     seedPlusSeqNo.Write(Secure.HashSHA256(seed));
 }
Exemplo n.º 14
0
        public byte[] CalcThumbprint()
        {
            string str = this._ObjectToJson(includeNull: false, compact: true);

            return(Secure.HashSHA256(str._GetBytes_UTF8()));
        }
Exemplo n.º 15
0
        protected override async Task InitMetadataImplAsync(CancellationToken cancel = default)
        {
            Memory <byte> firstSectorData = new byte[XtsAesMetaDataSize];

            // ヘッダの読み込みを試行する
            int readSize = await this.PhysicalReadAsync(0, firstSectorData, cancel);

            if (readSize == XtsAesMetaDataSize)
            {
                var metaDataParseResult = TryParseMetaData(firstSectorData);

                metaDataParseResult.ThrowIfException();

                var metaData = metaDataParseResult.Value !;

                // パスワード検査
                if (Secure.VeritySaltedPassword(metaData.SaltedPassword, this.CurrentPassword) == false)
                {
                    throw new CoresException("XtsAesRandomAccess: Incorrect password.");
                }

                // 秘密鍵解読
                var decrypted = ChaChaPoly.EasyDecryptWithPassword(metaData.MasterKeyEncryptedByPassword._GetHexBytes(), this.CurrentPassword);
                decrypted.ThrowIfException();

                // 秘密鍵サイズ検査
                if (decrypted.Value.Length != XtsAesKeySize)
                {
                    throw new CoresException("XtsAesRandomAccess: decrypted.Value.Length != XtsAesKeySize");
                }

                this.CurrentMasterKey = decrypted.Value;

                this.CurrentMetaData = metaData;
            }
            else if (readSize == 0)
            {
                // ファイルの内容が存在しない

                // マスターキーを新規作成する
                this.CurrentMasterKey = Secure.Rand(XtsAesKeySize);

                // メタデータを新規作成する
                var metaData = new XtsAesRandomAccessMetaData
                {
                    Version        = 1,
                    VirtualSize    = 0,
                    SaltedPassword = Secure.SaltPassword(this.CurrentPassword),
                    MasterKeyEncryptedByPassword = ChaChaPoly.EasyEncryptWithPassword(this.CurrentMasterKey, this.CurrentPassword)._GetHexString(),
                };

                this.CurrentMetaData = metaData;

                // メタデータを書き込みする
                await WriteMetaDataAsync(cancel);
            }
            else
            {
                // 不正 ここには来ないはず
                throw new CoresException($"XtsAesRandomAccess: Invalid readSize: {readSize}");
            }

            // XTS を作成
            this.CurrentXts        = XtsAes256.Create(this.CurrentMasterKey.ToArray());
            this.CurrentEncrypter  = this.CurrentXts.CreateEncryptor();
            this.CurrentDescrypter = this.CurrentXts.CreateDecryptor();
        }