Esempio n. 1
0
 public UserDB(Configurator conf)
 {
     this._config = conf;
     this._sha = SHA512.Create();
     try
     {	this.BuildDBConnectionString(conf);
         this._dbcon = new NpgsqlConnection(this._db_connection_string);
         this._cmd = this._dbcon.CreateCommand();
         this._dbcon.Open();
         this.CheckForTable();
     }
     catch(Exception e)
     {
         Logger.log("Failed to establish connection: "+e.Message+"\n"+e.StackTrace, Logger.Verbosity.moderate);
         throw new FatalException("UserManager failed to connect to the database. (Reason: "+e.Message+")");
     }
 }
 public void CreateIncorrect()
 {
     // try to build an incorrect hash algorithms
     hash = SHA512.Create("MD5");
 }
Esempio n. 3
0
 /// <summary>
 /// SHA512 加密
 /// </summary>
 /// <param name="input"> 要加密的字符串 </param>
 /// <param name="encoding"> 字符编码 </param>
 /// <returns></returns>
 public static string SHA512Encrypt(string input, Encoding encoding)
 {
     return HashEncrypt(SHA512.Create(), input, encoding);
 }
Esempio n. 4
0
 public static byte[] Compute(byte[] input, int offset, int count)
 {
     using var sha512 = SHA512.Create();
     return(sha512.ComputeHash(input, offset, count));
 }
Esempio n. 5
0
 public CryptoUtility()
 {
     this.hashAlgorithm = SHA512.Create();
 }
