Exemplo n.º 1
0
        public bool Mine(Block block, byte dificulty)
        {
            block.MinerPublicKey = publicKey;
            block.Dificulty      = dificulty;

            var data = block.GetData();

            stop = false;
            while (!stop)
            {
                using (var sha256 = new SHA256Managed())
                {
                    sha256.Initialize();
                    block.Hash = sha256.ComputeHash(data);
                }

                var first = Array.FindIndex(block.Hash, b => b != 0);
                if (first >= dificulty)
                {
                    return(true);
                }

                block.Nonce++;
                Buffer.BlockCopy(BitConverter.GetBytes(block.Nonce), 0, data, data.Length - 4, 4);

                //Thread.Sleep(1);
            }

            return(false);
        }
Exemplo n.º 2
0
        private static BigInteger Hash(params BigInteger[] integers)
        {
            using (var sha256 = new SHA256Managed())
            {
                sha256.Initialize();

                for (int i = 0; i < integers.Length; i++)
                {
                    byte[] buffer  = integers[i].ToByteArray(true);
                    int    padding = buffer.Length % 4;
                    if (padding != 0)
                    {
                        Array.Resize(ref buffer, buffer.Length + (4 - padding));
                    }

                    if (i == integers.Length - 1)
                    {
                        sha256.TransformFinalBlock(buffer, 0, buffer.Length);
                    }
                    else
                    {
                        sha256.TransformBlock(buffer, 0, buffer.Length, null, 0);
                    }
                }

                byte[] hash = sha256.Hash;
                ReverseBytesAsUInt32(hash);
                return(new BigInteger(hash, true));
            }
        }
Exemplo n.º 3
0
        public static void Fill(ConcurrentDictionary <string, ConcurrentBag <File> > files, string path,
                                Func <string, File> factory, Progress pg)
        {
            var sha = new SHA256Managed();

            sha.Initialize();

            List <string> list = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).ToList();

            int count = list.Count;
            int n     = 0;

            Console.Error.WriteLine("\r" + count + " files in " + path);

            foreach (var file in list)
            {
                byte[] hashBytes = sha.ComputeHash(System.IO.File.OpenRead(file));
                string hash      = BitConverter.ToString(hashBytes).Replace("-", "");

                files.AddOrUpdate(hash, h => new ConcurrentBag <File> {
                    factory(file)
                }, (h, l) =>
                {
                    l.Add(factory(file));
                    return(l);
                });

                pg.Report(++n, count);
            }
        }
Exemplo n.º 4
0
        public string StoreData(byte[] data, string extension = null)
        {
            var hasher = new SHA256Managed();

            hasher.Initialize();

            string hash = null;

            using (hasher)
            {
                hash = HexTools.ByteArrayToHexString(hasher.ComputeHash(data));

                var targetPath = BuildPath(hash, extension);
                if (_storage.Exists(targetPath))
                {
                    return(null);
                }

                var directory = Path.GetDirectoryName(targetPath);
                _storage.CreateFolder(directory);

                var file = _storage.Open(targetPath);
                using (file)
                {
                    file.Write(data, 0, data.Length);
                }
            }

            return(hash);
        }
        //Creates and returns new User by Email
        public async Task <pix_dtmodel.Models.User> CreateNewUser(string email, string hashPass, string uname)
        {
            //Create model
            pix_dtmodel.Models.User usr = new pix_dtmodel.Models.User();

            //Make a hasher
            SHA256 hasher = new SHA256Managed();

            hasher.Initialize(); //Init the csp

            //hash email for use in the UID
            byte[] hashedBytes = hasher.ComputeHash(Encoding.ASCII.GetBytes(email));
            //Use bit Converter to get hash string
            string hashString = BitConverter.ToString(hashedBytes).Replace("-", String.Empty);

            //Set fields
            usr.Uid = "USR" + hashString;

            //Check backend for duplicates
            if (userSession.GetRecordById(usr.Uid).Result != null)
            {
                //If query that returned a result than the user is taken return error
                return(null);
            }


            //Always store email in lowercase
            usr.Email = email.ToLower();
            //Always store username in lowercase
            usr.Username = uname.ToLower();

            //Contact google boi
            FirebaseAuthLink tempLink = await auth.CreateUserWithEmailAndPasswordAsync(email, hashPass, uname, true);

            //Now we've issued a request to create a new account using the hashed password, email and then a verification email will hopefully be issued out.
            usr.TimeLeft = tempLink.ExpiresIn + ""; //Expirary Date, refresh token when this gets too low.
            //apply token.
            usr.Token = tempLink.FirebaseToken;
            //set hash
            usr.HashWord = hashPass.Replace("-", String.Empty);
            //set Google id.
            usr.Gid = tempLink.User.LocalId;
            //Finally add to dbase
            userSession.Add(usr);



            //debug line
            Console.WriteLine("User " + uname + " expires in " + usr.TimeLeft);



            //cleanup?
            hasher.Clear();
            hashedBytes = null;
            hashString  = null;


            return(usr);
        }