Esempio n. 6
0
        public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm)
        {
            byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign");

            // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses.
            byte[]       dataArray  = new byte[33333];
            MemoryStream dataStream = new MemoryStream(dataArray, true);

            while (dataStream.Position < dataArray.Length - data.Length)
            {
                dataStream.Write(data, 0, data.Length);
            }

            dataStream.Position = 0;

            byte[] dataArray2 = new byte[dataArray.Length + 2];
            dataArray.CopyTo(dataArray2, 1);
            ArraySegment <byte> dataSpan = new ArraySegment <byte>(dataArray2, 1, dataArray.Length);

            HashAlgorithm halg;

            if (hashAlgorithm == HashAlgorithmName.MD5)
            {
                halg = MD5.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA1)
            {
                halg = SHA1.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA256)
            {
                halg = SHA256.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA384)
            {
                halg = SHA384.Create();
            }
            else if (hashAlgorithm == HashAlgorithmName.SHA512)
            {
                halg = SHA512.Create();
            }
            else
            {
                throw new Exception("Hash algorithm not supported.");
            }

            List <byte[]> signatures = new List <byte[]>(6);

            // Compute a signature using each of the SignData overloads.  Then, verify it using each
            // of the VerifyData overloads, and VerifyHash overloads.
            //
            // Then, verify that VerifyHash fails if the data is tampered with.

            signatures.Add(ecdsa.SignData(dataArray, hashAlgorithm));

            signatures.Add(ecdsa.SignData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, hashAlgorithm));

            signatures.Add(ecdsa.SignData(dataStream, hashAlgorithm));
            dataStream.Position = 0;

            signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray)));

            signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count)));

            signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataStream)));
            dataStream.Position = 0;

            foreach (byte[] signature in signatures)
            {
                Assert.True(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify 1");

                Assert.True(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify 2");

                Assert.True(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify 3");
                Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3A");
                dataStream.Position = 0;

                Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4");

                Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify 5");

                Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify 6");
                Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6A");
                dataStream.Position = 0;
            }

            int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count();

            Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized");

            foreach (byte[] signature in signatures)
            {
                signature[signature.Length - 1] ^= 0xFF; // flip some bits

                Assert.False(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify Tampered 1");

                Assert.False(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify Tampered 2");

                Assert.False(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify Tampered 3");
                Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3B");
                dataStream.Position = 0;

                Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4");

                Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify Tampered 5");

                Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify Tampered 6");
                Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6B");
                dataStream.Position = 0;
            }
        }
        async Task AuthenticateSASL(List <string> mechanisms, string username, bool async, CancellationToken cancellationToken = default)
        {
            // At the time of writing PostgreSQL only supports SCRAM-SHA-256 and SCRAM-SHA-256-PLUS
            var supportsSha256     = mechanisms.Contains("SCRAM-SHA-256");
            var supportsSha256Plus = mechanisms.Contains("SCRAM-SHA-256-PLUS");

            if (!supportsSha256 && !supportsSha256Plus)
            {
                throw new NpgsqlException("No supported SASL mechanism found (only SCRAM-SHA-256 and SCRAM-SHA-256-PLUS are supported for now). " +
                                          "Mechanisms received from server: " + string.Join(", ", mechanisms));
            }

            var mechanism      = string.Empty;
            var cbindFlag      = string.Empty;
            var cbind          = string.Empty;
            var successfulBind = false;

            if (supportsSha256Plus)
            {
                var sslStream = (SslStream)_stream;
                if (sslStream.RemoteCertificate is null)
                {
                    Log.Warn("Remote certificate null, falling back to SCRAM-SHA-256");
                }
                else
                {
                    using var remoteCertificate = new X509Certificate2(sslStream.RemoteCertificate);
                    // Checking for hashing algorithms
                    HashAlgorithm?hashAlgorithm = null;
                    var           algorithmName = remoteCertificate.SignatureAlgorithm.FriendlyName;
                    if (algorithmName is null)
                    {
                        Log.Warn("Signature algorithm was null, falling back to SCRAM-SHA-256");
                    }
                    else if (algorithmName.StartsWith("sha1", StringComparison.OrdinalIgnoreCase) ||
                             algorithmName.StartsWith("md5", StringComparison.OrdinalIgnoreCase) ||
                             algorithmName.StartsWith("sha256", StringComparison.OrdinalIgnoreCase))
                    {
                        hashAlgorithm = SHA256.Create();
                    }
                    else if (algorithmName.StartsWith("sha384", StringComparison.OrdinalIgnoreCase))
                    {
                        hashAlgorithm = SHA384.Create();
                    }
                    else if (algorithmName.StartsWith("sha512", StringComparison.OrdinalIgnoreCase))
                    {
                        hashAlgorithm = SHA512.Create();
                    }
                    else
                    {
                        Log.Warn($"Support for signature algorithm {algorithmName} is not yet implemented, falling back to SCRAM-SHA-256");
                    }

                    if (hashAlgorithm != null)
                    {
                        using var _ = hashAlgorithm;

                        // RFC 5929
                        mechanism = "SCRAM-SHA-256-PLUS";
                        // PostgreSQL only supports tls-server-end-point binding
                        cbindFlag = "p=tls-server-end-point";
                        // SCRAM-SHA-256-PLUS depends on using ssl stream, so it's fine
                        var cbindFlagBytes = Encoding.UTF8.GetBytes($"{cbindFlag},,");

                        var certificateHash = hashAlgorithm.ComputeHash(remoteCertificate.GetRawCertData());
                        var cbindBytes      = cbindFlagBytes.Concat(certificateHash).ToArray();
                        cbind          = Convert.ToBase64String(cbindBytes);
                        successfulBind = true;
                        IsScramPlus    = true;
                    }
                }
            }

            if (!successfulBind && supportsSha256)
            {
                mechanism = "SCRAM-SHA-256";
                // We can get here if PostgreSQL supports only SCRAM-SHA-256 or there was an error while binding to SCRAM-SHA-256-PLUS
                // So, we set 'n' (client does not support binding) if there was an error while binding
                // or 'y' (client supports but server doesn't) in other case
                cbindFlag      = supportsSha256Plus ? "n" : "y";
                cbind          = supportsSha256Plus ? "biws" : "eSws";
                successfulBind = true;
                IsScram        = true;
            }

            if (!successfulBind)
            {
                // We can get here if PostgreSQL supports only SCRAM-SHA-256-PLUS but there was an error while binding to it
                throw new NpgsqlException("Unable to bind to SCRAM-SHA-256-PLUS, check logs for more information");
            }

            var passwd = GetPassword(username) ??
                         throw new NpgsqlException($"No password has been provided but the backend requires one (in SASL/{mechanism})");

            // Assumption: the write buffer is big enough to contain all our outgoing messages
            var clientNonce = GetNonce();

            await WriteSASLInitialResponse(mechanism, PGUtil.UTF8Encoding.GetBytes($"{cbindFlag},,n=*,r={clientNonce}"), async, cancellationToken);
            await Flush(async, cancellationToken);

            var saslContinueMsg = Expect <AuthenticationSASLContinueMessage>(await ReadMessage(async), this);

            if (saslContinueMsg.AuthRequestType != AuthenticationRequestType.AuthenticationSASLContinue)
            {
                throw new NpgsqlException("[SASL] AuthenticationSASLContinue message expected");
            }
            var firstServerMsg = AuthenticationSCRAMServerFirstMessage.Load(saslContinueMsg.Payload);

            if (!firstServerMsg.Nonce.StartsWith(clientNonce, StringComparison.Ordinal))
            {
                throw new NpgsqlException("[SCRAM] Malformed SCRAMServerFirst message: server nonce doesn't start with client nonce");
            }

            var saltBytes      = Convert.FromBase64String(firstServerMsg.Salt);
            var saltedPassword = Hi(passwd.Normalize(NormalizationForm.FormKC), saltBytes, firstServerMsg.Iteration);

            var clientKey = HMAC(saltedPassword, "Client Key");

            byte[] storedKey;
            using (var sha256 = SHA256.Create())
                storedKey = sha256.ComputeHash(clientKey);

            var clientFirstMessageBare         = $"n=*,r={clientNonce}";
            var serverFirstMessage             = $"r={firstServerMsg.Nonce},s={firstServerMsg.Salt},i={firstServerMsg.Iteration}";
            var clientFinalMessageWithoutProof = $"c={cbind},r={firstServerMsg.Nonce}";

            var authMessage = $"{clientFirstMessageBare},{serverFirstMessage},{clientFinalMessageWithoutProof}";

            var clientSignature  = HMAC(storedKey, authMessage);
            var clientProofBytes = Xor(clientKey, clientSignature);
            var clientProof      = Convert.ToBase64String(clientProofBytes);

            var serverKey       = HMAC(saltedPassword, "Server Key");
            var serverSignature = HMAC(serverKey, authMessage);

            var messageStr = $"{clientFinalMessageWithoutProof},p={clientProof}";

            await WriteSASLResponse(Encoding.UTF8.GetBytes(messageStr), async, cancellationToken);
            await Flush(async, cancellationToken);

            var saslFinalServerMsg = Expect <AuthenticationSASLFinalMessage>(await ReadMessage(async), this);

            if (saslFinalServerMsg.AuthRequestType != AuthenticationRequestType.AuthenticationSASLFinal)
            {
                throw new NpgsqlException("[SASL] AuthenticationSASLFinal message expected");
            }

            var scramFinalServerMsg = AuthenticationSCRAMServerFinalMessage.Load(saslFinalServerMsg.Payload);

            if (scramFinalServerMsg.ServerSignature != Convert.ToBase64String(serverSignature))
            {
                throw new NpgsqlException("[SCRAM] Unable to verify server signature");
            }

            var okMsg = Expect <AuthenticationRequestMessage>(await ReadMessage(async), this);

            if (okMsg.AuthRequestType != AuthenticationRequestType.AuthenticationOk)
            {
                throw new NpgsqlException("[SASL] Expected AuthenticationOK message");
            }
 public static SHA512 CreateSHA512()
 {
     return(SHA512.Create(CryptoConfig.AllowOnlyFipsAlgorithms ? _SHA512CryptoServiceProvider : _SHA512Cng));
 }
Esempio n. 9
0
        private static ExitCode RunHashOptionsAndReturnExitCode(HashOptions hashOptions)
        {
            GenericHashResult hashResult = null;

            switch (hashOptions.InputType.ToLower())
            {
            case "string":
            {
                switch (hashOptions.Algorithm.ToLower())
                {
                case "md5":
                    hashResult = new MD5().HashString(hashOptions.InputToBeHashed);
                    break;

                case "sha1":
                    hashResult = new SHA1().HashString(hashOptions.InputToBeHashed);
                    break;

                case "sha256":
                    hashResult = new SHA256().HashString(hashOptions.InputToBeHashed);
                    break;

                case "sha384":
                    hashResult = new SHA384().HashString(hashOptions.InputToBeHashed);
                    break;

                case "sha512":
                    hashResult = new SHA512().HashString(hashOptions.InputToBeHashed);
                    break;

                case "bcrypt":
                    hashResult = new Hash.BCrypt().HashString(hashOptions.InputToBeHashed);
                    break;

                default:
                    hashResult = new GenericHashResult()
                    {
                        Success = false, Message = $"Unknown algorithm \"{hashOptions.Algorithm}\"."
                    };
                    break;
                }
            }
            break;

            case "file":
            {
                switch (hashOptions.Algorithm.ToLower())
                {
                case "md5":
                    hashResult = new MD5().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose);
                    break;

                case "sha1":
                    hashResult = new SHA1().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose);
                    break;

                case "sha256":
                    hashResult = new SHA256().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose);
                    break;

                case "sha384":
                    hashResult = new SHA384().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose);
                    break;

                case "sha512":
                    hashResult = new SHA512().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose);
                    break;

                case "bcrypt":
                    hashResult = new GenericHashResult()
                    {
                        Success = false, Message = $"Algorithm \"{hashOptions.Algorithm}\" currently not available for file hashing."
                    };
                    break;

                default:
                    hashResult = new GenericHashResult()
                    {
                        Success = false, Message = $"Unknown algorithm \"{hashOptions.Algorithm}\"."
                    };
                    break;
                }
            }
            break;

            default:
                hashResult = new GenericHashResult()
                {
                    Success = false, Message = $"Unknown input type \"{hashOptions.InputType}\"."
                };
                break;
            }

            if (hashResult.Success && !string.IsNullOrWhiteSpace(hashOptions.CompareHash))
            {
                bool hashesMatch = (
                    hashOptions.Algorithm.ToLower() != "bcrypt"
                        ? (hashResult.Hash).Equals(hashOptions.CompareHash, StringComparison.InvariantCultureIgnoreCase)
                        : new Hash.BCrypt().Verify(hashOptions.InputToBeHashed, hashOptions.CompareHash).Success
                    );

                var outputMessage = (
                    hashesMatch
                        ? $"Computed hash MATCH with given hash: {(hashOptions.Algorithm.ToLower() != "bcrypt" ? hashResult.Hash : hashOptions.CompareHash)}"
                        : $"Computed hash DOES NOT MATCH with given hash." +
                    (
                        hashOptions.Algorithm.ToLower() != "bcrypt"
                                ? $"\nComputed hash: {hashResult.Hash}\nGiven hash: {hashOptions.CompareHash}"
                                : ""
                    )
                    );

                Console.WriteLine(outputMessage);

                return(hashesMatch ? ExitCode.Sucess : ExitCode.Error);
            }
            else if (hashResult.Success && string.IsNullOrWhiteSpace(hashOptions.CompareHash))
            {
                Console.WriteLine(hashResult.Hash);

                return(ExitCode.Sucess);
            }
            else
            {
                Console.WriteLine(hashResult.Message);

                return(ExitCode.Error);
            }
        }
Esempio n. 10
0
        public void TestSignAndVerifyHash()
        {
            byte[] data = new byte[100];
            new Random().NextBytes(data);

            foreach (HashAlgorithm ha in new HashAlgorithm[] { MD5.Create(), SHA1.Create(), SHA256.Create(), SHA384.Create(), SHA512.Create() })
            {
                Hash hash = Hash.FromBytes(ha.ComputeHash(data));
                Assert.AreEqual(CryptoConfig.MapNameToOID(ha.GetType().FullName), hash.AlgorithmOID);

                using (RSAPrivateKey key = new RSAPrivateKey())
                {
                    byte[] sig = key.SignHash(hash);

                    using (RSAPublicKey pub = key.PublicKey)
                    {
                        Assert.IsTrue(pub.VerifyHash(sig, Hash.FromBytes(ha.ComputeHash(data))));
                        data[0] = (byte)~data[0];
                        Assert.IsFalse(pub.VerifyHash(sig, Hash.FromBytes(ha.ComputeHash(data))));
                    }
                }
            }
        }
        public void Deploy(string connectionString, Action <string> writeMessage)
        {
            var runningInCi = Environment.GetEnvironmentVariable("TF_BUILD") != null;

            var dacpacLocation = Path.GetFullPath(Path.Combine(
                                                      Environment.CurrentDirectory,
                                                      "../../../../../src/Dfc.CourseDirectory.Database/bin",
#if DEBUG
                                                      "Debug",
#else
                                                      "Release",
#endif
                                                      "Dfc.CourseDirectory.Database.dacpac"));

            var databaseName = GetDatabaseNameFromConnectionString();

            if (!runningInCi)
            {
                var dacpacHash         = ComputeDacpacHash();
                var schemaHashFileName = GetSchemaHashFileName();

                // Check the hash of the last deployed database schema.
                // If it matches this one we can skip the deployment.
                if (TryGetLastDeployedDacpacHash(out var hash) && hash == dacpacHash)
                {
                    writeMessage("DACPAC is unchanged - skipping deployment");
                    return;
                }

                DeployCore();

                WriteDacpacHashToCacheFile();

                string ComputeDacpacHash()
                {
                    using (var fs = File.OpenRead(dacpacLocation))
                        using (var hashAlgo = SHA512.Create())
                        {
                            return(Convert.ToBase64String(hashAlgo.ComputeHash(fs)));
                        }
                }

                string GetSchemaHashFileName() =>
                Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    "CourseDirectory",
                    $"{databaseName}.sqlschemahash");

                bool TryGetLastDeployedDacpacHash(out string hash)
                {
                    if (File.Exists(schemaHashFileName))
                    {
                        hash = File.ReadAllText(schemaHashFileName);
                        return(true);
                    }
                    else
                    {
                        hash = default;
                        return(false);
                    }
                }

                void WriteDacpacHashToCacheFile()
                {
                    var schemaHashFileDirectory = Path.GetDirectoryName(schemaHashFileName);

                    Directory.CreateDirectory(schemaHashFileDirectory);

                    File.WriteAllText(schemaHashFileName, dacpacHash);
                }
            }
            else
            {
                DeployCore();
            }

            void DeployCore()
            {
                var dacServices = new DacServices(connectionString);

                try
                {
                    dacServices.ProgressChanged += DacServices_ProgressChanged;

                    using var dacpac = DacPackage.Load(dacpacLocation);

                    dacServices.Deploy(
                        dacpac,
                        databaseName,
                        upgradeExisting: true,
                        options: new DacDeployOptions()
                    {
                        BlockOnPossibleDataLoss = false,
                        DropObjectsNotInSource  = true,
                        DoNotDropObjectTypes    = new[]
                        {
                            ObjectType.Logins,
                            ObjectType.Users,
                            ObjectType.Permissions,
                            ObjectType.RoleMembership
                        }
                    });
                }
                finally
                {
                    dacServices.ProgressChanged -= DacServices_ProgressChanged;
                }
            }

            void DacServices_ProgressChanged(object sender, DacProgressEventArgs e) => writeMessage?.Invoke(e.Message);

            string GetDatabaseNameFromConnectionString() =>
            new SqlConnectionStringBuilder(connectionString).InitialCatalog;
        }