Exemplo n.º 6
0
        public byte[] GetData()
        {
            var transactions = GetTransactions();

            var data = new byte[32 * transactions.Length + MinerPublicKey.Length + 4 + 1];

            var offset = 0;

            foreach (var transaction in transactions)
            {
                byte[] hash;

                var td = transaction.GetData();
                using (var sha256 = new SHA256Managed())
                {
                    sha256.Initialize();
                    hash = sha256.ComputeHash(td);
                }

                Buffer.BlockCopy(hash, 0, data, offset, 32);
                offset += 32;
            }

            Buffer.BlockCopy(MinerPublicKey, 0, data, offset, MinerPublicKey.Length);
            offset += MinerPublicKey.Length;

            Buffer.BlockCopy(BitConverter.GetBytes(Nonce), 0, data, offset, 4);
            offset += 4;

            data[offset] = Dificulty;

            return(data);
        }
Exemplo n.º 7
0
        internal static byte[] CreateSaltedHash(byte[] password, byte[] salt, Int32 hashIterations)
        {
            // Seed for the pseudo-random fcn: salt + block index.
            byte[] saltAndIndex = new byte[salt.Length + BLOCK_INDEX];
            Array.Copy(salt, 0, saltAndIndex, 0, salt.Length);

            byte[] hashOutput       = new byte[BLOCK_COUNT * SHA2_256_HASH_SIZE_IN_BYTES];
            int    hashOutputOffset = 0;

            SHA256Managed hashInner = new SHA256Managed();
            SHA256Managed hashOuter = new SHA256Managed();

            // For HMAC the key must be hashed or padded with zeros so
            // that it fits into a single block of the hash algorithm being used.
            if (password.Length > SHA2_256_BLOCK_SIZE_IN_BYTES)
            {
                password = hashInner.ComputeHash(password);
            }
            byte[] key = new byte[SHA2_256_BLOCK_SIZE_IN_BYTES];
            Array.Copy(password, 0, key, 0, password.Length);

            byte[] keyInner = new byte[SHA2_256_BLOCK_SIZE_IN_BYTES];
            byte[] keyOuter = new byte[SHA2_256_BLOCK_SIZE_IN_BYTES];
            for (Int32 i = 0; i < SHA2_256_BLOCK_SIZE_IN_BYTES; i++)
            {
                keyInner[i] = (byte)(key[i] ^ INNER_HASH_PADDING);
                keyOuter[i] = (byte)(key[i] ^ OUTER_HASH_PADDING);
            }

            // For each block of desired output...
            for (Int32 hashBlock = 0; hashBlock < BLOCK_COUNT; hashBlock++)
            {
                // Seed HMAC with salt & block index.
                IncrementInteger(saltAndIndex, salt.Length);
                byte[] hmacResult = saltAndIndex;

                for (Int32 i = 0; i < hashIterations; i++)
                {
                    // Simple implementation of HMAC-SHA2-256.
                    hashInner.Initialize();
                    hashInner.TransformBlock(keyInner, 0, SHA2_256_BLOCK_SIZE_IN_BYTES, keyInner, 0);
                    hashInner.TransformFinalBlock(hmacResult, 0, hmacResult.Length);

                    byte[] temp = hashInner.Hash;

                    hashOuter.Initialize();
                    hashOuter.TransformBlock(keyOuter, 0, SHA2_256_BLOCK_SIZE_IN_BYTES, keyOuter, 0);
                    hashOuter.TransformFinalBlock(temp, 0, temp.Length);
                    hmacResult = hashOuter.Hash;

                    // XOR result into output buffer.
                    XorByteArray(hmacResult, 0, hashOutput, hashOutputOffset);
                }
                hashOutputOffset += SHA2_256_HASH_SIZE_IN_BYTES;
            }
            byte[] result = new byte[SHA2_256_HASH_SIZE_IN_BYTES];
            Array.Copy(hashOutput, 0, result, 0, SHA2_256_HASH_SIZE_IN_BYTES);
            return(result);
        }