Esempio n. 12
0
        private void buttonChange_Click(object sender, EventArgs e)
        {
            #region 입력값 검증
            if (textBoxChangeKey.Text == "")
            {
                MessageBox.Show("키 값을 입력해 주세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxChangeKey.Focus(); return;
            }

            if (textBoxChangeKey.Text != textBoxChangeConKey.Text)
            {
                MessageBox.Show("입력하신 키 값이 서로 일치하지 않습니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxChangeConKey.Focus(); return;
            }

            if (textBoxChangePassword.Text == "")
            {
                MessageBox.Show("비밀번호를 입력해 주세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxChangePassword.Focus(); return;
            }

            if (textBoxChangePassword.Text != textBoxChangeConPassword.Text)
            {
                MessageBox.Show("입력하신 비밀번호가 서로 일치하지 않습니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxChangeConPassword.Focus(); return;
            }
            #endregion

            if (MessageBox.Show("정말로 변경하시겠습니까?", "질문", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                AES256 AES = new AES256();
                string hashString = null; byte[] encryptedBytes = null;

                // 리스트뷰 정보 새로 암호화
                if (mainForm.listViewMain.Items.Count > 0)
                {
                    using (MemoryStream MS = new MemoryStream())
                    {
                        using (StreamWriter SW = new StreamWriter(MS, Encoding.UTF8))
                        {
                            List <string> list = new List <string>();

                            foreach (ListViewItem LVI in mainForm.listViewMain.Items)
                            {
                                list.Add(LVI.Text);
                                list.Add(LVI.SubItems[1].Text);
                                list.Add(LVI.SubItems[2].Text);
                                list.Add(LVI.SubItems[3].Text);
                                list.Add(AES.DecryptString((string)LVI.Tag));
                            }

                            AES.KeyString = textBoxChangeKey.Text;
                            AES.SaltBytes = CommonData.EncryptSalt;

                            for (int i = 0; i < list.Count; i += 5)
                            {
                                SW.WriteLine(list[i]);
                                SW.WriteLine(list[i + 1]);
                                SW.WriteLine(list[i + 2]);
                                SW.WriteLine(list[i + 3]);
                                SW.WriteLine(AES.EncryptString(list[i + 4]));
                                SW.Flush();
                            }

                            encryptedBytes = AES.EncryptByte(MS.ToArray());
                            File.WriteAllBytes(Path.Combine(Application.StartupPath, CommonData.Folder, CommonData.DataFile), encryptedBytes);
                        }
                    }
                }
                else
                {
                    AES.KeyString = textBoxChangeKey.Text; AES.SaltBytes = CommonData.EncryptSalt;
                    File.Delete(Path.Combine(Application.StartupPath, CommonData.Folder, CommonData.DataFile));
                }

                // 비밀번호 암호화
                hashString     = Convert.ToBase64String(SHA512.Create().ComputeHash(Encoding.UTF8.GetBytes(CommonData.HashSalt + textBoxChangePassword.Text)));
                encryptedBytes = AES.EncryptByte(Encoding.UTF8.GetBytes(hashString + textBoxChangePassword.Text));

                // 정보 저장
                File.WriteAllBytes(Path.Combine(Application.StartupPath, CommonData.Folder, CommonData.PasswordFile), encryptedBytes);

                // 성공 메세지
                MessageBox.Show("비밀번호가 정상적으로 변경되었습니다. \n프로그램을 다시 실행해 주세요.", "알림", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }
        }
Esempio n. 13
0
 public override void SetUp()
 {
     hash = SHA512.Create();
 }
Esempio n. 14
0
        public static decimal sGetLucky(string server, string client, int nonce)
        {
            SHA512 betgenerator = SHA512.Create();

            int charstouse = 5;

            List <byte> buffer = new List <byte>();
            string      msg    = server + ":" + nonce.ToString() + ":" + client;

            foreach (char c in msg)
            {
                buffer.Add(Convert.ToByte(c));
            }

            byte[]        hash = betgenerator.ComputeHash(buffer.ToArray());
            StringBuilder hex2 = new StringBuilder(hash.Length * 2);

            foreach (byte b in hash)
            {
                hex2.AppendFormat("{0:x2}", b);
            }
            msg = hex2.ToString();
            buffer.Clear();
            foreach (char c in msg)
            {
                buffer.Add(Convert.ToByte(c));
            }
            hash = betgenerator.ComputeHash(hash);
            StringBuilder hex = new StringBuilder(hash.Length * 2);

            foreach (byte b in hash)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            int    SIZE = 4;
            var    r    = new string[] { "0", "0", "0", "0", };
            string Hash = hex.ToString();

            if (nonce == 46)
            {
            }
            for (var i = 0; i < hash.Length; ++i)
            {
                try
                {
                    int tmp       = int.Parse(r[i % SIZE], System.Globalization.NumberStyles.HexNumber) + hash[i];
                    var stringVal = tmp % 256;
                    r[i % SIZE] = (stringVal.ToString("X"));
                }
                catch
                {
                    r[i % SIZE] = "0";
                }
            }
            string hexres = "";

            for (int i = 0; i < r.Length; i++)
            {
                hexres += r[i] == "0"?"00": r[i];
            }
            long    Lucky  = long.Parse(hexres, System.Globalization.NumberStyles.HexNumber);
            decimal result = ((decimal)(Lucky % 1000000)) / 10000m;

            return(result);

            return(0);
        }
 public override void CreateNull()
 {
     // try to build null implementation
     hash = SHA512.Create(null);
 }
Esempio n. 16
0
 static HashHelper()
 {
     sha512 = SHA512.Create();
 }
Esempio n. 17
0
 public static byte[] ComputeSHA512(this byte[] buffer)
 {
     using var hasher = SHA512.Create();
     return(hasher.ComputeHash(buffer));
 }
Esempio n. 18
0
        /// <summary>
        /// OBSOLETE METHOD: This method was to create a SHA512 hash from a string
        /// </summary>
        /// <param name="inputString">the string to be hashed</param>
        /// <returns>the byte array derived from the string</returns>
        public static byte[] GetHash(string inputString)
        {
            HashAlgorithm algorithm = SHA512.Create();

            return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
        }
Esempio n. 19
0
    protected void btnmodalsubmit_Click1(object sender, EventArgs e)
    {
        SHA512 m = SHA512.Create();

        byte[]        bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(txtpass.Text);
        byte[]        hash  = m.ComputeHash(bytes);
        StringBuilder sb    = new StringBuilder();

        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        var pass = sb.ToString();

        try
        {
            if (txtid.Text != "" && txtid.Text != null && txtpass.Text != "" && txtpass.Text != null)
            {
                con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\webdata.mdf;Integrated Security=True");
                con.Open();

                if (Char.IsLetter(txtid.Text, 1))
                {
                    command  = new SqlCommand("select count(*) from simpleuserregister where email='" + txtid.Text + "' and password='******'", con);
                    command1 = new SqlCommand("select username from simpleuserregister where email='" + txtid.Text + "'", con);
                    command2 = new SqlCommand("select id from simpleuserregister where email='" + txtid.Text + "'", con);
                }
                else
                {
                    command  = new SqlCommand("select count(*) from simpleuserregister where contactno=" + txtid.Text + " and password='******'", con);
                    command1 = new SqlCommand("select username from simpleuserregister where contactno=" + txtid.Text + "", con);
                    command2 = new SqlCommand("select id from simpleuserregister where contactno=" + txtid.Text + "", con);
                }

                int    cnt, cnt3;
                string name;
                cnt = Convert.ToInt32(command.ExecuteScalar());
                //  lblerror.Text = Convert.ToString(cnt);
                cnt3 = Convert.ToInt32(command2.ExecuteScalar());
                name = Convert.ToString(command1.ExecuteScalar());

                con.Close();

                if (cnt == 1)
                {
                    lblerror.Text   = "successfuly";
                    Session["id"]   = cnt3;
                    Session["user"] = name;

                    ((MasterPage)Master).getdata.Text = name;


                    Response.Redirect("postproperty.aspx");
                }
                else
                {
                    lblerror.Text = "invalid";
                }
            }
            else if (txtid.Text == "")
            {
                lblerror.Text = "Please fill mobile no.or e-mail";
            }
            else if (txtpass.Text == "")
            {
                lblerror.Text = "Please fill the password";
            }
            else
            {
                lblerror.Text = "Both fields are required";
            }
        }
        catch
        {
            error.InnerHtml = "Something wrong, Please try again";
        }
    }
Esempio n. 20
0
        /**
         * Registo de novos utilizadores. Devem ser recebidos o username, email e password para criar o novo utilizador.
         * Quando é guardado um novo utilizador na base de dados, o email e username são transformados em upper case, e
         * a password é encriptada.
         */
        public async override Task <UserRegistModel> Regist(UserRegistLookupModel request, ServerCallContext context)
        {
            UserRegistModel output = new UserRegistModel();

            // Transformação dos carateres do email e username para upper case
            string email    = request.Email.ToUpper();
            string username = request.Username;//.ToUpper();

            // Verificações se um outro utilizador tem o mesmo email e/ou o mesmo username
            Models.User u1 = new Models.User(), u2 = new Models.User();
            u1 = _context.User.FirstOrDefault(u => u.Username == username);
            u2 = _context.User.FirstOrDefault(u => u.Email == email);

            // Um utilizador tem o mesmo username
            if (u1 != null)
            {
                if (u2 == null)
                {
                    output.Valid = -3; // Um utilizador tem apenas o mesmo username
                }
                else
                {
                    output.Valid = -1; // Um utilizador tem o mesmo username e email
                }
            }
            // Um utilizador tem o mesmo email
            else if (u2 != null)
            {
                output.Valid = -2; // Um utilizador tem apenas o mesmo email
            }
            // Nenhum utilizador tem o mesmo username e/ou email
            else
            {
                // Encriptação da password
                SHA512 sha512   = SHA512Managed.Create();
                byte[] bytes    = sha512.ComputeHash(Encoding.UTF8.GetBytes(request.Password));
                string password = Convert.ToBase64String(bytes);

                Models.User u = new Models.User
                {
                    Username = username,
                    Email    = email,
                    Password = password
                };

                // Verifica e garante que a BD existe
                _context.Database.EnsureCreated();

                // Guarda-se o novo utilizador na base de dados
                _context.User.Add(u);
                _context.SaveChanges();

                // Regista o utilizador no banco de créditos
                await APIServerCommunication.RegisterUser(u.Username, u.Id);

                // Envia-se uma mensagem uma mensagem de confirmação de registo ao cliente
                output.Valid = 1;
            }

            return(await Task.FromResult(output));
        }
Esempio n. 21
0
 public static byte[] Hash(string s)
 {
     byte[] input = Encoding.Unicode.GetBytes(s);
     return(SHA512.Create().ComputeHash(input));
 }
Esempio n. 22
0
        public static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;

            Console.WriteLine("Findup.exe v2.0 - By James Gentile - [email protected] - 2012.");
            Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files.");
            Console.WriteLine(" ");
            string          optionskey = "-paths";
            List <FileInfo> files      = new List <FileInfo>();
            int             i          = 0;

            for (i = 0; i < args.Length; i++)
            {
                string argitem = args[i].ToLower();

                if ((System.String.Compare(argitem, "-help", true) == 0) || (System.String.Compare(argitem, "-h", true) == 0))
                {
                    Console.WriteLine("Usage:    findup.exe <file/directory #1..#N> [-recurse] [-noerr] [-x/-i/-xd/-id/-xf/-if] <files/directories/regex> [-regex] [-delete]");
                    Console.WriteLine(" ");
                    Console.WriteLine("Options:  -help     - displays this help message.");
                    Console.WriteLine("          -recurse  - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
                    Console.WriteLine("          -noerr    - discards error messages.");
                    Console.WriteLine("          -delete   - delete each duplicate file with confirmation.");
                    Console.WriteLine("          -x        - eXcludes if full file path starts with (or RegEx matches if -xr) one of the items following this switch until another switch is used.");
                    Console.WriteLine("          -i        - include if full file path starts with (or Regex matches if -ir) one of the items following this switch until another switch is used.");
                    Console.WriteLine("          -xd       - eXcludes all directories - minus drive/files - (using RegEx if -xdr) including subdirs following this switch until another switch is used.");
                    Console.WriteLine("          -id       - Include only directories - minus drive/files - (using RegEx if -idr) including subdirs following this switch until another switch is used.");
                    Console.WriteLine("          -xf       - eXcludes all files - minus drive/directories - (using RegEx if -xfr) following this switch until another switch is used.");
                    Console.WriteLine("          -if       - Include only files - minus drive/directories - (using RegEx if -ifr) following this switch until another switch is used.");
                    Console.WriteLine("          [r]       - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr.");
                    Console.WriteLine("          -paths    - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option.");
                    Console.WriteLine(" ");
                    Console.WriteLine("Examples: findup.exe c:\\finances -recurse -noerr");
                    Console.WriteLine("                     - Find dupes in c:\\finance.");
                    Console.WriteLine("                     - recurse all subdirs of c:\\finance.");
                    Console.WriteLine("                     - suppress error messages.");
                    Console.WriteLine("          findup.exe c:\\users\\alice\\plan.txt d:\\data -recurse -x d:\\data\\webpics");
                    Console.WriteLine("                     - Find dupes in c:\\users\\alice\\plan.txt, d:\\data");
                    Console.WriteLine("                     - recurse subdirs in d:\\data.");
                    Console.WriteLine("                     - exclude any files in d:\\data\\webpics and subdirs.");
                    Console.WriteLine("          findup.exe c:\\data *.txt c:\\reports\\quarter.doc -xr \"(jim)\" -regex");
                    Console.WriteLine("                     - Find dupes in c:\\data, *.txt in current directory and c:\\reports\\quarter.doc");
                    Console.WriteLine("                     - exclude any file with 'jim' in the name as specified by the Regex item \"(jim)\"");
                    Console.WriteLine("          findup.exe c:\\data *.txt c:\\reports\\*quarter.doc -xr \"[bf]\" -ir \"(smith)\" -regex");
                    Console.WriteLine("                     - Find dupes in c:\\data, *.txt in current directory and c:\\reports\\*quarter.doc");
                    Console.WriteLine("                     - Include only files with 'smith' and exclude any file with letters b or f in the name as specified by the Regex items \"[bf]\",\"(smith)\"");
                    Console.WriteLine("Note:     Exclude takes precedence over Include.");
                    return;
                }
                if (optionsbools.ContainsKey(argitem))
                {
                    optionsbools[argitem] = true;
                    optionskey            = "-paths";
                    continue;
                }
                if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem))
                {
                    optionskey = argitem;
                    continue;
                }
                if (optionspaths.ContainsKey(optionskey))
                {
                    optionspaths[optionskey].Add(argitem);
                }
                else
                {
                    try {
                        Regex rgx = new Regex(argitem, RegexOptions.Compiled);
                        optionsregex[optionskey].Add(rgx);
                    }
                    catch (Exception e) { WriteErr("Regex compilation failed: " + e.Message); }
                }
            }
            if (optionspaths["-paths"].Count == 0)
            {
                WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory.");
                optionspaths["-paths"].Add(".");
            }
            Console.Write("Getting file info and sorting file list...");
            getFiles(optionspaths["-paths"], "*.*", optionsbools["-recurse"], files);

            if (files.Count < 2)
            {
                WriteErr("\nFindup.exe needs at least 2 files to compare. Try findup.exe -help");
                Console.WriteLine("\n");
                return;
            }

            files.Sort(new FileLengthComparer());
            Console.WriteLine("Completed!");

            Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths...");

            var SizeHashFile = new Dictionary <long, Dictionary <string, List <FileInfo> > >();

            for (i = 0; i < (files.Count - 1); i++)
            {
                if (files[i].Length != files[i + 1].Length)
                {
                    continue;
                }
                var breakout = false;
                while (true)
                {
                    try
                    {
                        var _SHA512 = SHA512.Create();
                        using (var fstream = File.OpenRead(files[i].FullName))
                        {
                            _SHA512.ComputeHash(fstream);
                        }
                        string SHA512string = "";
                        foreach (var c in _SHA512.Hash)
                        {
                            SHA512string += String.Format("{0:x2}", c);
                        }

                        if (!SizeHashFile.ContainsKey(files[i].Length))
                        {
                            SizeHashFile.Add(files[i].Length, new Dictionary <string, List <FileInfo> >());
                        }
                        if (!SizeHashFile[files[i].Length].ContainsKey(SHA512string))
                        {
                            SizeHashFile[files[i].Length][SHA512string] = new List <FileInfo>()
                            {
                            }
                        }
                        ;
                        SizeHashFile[files[i].Length][SHA512string].Add(files[i]);
                    }
                    catch (Exception e) { WriteErr("Hash error: " + e.Message); }

                    if (breakout == true)
                    {
                        break;
                    }
                    i++;
                    if (i == (files.Count - 1))
                    {
                        breakout = true; continue;
                    }
                    breakout = (files[i].Length != files[i + 1].Length);
                }
            }

            Console.WriteLine("Completed!");

            foreach (var SizeGroup in SizeHashFile)
            {
                foreach (var HashGroup in SizeGroup.Value)
                {
                    var SGK  = (long)SizeGroup.Key;
                    var HGVC = (long)HashGroup.Value.Count;
                    if (HGVC > 1)
                    {
                        Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HGVC, SGK, SGK * HGVC);
                        foreach (var Filenfo in HashGroup.Value)
                        {
                            Console.WriteLine(Filenfo.FullName);
                            numOfDupes++;
                            dupeBytes += Filenfo.Length;
                            if (optionsbools["-delete"])
                            {
                                if (DeleteDupe(Filenfo))
                                {
                                    bytesrecovered += Filenfo.Length; deletedfiles++;
                                }
                            }
                        }
                    }
                }
            }

            Console.WriteLine("\n ");
            Console.WriteLine("Files checked      : {0:N0}", files.Count);              // display statistics and return to OS.
            Console.WriteLine("Duplicate files    : {0:N0}", numOfDupes);
            Console.WriteLine("Duplicate bytes    : {0:N0}", dupeBytes);
            Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles);
            Console.WriteLine("Bytes recovered    : {0:N0}", bytesrecovered);
            Console.WriteLine("Execution time     : " + (DateTime.Now - startTime));
        }
Esempio n. 23
0
 public RemitaHashGenerator(IntegrateConfig config)
 {
     Config     = config;
     HasherBase = new SHA512Managed();
 }
Esempio n. 24
0
        internal static async Task SignRequest(HttpClient client, HttpMethod method, string serviceUrl,
                                               HttpContent content, string consumerKey, string consumerSecret, SignatureMethod signatureMethod)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (string.IsNullOrEmpty(serviceUrl))
            {
                throw new ArgumentNullException(nameof(serviceUrl));
            }

            var serviceUri = new Uri(serviceUrl, UriKind.RelativeOrAbsolute);

            if (!serviceUri.IsAbsoluteUri)
            {
                if (client.BaseAddress == null)
                {
                    throw new LtiException("If serviceUrl is relative, client.BaseAddress cannot be null.");
                }

                if (!Uri.TryCreate(client.BaseAddress, serviceUrl, out serviceUri))
                {
                    throw new LtiException($"Cannot form a valid URI from {client.BaseAddress} and {serviceUrl}.");
                }
            }

            var ltiRequest = new LtiRequest(LtiConstants.LtiOauthBodyHashMessageType)
            {
                ConsumerKey = consumerKey,
                HttpMethod  = method.Method,
                Url         = serviceUri
            };

            AuthenticationHeaderValue authorizationHeader;

            // Determine hashing algorithm
            HashAlgorithm sha;

            switch (signatureMethod)
            {
            default:
            case SignatureMethod.HmacSha1:
                sha = SHA1.Create();
                break;

            case SignatureMethod.HmacSha256:
                sha = SHA256.Create();
                break;

            case SignatureMethod.HmacSha384:
                sha = SHA384.Create();
                break;

            case SignatureMethod.HmacSha512:
                sha = SHA512.Create();
                break;
            }

            // Create an Authorization header using the body hash
            using (sha)
            {
                var hash = sha.ComputeHash(await content.ReadAsByteArrayAsync());
                authorizationHeader = ltiRequest.GenerateAuthorizationHeader(hash, consumerSecret);
            }

            // Attach the header to the client request
            client.DefaultRequestHeaders.Authorization = authorizationHeader;
        }
Esempio n. 25
0
        public Command GetCommand()
        {
            CTS = new CancellationTokenSource();
            CT  = CTS.Token;
            TABLE.Add(new CommandArgumentEntry("[string] [string]", true, "[wordlist path] [hash]"));
            CMD_HASHCRACK = new Command("HASHCRACK", TABLE, false, "Starts a search for a matching hash value in the specified wordlist. Supported hash types: SHA1, SHA256, SHA384, SHA512.", ExecutionLevel.User, CLIMode.Default);
            CMD_HASHCRACK.SetAsyncFunction(async() =>
            {
                processedWords = 0;
                progress       = 0;
                count          = 0;
                currentWord    = null;
                currentResult  = null;
                try
                {
                    ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                    {
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = true;
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown += Main_KeyDown;
                    });
                    HashType hashType;

                    string result = null;
                    async Task HASH_TASK(string word)
                    {
                        await Task.Delay(0);
                        object hashingObject = null;
                        string hash          = null;
                        if (result == null)
                        {
                            switch (hashType)
                            {
                            case HashType.SHA1:
                                hashingObject = SHA1.Create();
                                hash          = BitConverter.ToString(((SHA1)hashingObject).ComputeHash(Encoding.UTF8.GetBytes(word))).Replace("-", "");
                                break;

                            case HashType.SHA256:
                                hashingObject = SHA256.Create();
                                hash          = BitConverter.ToString(((SHA256)hashingObject).ComputeHash(Encoding.UTF8.GetBytes(word))).Replace("-", "");
                                break;

                            case HashType.SHA384:
                                hashingObject = SHA384.Create();
                                hash          = BitConverter.ToString(((SHA384)hashingObject).ComputeHash(Encoding.UTF8.GetBytes(word))).Replace("-", "");
                                break;

                            case HashType.SHA512:
                                hashingObject = SHA512.Create();
                                hash          = BitConverter.ToString(((SHA512)hashingObject).ComputeHash(Encoding.UTF8.GetBytes(word))).Replace("-", "");
                                break;
                            }
                            if (hash == CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString().ToUpper())
                            {
                                result = word;
                            }
                        }

                        currentResult = hash;
                        currentWord   = word;
                        processedWords++;
                        progress      = processedWords / count * 100;
                        word          = null;
                        hash          = null;
                        hashingObject = null;
                    }

                    List <Task> taskList = new List <Task>();
                    Regex hexCheck       = new Regex("^[a-fA-F0-9]*$");
                    switch (CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString().Length)
                    {
                    case 40 when hexCheck.IsMatch(CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString()):
                        hashType = HashType.SHA1;
                        break;

                    case 64 when hexCheck.IsMatch(CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString()):
                        hashType = HashType.SHA256;
                        break;

                    case 96 when hexCheck.IsMatch(CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString()):
                        hashType = HashType.SHA384;
                        break;

                    case 128 when hexCheck.IsMatch(CMD_HASHCRACK.InputArgumentEntry.Arguments[1].Value.ToString()):
                        hashType = HashType.SHA512;
                        break;

                    default:
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                        {
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                        });
                        return("\nIncorrect hash format or unsupported type!");
                    }
                    string path = null;
                    if (File.Exists(CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString()) && CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString().Contains(":"))
                    {
                        path = CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString();
                    }
                    else if (File.Exists(EnvironmentVariables.GetCurrentValue("DIRECTORY").ToString() + CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString()))
                    {
                        path = EnvironmentVariables.GetCurrentValue("DIRECTORY").ToString() + CMD_HASHCRACK.InputArgumentEntry.Arguments[0].Value.ToString();
                    }
                    if (path == null)
                    {
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                        {
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                        });
                        return("\nFile not found!");
                    }
                    string[] lines = File.ReadAllLines(path);
                    count          = lines.Length;
                    taskList.Add(Task.Run(async() => { await HASH_TASK(lines[0]); }));
                    for (int i = 0; i < lines.Length; i++)
                    {
                        if (CT.IsCancellationRequested)
                        {
                            ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                            {
                                ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                                ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                            });
                            return("\nProcess interrupted.");
                        }
                        if (result != null)
                        {
                            break;
                        }
                        taskList.RemoveAll(x => x.IsCompleted);
                        taskList.Add(Task.Run(async() => { await HASH_TASK(lines[i]); }));
                    }
                    await Task.WhenAll(taskList).ContinueWith(t => t.Dispose());
                    ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                    {
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                    });
                    if (result == null)
                    {
                        return("\nNo matching hash found!");
                    }
                    return($"\nResult: {result}");
                }
                catch (Exception ex)
                {
                    ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).Dispatcher.Invoke(() =>
                    {
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).IsReadOnly      = false;
                        ((TextEditor)EnvironmentVariables.GetCurrentValue("IOFIELD")).PreviewKeyDown -= Main_KeyDown;
                        IOInteractLayer.StandardError(CMD_HASHCRACK, ex);
                    });
                    return("");
                }
            });
            return(CMD_HASHCRACK);
        }