Exemplo n.º 8
0
 public static string SHA256(string input)
 {
     if (!init)
     {
         sha.Initialize();
     }
     byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(input));
     return(BitConverter.ToString(hash).Replace("-", ""));
 }
Exemplo n.º 9
0
        private string Sha256Hash(string rawString)
        {
            var rawStringBytes = Encoding.Unicode.GetBytes(rawString);
            var hashProvider   = new SHA256Managed();

            hashProvider.Initialize();
            rawStringBytes = hashProvider.ComputeHash(rawStringBytes);
            hashProvider.Clear();
            return(Convert.ToBase64String(rawStringBytes));
        }
Exemplo n.º 10
0
        public static string HashPassword(string password)
        {
            Byte[]        passwordBytes = Encoding.Unicode.GetBytes(password);
            SHA256Managed hashProvider  = new SHA256Managed();

            hashProvider.Initialize();
            passwordBytes = hashProvider.ComputeHash(passwordBytes);
            hashProvider.Clear();
            return(Convert.ToBase64String(passwordBytes));
        }
        public static string CalculateFingerprintHash(string fingerprint)
        {
            SHA256Managed sh = new SHA256Managed();

            byte[] request = UTF8Encoding.UTF8.GetBytes(fingerprint);

            sh.Initialize();
            byte[] hash = sh.ComputeHash(request, 0, request.Length);

            return(Convert.ToBase64String(hash));
        }
Exemplo n.º 12
0
        public static void SequenceHash()
        {
            byte[] data = { 1, 2, 3, 5, 8, 13 };
            using var alg = new SHA256Managed();
            var hash = new byte[alg.HashSize / 8];

            using var builder = new HashBuilder(alg);
            builder.Add(new ChunkSequence <byte>(data, 3).ToReadOnlySequence());
            Equal(alg.HashSize / 8, builder.Build(hash));
            alg.Initialize();
            Equal(hash, alg.ComputeHash(data));
        }
Exemplo n.º 13
0
 private static byte[] GetBytes(byte[] password, byte[] salt, int iterations, int howManyBytes)
 {
     // round up
     uint cBlocks = (uint)((howManyBytes + HASH_SIZE_IN_BYTES - 1) / HASH_SIZE_IN_BYTES);
     // seed for the pseudo-random fcn: salt + block index
     byte[] saltAndIndex = new byte[salt.Length + 4];
     Array.Copy(salt, 0, saltAndIndex, 0, salt.Length);
     byte[] output = new byte[cBlocks * HASH_SIZE_IN_BYTES];
     int outputOffset = 0;
     SHA256Managed innerHash = new SHA256Managed();
     SHA256Managed outerHash = new SHA256Managed();
     // HMAC says the key must be hashed or padded with zeros
     // so it fits into a single block of the hash in use
     if (password.Length > BLOCK_SIZE_IN_BYTES)
     {
         password = innerHash.ComputeHash(password);
     }
     byte[] key = new byte[BLOCK_SIZE_IN_BYTES];
     Array.Copy(password, 0, key, 0, password.Length);
     byte[] InnerKey = new byte[BLOCK_SIZE_IN_BYTES];
     byte[] OuterKey = new byte[BLOCK_SIZE_IN_BYTES];
     for (int i = 0; i < BLOCK_SIZE_IN_BYTES; ++i)
     {
         InnerKey[i] = (byte)(key[i] ^ IPAD);
         OuterKey[i] = (byte)(key[i] ^ OPAD);
     }
     // for each block of desired output
     for (int iBlock = 0; iBlock < cBlocks; ++iBlock)
     {
         // seed HMAC with salt & block index
         _incrementBigEndianIndex(saltAndIndex, salt.Length);
         byte[] U = saltAndIndex;
         for (int i = 0; i < iterations; ++i)
         {
             // simple implementation of HMAC-SHA-256
             innerHash.Initialize();
             innerHash.TransformBlock(InnerKey, 0, BLOCK_SIZE_IN_BYTES, InnerKey, 0);
             innerHash.TransformFinalBlock(U, 0, U.Length);
             byte[] temp = innerHash.Hash; outerHash.Initialize();
             outerHash.TransformBlock(OuterKey, 0, BLOCK_SIZE_IN_BYTES, OuterKey, 0);
             outerHash.TransformFinalBlock(temp, 0, temp.Length);
             U = outerHash.Hash;
             // U = result of HMAC
             // xor result into output buffer
             _xorByteArray(U, 0, HASH_SIZE_IN_BYTES, output, outputOffset);
         }
         outputOffset += HASH_SIZE_IN_BYTES;
     }
     byte[] result = new byte[howManyBytes];
     Array.Copy(output, 0, result, 0, howManyBytes);
     return result;
 }