Esempio n. 26
0
 public Cryptography()
 {
     _sha1   = SHA1.Create();
     _sha256 = SHA256.Create();
     _sha512 = SHA512.Create();
 }
Esempio n. 27
0
        private async Task HandleLoginAction()
        {
            bool isUserEmpty     = string.IsNullOrEmpty(nUser.Text);
            bool isPasswordEmpty = string.IsNullOrEmpty(nPassword.Text);

            if (isUserEmpty || isPasswordEmpty)
            {
                if (isUserEmpty)
                {
                    nUser.Focus();
                }
                nUser.PlaceholderColor = Color.Red;
                if (isPasswordEmpty)
                {
                    nPassword.Focus();
                }
                nPassword.PlaceholderColor = Color.Red;
                await DisplayAlert("Alert", "Pleae fill the RED fields", "Ok");
            }
            else
            {
                ///no internet access
                ///local sign in
                if (!CrossConnectivity.Current.IsConnected)
                {
                    String Hashed = "";
                    using (var sha = SHA512.Create())
                    {
                        using (var md5 = MD5.Create())
                        {
                            Hashed = Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(nPassword.Text))))));
                        }
                    }

                    ///verification
                    var UserInfo = await LoginHandler.LoginInfo(nUser.Text, Hashed);

                    if (UserInfo.Count > 0)
                    {
                        if (UserInfo[0].MedicID != 0)
                        {
                            Utilities.MedicID = UserInfo[0].MedicID;
                        }

                        await Navigation.PushAsync(new HomePage(UserInfo[0].UserID, (UserInfo[0].MedicID != 0)));

                        Navigation.RemovePage(this);
                    }
                    else
                    {
                        await DisplayAlert("Alert", "Please create an account when you are connected before you can use this application offline.", "Ok");
                    }
                }
                else
                {
                    Dictionary <int, String[]> KeyValues = new Dictionary <int, string[]>();
                    KeyValues.Add(0, new String[] { "password", nPassword.Text });
                    KeyValues.Add(1, new String[] { "user", nUser.Text });
                    FormUrlEncodedContent Data = Utilities.PostDataEncoder(KeyValues);

                    String ResponseJson = "";
                    try
                    {
                        ResponseJson = await Model.LoginModel.Login(Data);

                        var DecodedJson = JObject.Parse(ResponseJson.ToString());

                        if (Convert.ToBoolean(DecodedJson["status"]))
                        {
                            ///request needed permission of not granted
                            bool StoragePermissionGranted = await Utilities.CheckPermission(Permission.Storage, Utilities.ApplicationName + " would need access to device storage.");

                            Utilities.IsLoggedIn = true;
                            Utilities.IsMedic    = Convert.ToBoolean(DecodedJson["info"]["is_medic"]);
                            Utilities.ID         = (int)DecodedJson["info"]["id"];

                            if (Utilities.IsMedic)
                            {
                                Utilities.MedicID = (int)DecodedJson["info"]["medic_id"];
                            }



                            ///save info to local db

                            using (var sha = SHA512.Create())
                            {
                                using (var md5 = MD5.Create())
                                {
                                    String Hashed = Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(nPassword.Text))))));

                                    var UserInfo = await LoginHandler.LoginInfo(nUser.Text, Hashed);

                                    if (UserInfo.Count == 0)
                                    {
                                        await LoginHandler.InsertNewLoginInfo(nUser.Text, Hashed, (int)DecodedJson["info"]["id"], (Utilities.IsMedic)?(int)DecodedJson["info"]["medic_id"] : 0, DecodedJson["info"]["name"].ToString());

                                        var UserDetails = await SettingsController.GetSettings();

                                        await UserDetailsHandler.SaveUserDetails(new UserDetailsModel { Address = UserDetails["address"], DOB = UserDetails["dob"], Email = UserDetails["email"], FullName = UserDetails["name"], PhoneNo = UserDetails["phone"], UserID = Utilities.ID });
                                    }
                                }
                            }



                            await Navigation.PushAsync(new HomePage((int)DecodedJson["info"]["id"], Utilities.IsMedic));

                            //await ChatHandler.GetLastUniqueConversation();

                            Navigation.RemovePage(this);
                        }
                        else
                        {
                            await DisplayAlert("Alert", DecodedJson["message"].ToString(), "Okay");
                        }
                    }
                    catch (System.Net.WebException WebEx)
                    {
                        await DisplayAlert("Alert", WebEx.Message + "\n" + Utilities.BaseAddress + "\n" + ResponseJson, "Okay");
                    }
                    catch (Exception ex)
                    {
                        await DisplayAlert("Alert", ex.StackTrace + "\n" + Utilities.BaseAddress + "\n" + ResponseJson, "Okay");
                    }
                }
            }
        }
Esempio n. 28
0
 /// <summary>
 /// 验证 SHA512 值
 /// </summary>
 /// <param name="input"> 未加密的字符串 </param>
 /// <param name="encoding"> 字符编码 </param>
 /// <returns></returns>
 public static bool VerifySHA512Value(string input, Encoding encoding)
 {
     return VerifyHashValue(SHA512.Create(), input, SHA512Encrypt(input, encoding), encoding);
 }
Esempio n. 29
0
 public static FileHash Create(FilePath path)
 {
     using var hashAlgorithm = SHA512.Create();
     return(Create(path, hashAlgorithm));
 }
 public void CreateInvalid()
 {
     // try to build invalid implementation
     hash = SHA512.Create("InvalidHash");
     Assert.IsNull(hash, "SHA512.Create('InvalidHash')");
 }
Esempio n. 31
0
        public async Task PublishAsync(
            IKubernetesObject <V1ObjectMeta> resource,
            string reason,
            string message,
            EventType type = EventType.Normal)
        {
            _logger.LogTrace(
                "Encoding event name with: {resourceName}.{resourceNamespace}.{reason}.{message}.{type}.",
                resource.Name(),
                resource.Namespace(),
                reason,
                message,
                type);
            var eventName =
                Base32.Rfc4648.Encode(
                    SHA512.HashData(
                        Encoding.UTF8.GetBytes($"{resource.Name()}.{resource.Namespace()}.{reason}.{message}.{type}")));

            _logger.LogTrace(@"Search or create event with name ""{name}"".", eventName);
            var @event = await _client.Get <Corev1Event>(eventName, resource.Namespace()) ??
                         new Corev1Event
            {
                Kind       = Corev1Event.KubeKind,
                ApiVersion = $"{Corev1Event.KubeGroup}/{Corev1Event.KubeApiVersion}",
                Metadata   = new V1ObjectMeta
                {
                    Name = eventName,
                    NamespaceProperty = resource.Namespace(),
                    Annotations       = new Dictionary <string, string>
                    {
                        { "nameHash", "sha512" },
                        { "nameEncoding", "Base32 / RFC 4648" },
                    },
                },
                Type               = type.ToString(),
                Reason             = reason,
                Message            = message,
                ReportingComponent = _settings.Name,
                ReportingInstance  = Environment.MachineName,
                Source             = new V1EventSource {
                    Component = _settings.Name
                },
                InvolvedObject = resource.MakeObjectReference(),
                FirstTimestamp = DateTime.UtcNow,
                LastTimestamp  = DateTime.UtcNow,
                Count          = 0,
            };

            @event.Count++;
            @event.LastTimestamp = DateTime.UtcNow;
            _logger.LogTrace(
                "Save event with new count {count} and last timestamp {timestamp}",
                @event.Count,
                @event.LastTimestamp);

            await _client.Save(@event);

            _logger.LogInformation(
                @"Created or updated event with name ""{name}"" to new count {count} on resource ""{kind}/{name}"".",
                eventName,
                @event.Count,
                resource.Kind,
                resource.Name());
        }