Exemplo n.º 14
0
        public static void HashBuilding()
        {
            byte[] data = { 1, 2, 3 };
            using var alg = new SHA256Managed();
            var hash = new byte[alg.HashSize / 8];

            using var builder = new HashBuilder(alg);
            False(builder.IsEmpty);
            builder.Add(data);
            Equal(alg.HashSize / 8, builder.Build(hash));
            alg.Initialize();
            Equal(hash, alg.ComputeHash(data));
        }
Exemplo n.º 15
0
        public static async Task HashPipe()
        {
            byte[] data = { 1, 2, 3, 5, 8, 13 };
            using var alg = new SHA256Managed();
            var hash = new byte[alg.HashSize / 8];
            var pipe = new Pipe();
            await pipe.Writer.WriteAsync(data);

            await alg.ComputeHashAsync(pipe.Reader, data.Length, hash);

            alg.Initialize();
            Equal(hash, alg.ComputeHash(data));
        }
Exemplo n.º 16
0
        public string HashPassword(string password)
        {
            password = "******" + password + "$#!%^";
            var pwdBytes = Encoding.UTF8.GetBytes(password);

            SHA256 hashAlg = new SHA256Managed();

            hashAlg.Initialize();
            var hashedBytes = hashAlg.ComputeHash(pwdBytes);
            var hash        = Convert.ToBase64String(hashedBytes);

            return(hash);
        }
Exemplo n.º 17
0
        public override uint256 GetHash()
        {
            ProcessBlock();
            sha.TransformFinalBlock(Empty, 0, 0);
            var hash1 = sha.Hash;

            Buffer.BlockCopy(sha.Hash, 0, _Buffer, 0, 32);
            sha.Initialize();
            sha.TransformFinalBlock(_Buffer, 0, 32);
            var hash2 = sha.Hash;

            return(new uint256(hash2));
        }
Exemplo n.º 18
0
        public MerkleTree()
        {
            m_BranchNodes = new List <MerkleNode>();
            m_LeafNodes   = new SortedDictionary <int, MerkleNode>();

            m_Tasks     = new List <Task>();
            m_StopWatch = new Stopwatch();

            m_Sha256Managed = new SHA256Managed();
            m_Sha256Managed.Initialize();

            m_IsMultithreaded = true;
        }
Exemplo n.º 19
0
    public static String GenerateHash(String password)
    {
        //WARNING: This code does not reflect best practice.  It is a simplistic implementation designed to introduce the concept of hashing.
        password = "******" + password + "$#!%^";
        var pwdBytes = Encoding.UTF8.GetBytes(password);

        SHA256 hashAlg = new SHA256Managed();

        hashAlg.Initialize();
        var hashedBytes = hashAlg.ComputeHash(pwdBytes);
        var hash        = Convert.ToBase64String(hashedBytes);

        return(hash);
    }
Exemplo n.º 20
0
        public byte[] CalculateHash()
        {
            using (var sha256 = new SHA256Managed())
            {
                sha256.Initialize();
                sha256.TransformBlock(this.Index);
                sha256.TransformBlock(this.PreviousHash);
                sha256.TransformBlock(this.TimeStamp.ToBinary());
                sha256.TransformBlock(this.Data);
                sha256.TransformFinalBlock(this.Nonce);

                return(sha256.Hash);
            }
        }