Esempio n. 32
0
		public SHA512Cng ()
		{
			// note: we don't use SHA512.Create since CryptoConfig could, 
			// if set to use this class, result in a endless recursion
			hash = new SHA512Managed ();
		}
        private static void Verify(
            ref ECParameters iutParameters,
            ref ECParameters cavsParameters,
            ECCurve explicitCurve,
            byte[] iutZ)
        {
            using (ECDiffieHellman iut = ECDiffieHellmanFactory.Create())
                using (ECDiffieHellman cavs = ECDiffieHellmanFactory.Create())
                {
                    iut.ImportParameters(iutParameters);
                    cavs.ImportParameters(cavsParameters);

                    using (ECDiffieHellmanPublicKey cavsPublic = cavs.PublicKey)
                        using (HashAlgorithm sha256 = SHA256.Create())
                            using (HashAlgorithm sha384 = SHA384.Create())
                            {
                                Verify(iut, cavsPublic, sha256, HashAlgorithmName.SHA256, iutZ);
                                Verify(iut, cavsPublic, sha384, HashAlgorithmName.SHA384, iutZ);
                            }

                    if (ECDiffieHellmanFactory.ExplicitCurvesSupported)
                    {
                        iutParameters.Curve = explicitCurve;
                        iut.ImportParameters(iutParameters);

                        // IUT is explicit, CAVS is named, but they're the same key.
                        // If this test ever starts throwing CryptographicException we can guard it.
                        // Support is entirely left up to the library.
                        // It was kind of surprising that it worked.
                        using (ECDiffieHellmanPublicKey cavsPublic = cavs.PublicKey)
                            using (HashAlgorithm sha256 = SHA256.Create())
                                using (HashAlgorithm sha512 = SHA512.Create())
                                {
                                    bool trySecondCase = true;

                                    try
                                    {
                                        Verify(iut, cavsPublic, sha256, HashAlgorithmName.SHA256, iutZ);
                                    }
                                    catch (CryptographicException)
                                    {
                                        // This is expected to work on Windows.
                                        // On Linux (via OpenSSL) it is less predictable, since it fails with
                                        // EVP_PKEY_derive_set_peer:different parameters if one key uses
                                        // the GFp_simple routines and another uses GFp_nist or GFp_mont (or,
                                        // one presumes, something custom from an HSM) even if they actually
                                        // represent the same curve.
                                        //
                                        // secp256r1 and secp521r1 both succeed this block, secp384r1 fails.
                                        if (OperatingSystem.IsWindows())
                                        {
                                            throw;
                                        }

                                        trySecondCase = false;
                                    }

                                    // If the first one failed, don't try the second.
                                    // If the first one passed, the second should, too.
                                    if (trySecondCase)
                                    {
                                        Verify(iut, cavsPublic, sha512, HashAlgorithmName.SHA512, iutZ);
                                    }
                                }

                        cavsParameters.Curve = explicitCurve;
                        cavs.ImportParameters(cavsParameters);

                        // Explicit, explicit; over the same curve.
                        using (ECDiffieHellmanPublicKey cavsPublic = cavs.PublicKey)
                            using (HashAlgorithm sha384 = SHA384.Create())
                                using (HashAlgorithm sha512 = SHA512.Create())
                                {
                                    Verify(iut, cavsPublic, sha384, HashAlgorithmName.SHA384, iutZ);
                                    Verify(iut, cavsPublic, sha512, HashAlgorithmName.SHA512, iutZ);
                                }
                    }
                }
        }