Exemplo n.º 21
0
        //Create a string from the input
        private static string Hash(string url)
        {
            byte[] result;
            SHA256 shaM = new SHA256Managed();

            byte[] ms = new byte[url.Length];
            for (int i = 0; i < url.Length; i++)
            {
                byte b = Convert.ToByte(url[i]);
                ms[i] = (b);
            }
            shaM.Initialize();
            result = shaM.ComputeHash(ms, 0, ms.Length);
            return(BitConverter.ToString(result));
        }
Exemplo n.º 22
0
            public static string GenUid(string email)
            {
                //Make a hasher
                SHA256 hasher = new SHA256Managed();

                hasher.Initialize(); //Init the csp

                //hash email for use in the UID
                byte[] hashedBytes = hasher.ComputeHash(Encoding.ASCII.GetBytes(email));
                //Use bit Converter to get hash string
                string hashString = BitConverter.ToString(hashedBytes).Replace("-", String.Empty);


                return("USR" + hashString);
            }
Exemplo n.º 23
0
 private byte[] ComputeBinding(ChannelHeader channelHeader, SignatureHeader signatureHeader)
 {
     using (SHA256Managed digest = new SHA256Managed())
     {
         digest.Initialize();
         digest.TransformBlock(signatureHeader.Nonce.ToByteArray(), 0, signatureHeader.Nonce.Length, null, 0);
         digest.TransformBlock(creator.ToByteArray(), 0, creator.Length, null, 0);
         byte[] epoch = BitConverter.GetBytes(channelHeader.Epoch);
         if (!BitConverter.IsLittleEndian)
         {
             epoch = epoch.Reverse().ToArray();
         }
         digest.TransformFinalBlock(epoch, 0, epoch.Length);
         return(digest.Hash);
     }
 }
Exemplo n.º 24
0
        public static async Task HashEntirePipe()
        {
            byte[] data = { 1, 2, 3, 5, 8, 13 };
            using var alg = new SHA256Managed();
            var hash = new byte[alg.HashSize / 8];
            var pipe = new Pipe();

            ThreadPool.QueueUserWorkItem(async state =>
            {
                await pipe.Writer.WriteAsync(data);
                pipe.Writer.Complete();
            });
            await alg.ComputeHashAsync(pipe.Reader, hash);

            alg.Initialize();
            Equal(hash, alg.ComputeHash(data));
        }
Exemplo n.º 25
0
        public static string HashPassword(string ClientHashedPassword)
        {
            //haslo >8 liter sprawdzane po stronie kilenta
            var    byteArrayClientPassword = Encoding.UTF8.GetBytes(ClientHashedPassword);
            SHA256 sha = new SHA256Managed();

            sha.Initialize();
            var    hashedPasswordBytes = sha.ComputeHash(byteArrayClientPassword);
            string result = "";

            foreach (var h in hashedPasswordBytes)
            {
                result += string.Format("{0:x2}", h);
            }
            sha.Clear();
            return(result);
        }
    /*
         *pHash - is the Hash Returned from the Credit Service.  You need to URLDecode the value before passing it in.
         *pSecretValue - the secret key issued when you registered at the Credit Gateway
         *pAppId - the appid issued to you when you registered at the credit gateway
         *pTransId - the transaction id your system issues to identify the purchase
         *pTransAmount - the value you are charging for this transaction
         *pAppStatus - The status of the credit transaction. Values : A = Accepted, D = Denied
         */
    public static bool VerifyServerResponseHash(String pHash, String pSecretValue, String pAppId, String pTransId, String pTransAmount, String pAppStatus)
    {
        String secretPartA = pSecretValue.Substring(0, 5);
            String secretPartB = pSecretValue.Substring(5, 5);
            String val = secretPartA + "-" + pAppId + "-" + pTransId + "-" + pTransAmount + "-" + pAppStatus + "-" + secretPartB;
            var pwdBytes = Encoding.UTF8.GetBytes(val);

            SHA256 hashAlg = new SHA256Managed();
            hashAlg.Initialize();
            var hashedBytes = hashAlg.ComputeHash(pwdBytes);
            var hash = Convert.ToBase64String(hashedBytes);

            if (hash == pHash)
                return true;
            else
                return false;
    }
        public string HashPassword(string ClientHashedPassword)
        {
            var    byteArrayClientPassword = Encoding.UTF8.GetBytes(ClientHashedPassword);
            SHA256 sha = new SHA256Managed();

            sha.Initialize();
            var hashedPasswordBytes = sha.ComputeHash(byteArrayClientPassword);
            //var hashedPasswordString = Encoding.UTF8.GetString(hashedPasswordBytes);
            string result = "";

            foreach (var h in hashedPasswordBytes)
            {
                result += string.Format("{0:x2}", h);
            }
            sha.Clear();
            //Console.WriteLine(hashedPasss);
            return(result);
        }
Exemplo n.º 28
0
        private string GetComputedSignature(DateTime now)
        {
            var header     = this.GetHeader();
            var claimSet   = this.GetClaimSet(now);
            var privateKey = this.GetPrivateKey();

            using (var hashAlg = new SHA256Managed())
            {
                hashAlg.Initialize();

                var headerAndPayload = Encode.UrlBase64Encode(header) + "." + Encode.UrlBase64Encode(claimSet);

                var headerPayloadBytes = Encoding.ASCII.GetBytes(headerAndPayload);

                var signature = Encode.UrlBase64Encode(privateKey.SignData(headerPayloadBytes, hashAlg));

                return(headerAndPayload + "." + signature);
            }
        }
Exemplo n.º 29
0
        /*
         * pSecretValue - the secret key issued when you registered at the Credit Gateway
         * pAppId - the appid issued to you when you registered at the credit gateway
         * pTransId - the transaction id your system issues to identify the purchase
         * pTransAmount - the value you are charging for this transaction
         */
        public static String GenerateClientRequestHash(String pSecretValue, String pAppId, String pTransId, String pTransAmount)
        {
            try
            {
                String secretPartA = pSecretValue.Substring(0, 5);
                String secretPartB = pSecretValue.Substring(5, 5);
                String val         = secretPartA + "-" + pAppId + "-" + pTransId + "-" + pTransAmount + "-" + secretPartB;
                var    pwdBytes    = Encoding.UTF8.GetBytes(val);

                SHA256 hashAlg = new SHA256Managed();
                hashAlg.Initialize();
                var hashedBytes = hashAlg.ComputeHash(pwdBytes);
                var hash        = Convert.ToBase64String(hashedBytes);
                return(hash);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
    /*
         *pSecretValue - the secret key issued when you registered at the Credit Gateway
         *pAppId - the appid issued to you when you registered at the credit gateway
         *pTransId - the transaction id your system issues to identify the purchase
         *pTransAmount - the value you are charging for this transaction
         */
    public static String GenerateClientRequestHash(String pSecretValue, String pAppId, String pTransId, String pTransAmount)
    {
        try
            {
                String secretPartA = pSecretValue.Substring(0, 5);
                String secretPartB = pSecretValue.Substring(5, 5);
                String val = secretPartA + "-" + pAppId + "-" + pTransId + "-" + pTransAmount + "-" + secretPartB;
                var pwdBytes = Encoding.UTF8.GetBytes(val);

                SHA256 hashAlg = new SHA256Managed();
                hashAlg.Initialize();
                var hashedBytes = hashAlg.ComputeHash(pwdBytes);
                var hash = Convert.ToBase64String(hashedBytes);
                return hash;
            }
            catch (Exception)
            {
                return null;
            }
    }
Exemplo n.º 31
0
        public static string GetJWT(string clientEmail, RSACryptoServiceProvider privateKey, DateTime now)
        {
            var payload = new {
                scope = scope,
                iss   = clientEmail,
                aud   = "https://accounts.google.com/o/oauth2/token",
                exp   = (int)(now - zeroDate + TimeSpan.FromHours(1)).TotalSeconds,
                iat   = (int)(now - zeroDate).TotalSeconds,
                //sub = "*****@*****.**",
            };

            string serializedPayload = JsonConvert.SerializeObject(payload);

            using (var hashAlg = new SHA256Managed()) {
                hashAlg.Initialize();
                var headerAndPayload   = UrlBase64Encode(serializedHeader) + "." + UrlBase64Encode(serializedPayload);
                var headerPayloadBytes = Encoding.ASCII.GetBytes(headerAndPayload);
                var signature          = UrlBase64Encode(privateKey.SignData(headerPayloadBytes, hashAlg));
                return(headerAndPayload + "." + signature);
            }
        }
Exemplo n.º 32
0
        /*
         * pHash - is the Hash Returned from the Credit Service.  You need to URLDecode the value before passing it in.
         * pSecretValue - the secret key issued when you registered at the Credit Gateway
         * pAppId - the appid issued to you when you registered at the credit gateway
         * pTransId - the transaction id your system issues to identify the purchase
         * pTransAmount - the value you are charging for this transaction
         * pAppStatus - The status of the credit transaction. Values : A = Accepted, D = Denied
         */
        public static bool VerifyServerResponseHash(String pHash, String pSecretValue, String pAppId, String pTransId, String pTransAmount, String pAppStatus)
        {
            String secretPartA = pSecretValue.Substring(0, 5);
            String secretPartB = pSecretValue.Substring(5, 5);
            String val         = secretPartA + "-" + pAppId + "-" + pTransId + "-" + pTransAmount + "-" + pAppStatus + "-" + secretPartB;
            var    pwdBytes    = Encoding.UTF8.GetBytes(val);

            SHA256 hashAlg = new SHA256Managed();

            hashAlg.Initialize();
            var hashedBytes = hashAlg.ComputeHash(pwdBytes);
            var hash        = Convert.ToBase64String(hashedBytes);

            if (hash == pHash)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 33
0
        public static string Update(string p_Username, string p_Password, string p_IPAddress)
        {
            TcpClient     l_Client   = new TcpClient("hosting.caveserver.de", 8246);
            NetworkStream l_Stream   = l_Client.GetStream();
            StreamReader  l_Reader   = new StreamReader(l_Stream);
            StreamWriter  l_Writer   = new StreamWriter(l_Stream);
            string        l_Greeting = l_Reader.ReadLine();

            if (!l_Greeting.StartsWith("*"))
            {
                l_Client.Close();
                throw new Exception("Invalid server greeting!");
            }
            #region LOGIN
            {
                l_Writer.WriteLine("LOGIN " + p_Username);
                l_Writer.Flush();
                string l_Answer1 = l_Reader.ReadLine();
                if (!l_Answer1.StartsWith("USERSALT"))
                {
                    l_Client.Close();
                    throw new Exception("Error while logging in (Stage1):\n" + l_Answer1);
                }
                string l_Answer2 = l_Reader.ReadLine();
                if (!l_Answer2.StartsWith("SERVERSALT"))
                {
                    l_Client.Close();
                    throw new Exception("Error while logging in (Stage2):\n" + l_Answer2);
                }
                try
                {
                    string l_UserSalt   = l_Answer1.Split(' ')[1];
                    string l_ServerSalt = l_Answer2.Split(' ')[1];

                    SHA256Managed SHA256 = new SHA256Managed();
                    SHA256.Initialize();
                    byte[] l_Data1   = SHA256.ComputeHash(Encoding.UTF8.GetBytes(p_Password + l_UserSalt));
                    string l_String1 = Convert.ToBase64String(l_Data1).TrimEnd('=');

                    SHA256 = new SHA256Managed();
                    SHA256.Initialize();
                    byte[] l_Data2   = SHA256.ComputeHash(Encoding.UTF8.GetBytes(l_String1 + l_ServerSalt));
                    string l_String2 = Convert.ToBase64String(l_Data2).TrimEnd('=');
                    l_Writer.WriteLine("PASSWORD " + l_String2);
                    l_Writer.Flush();
                }
                catch (Exception ex)
                {
                    throw new Exception("Error while logging in (Stage3)", ex);
                }
                string l_Answer = l_Reader.ReadLine();
                if (!l_Answer.StartsWith("OK LOGIN"))
                {
                    l_Client.Close();
                    throw new Exception("Error while logging in (Stage4):\n" + l_Answer);
                }
            }
            #endregion
            #region UPDATE
            {
                if (p_IPAddress != null)
                {
                    l_Writer.WriteLine("UPDATE " + p_IPAddress);
                    l_Writer.Flush();
                }
                else
                {
                    l_Writer.WriteLine("UPDATE");
                    l_Writer.Flush();
                }
                string l_Answer = l_Reader.ReadLine();
                l_Client.Close();
                if (!l_Answer.StartsWith("OK UPDATE"))
                {
                    throw new Exception("Error while updating ip address:\n" + l_Answer);
                }
                return(l_Answer);
            }
            #endregion
        }