예제 #1
0
        public async Task <AppUser> CreateUser(RegisterDto registerDto)
        {
            if (await UserExists(registerDto.Username))
            {
                return(null);
            }

            using var hmac = new HMACSHA512(); //will provide hashing algorithm
            var user = new AppUser
            {
                Username     = registerDto.Username.ToLower(),
                PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(registerDto.Password)),
                PasswordSalt = hmac.Key,
                Organisation = await _dataContext.Organisations.FindAsync(registerDto.OrganisationId),
                Type         = await _dataContext.UserTypes.FindAsync(registerDto.UserTypeId),
                Firstname    = registerDto.Firstname,
                Lastname     = registerDto.Lastname
            };

            _dataContext.Users.Add(user);
            await _dataContext.SaveChangesAsync();

            return(user);
        }
예제 #2
0
        /// <summary>
        /// HmacSha512 加密
        /// </summary>
        /// <param name="clearMessage"></param>
        /// <param name="secretKeyString"></param>
        /// <returns></returns>
        protected string HmacSha512(string clearMessage, string secretKeyString)
        {
            Encoding encoder = Encoding.UTF8;

            //Transform the clear query string to a byte array
            byte[] messageBytes = encoder.GetBytes(clearMessage);

            //Transform the secret key string to a byte array
            var key = Convert.ToBase64String(encoder.GetBytes(secretKeyString));

            byte[] secretKeyBytes = encoder.GetBytes(key);

            //Init the Hmac SHA512 generator with the key
            HMACSHA512 hmacsha512 = new HMACSHA512(secretKeyBytes);

            //Hash the message
            byte[] hashValue = hmacsha512.ComputeHash(messageBytes);

            //Transform the hash bytes array to a string string
            string hmac = BitConverter.ToString(hashValue).Replace("-", "");

            //Force the case of the HMAC key to Uppercase
            return(hmac);
        }
예제 #3
0
        private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }

            if (storedHash.Length != 64)
            {
                throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
            }

            if (storedSalt.Length != 128)
            {
                throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
            }

            using (var hmac = new HMACSHA512(storedSalt))
            {
                var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != storedHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
예제 #4
0
        private string InternalQuery(NameValueDictionary args)
        {
            lock (m_nonceLock)
            {
                args.Add("nonce", GetNonce().ToString(CultureInfo.InvariantCulture));

                var dataStr = BuildPostData(args);
                var data    = Encoding.ASCII.GetBytes(dataStr);

                using (var httpContent = new FormUrlEncodedContent(args))
                {
                    using (var request = new HttpRequestMessage(HttpMethod.Post, WebApi.RootUrl + "/tapi"))
                    {
                        request.Headers.Add("Key", m_key);
                        request.Headers.Add("Sign", ByteArrayToString(m_hashMaker.ComputeHash(data)).ToLowerInvariant());
                        request.Content = httpContent;

                        var response     = WebApi.Client.SendAsync(request).Result;
                        var resultString = response.Content.ReadAsStringAsync().Result;
                        return(resultString);
                    }
                }
            }
        }
예제 #5
0
        private static string GetEncodedPassword(string password, string passwordSalt)
        {
            var encoder        = new ASCIIEncoding();
            var messageBytes   = encoder.GetBytes(password);
            var secretKeyBytes = new byte[passwordSalt.Length / 2];

            for (int index = 0; index < secretKeyBytes.Length; index++)
            {
                string byteValue = passwordSalt.Substring(index * 2, 2);
                secretKeyBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            }
            var hmacsha512 = new HMACSHA512(secretKeyBytes);

            byte[] hashValue = hmacsha512.ComputeHash(messageBytes);

            string hmac = "";

            foreach (byte x in hashValue)
            {
                hmac += String.Format("{0:x2}", x);
            }

            return(hmac.ToUpper());
        }
예제 #6
0
        public async Task <ActionResult <UserResponse> > Login(LoginUserRequest request)
        {
            var user = await _context.Users.SingleOrDefaultAsync(u => u.UserName == request.UserName.ToLower());

            if (user == null)
            {
                return(Unauthorized("Invalid username or password"));
            }

            using var hmac = new HMACSHA512(user.PasswordSalt);

            var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(request.Password));

            if (!computedHash.SequenceEqual(user.PasswordHash))
            {
                return(Unauthorized("Invalid username or password"));
            }

            return(new UserResponse
            {
                UserName = user.UserName,
                Token = _tokenService.CreateToken(user)
            });
        }
        public static Uri GetHmacedUri(string uri, string key, string[] paramsToVerify)
        {
            UriBuilder          result         = new UriBuilder(uri);
            NameValueCollection param          = HttpUtility.ParseQueryString(result.Query);
            NameValueCollection verifiedParams = HttpUtility.ParseQueryString(string.Empty);

            foreach (string str in paramsToVerify)
            {
                verifiedParams[str] = HttpUtility.UrlEncode(param[str]);
            }

            string pathAndQuery = result.Path + "?" + verifiedParams.ToString();

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[]     keyByte    = encoding.GetBytes(key);
            HMACSHA512 hmacsha512 = new HMACSHA512(keyByte);

            byte[] computeHash = hmacsha512.ComputeHash(encoding.GetBytes(pathAndQuery));
            string hash        = BitConverter.ToString(computeHash).Replace("-", string.Empty).ToLower();

            verifiedParams["hmac"] = hash;
            result.Query           = verifiedParams.ToString();
            return(result.Uri);
        }
예제 #8
0
        public static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
        {
            if (storedHash.Length != 64)
            {
                throw new AppException("Invalid length of password hash (64 bytes expected).");
            }
            if (storedSalt.Length != 128)
            {
                throw new AppException("Invalid length of password salt (128 bytes expected).");
            }

            using (var hmac = new HMACSHA512(storedSalt))
            {
                var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != storedHash[i])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
예제 #9
0
        public async Task <ActionResult <AppUser> > Login(LoginDto loginDto)
        {
            var user = await _context.Users
                       .SingleOrDefaultAsync(x => x.UserName == loginDto.Username);

            if (user == null)
            {
                return(Unauthorized("Invalid username"));
            }

            using var hmac = new HMACSHA512(user.PasswordSalt);

            var ComputeHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(loginDto.password));

            for (int i = 0; i < ComputeHash.Length; i++)
            {
                if (ComputeHash[i] != user.PasswordHash[i])
                {
                    return(Unauthorized("Invalid password"));
                }
            }

            return(user);
        }
        public async Task <ActionResult <UserDto> > Register(RegisterDto registerDto)
        {
            if (await UserExists(registerDto.Username))
            {
                return(BadRequest("User nam is taken"));
            }

            using var hmac = new HMACSHA512();
            var user = new AppUser
            {
                UserName     = registerDto.Username.ToLower(),
                passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(registerDto.Password)),
                passwordSlat = hmac.Key
            };

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return(new UserDto
            {
                Username = user.UserName,
                Token = _tokenService.CreateToken(user)
            });
        }
예제 #11
0
        public async Task <ActionResult <AppUser> > Login(LoginDTO loginDTo)
        {
            AppUser user = await __context.MyProperty.SingleOrDefaultAsync(x => x.UserName == loginDTo.Username.ToLower());

            if (user == null)
            {
                return(Unauthorized("invalid username"));
            }


            using HMAC hMAC = new HMACSHA512(user.PasswordSalt);
            var Computedpassword = hMAC.ComputeHash(Encoding.UTF8.GetBytes(loginDTo.Password));

            for (int i = 0; i < Computedpassword.Length; i++)
            {
                if (Computedpassword[i] != user.PasswordHash[i])
                {
                    return(Unauthorized("Wrong password"));
                }
            }


            return(user);
        }
예제 #12
0
파일: rollin.cs 프로젝트: nrkquebec/DiceBot
        new public static decimal sGetLucky(string server, string client, int nonce)
        {
            HMACSHA512  betgenerator = new HMACSHA512();
            List <byte> serverb      = new List <byte>();

            for (int i = 0; i < server.Length; i++)
            {
                serverb.Add(Convert.ToByte(server[i]));
            }


            List <byte> buffer = new List <byte>();
            string      msg    = client;

            foreach (char c in msg)
            {
                buffer.Add(Convert.ToByte(c));
            }
            betgenerator.Key = buffer.ToArray();
            byte[] hash = betgenerator.ComputeHash(serverb.ToArray());

            StringBuilder hex = new StringBuilder(hash.Length * 2);

            foreach (byte b in hash)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            string          hashres = hex.ToString();
            int             start   = (hashres.ToString().Length / 2) - 4;
            string          s       = hashres.ToString().Substring(start, 8);
            UInt32          seed    = UInt32.Parse(s, System.Globalization.NumberStyles.HexNumber);
            MersenneTwister twist   = new MersenneTwister(seed);
            int             t4      = (int)(twist.genrand_real2() * 100);

            return(t4);
        }
예제 #13
0
        public async Task <ActionResult <UserDto> > Register(RegisterDto registerDto)
        {
            if (await UserExists(registerDto.Username.ToLower()))
            {
                return(BadRequest("User Name is taken!"));
            }
            var user = _maper.Map <AppUser>(registerDto);

            using var hmac = new HMACSHA512();

            user.UserName     = registerDto.Username.ToLower();
            user.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(registerDto.Password));
            user.PasswordSalt = hmac.Key;

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return(new UserDto
            {
                Username = user.UserName,
                Token = _tokenService.CreateToken(user),
                KnownAs = user.KnownAs
            });
        }
        public async Task<ActionResult<UserDto>> Register(RegisterDto registerDto)
        // public async Task<ActionResult<AppUser>> Register(string username, string password)
        {
            if (await UserExists(registerDto.Username)) 
            return BadRequest ("Username is Taken");

            using var hmac = new HMACSHA512(); //metode hashing
            var user = new AppUser
            {
                Username = registerDto.Username.ToLower(),
                PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(registerDto.Password)),
                PasswordSalt = hmac.Key
            };

            _context.Users.Add(user);
            await _context.SaveChangesAsync(); //save PasswordHash, PasswordSalt dan username

            // return user;
            return new UserDto
            {
                Username = user.Username,
                Token = _tokenService.CreateToken(user)
            };
        }
    public string post(String url, String parameters, String key, String secret)
    {
        try
        {
            // lock (objLock)
            {
                Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                parameters = "?nonce=" + unixTimestamp + "&" + parameters;
                Logger.log(url + parameters);
                var request = (HttpWebRequest)WebRequest.Create(url + parameters);

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                var data = Encoding.ASCII.GetBytes(url + parameters);

                HMACSHA512 encryptor = new HMACSHA512();
                encryptor.Key = Encoding.ASCII.GetBytes(secret);
                String sign = Utils.ByteToString(encryptor.ComputeHash(data)).ToLower();

                request.Headers["apisign"] = sign;
                request.Method             = "POST";
                var    response = (HttpWebResponse)request.GetResponse();
                String result   = new StreamReader(response.GetResponseStream()).ReadToEnd();

                Logger.log(result);
                return(result);
            }
        }
        catch (Exception ex)
        {
            Logger.log("ERROR POST " + ex.Message + ex.StackTrace);
            return(null);
        }
        finally
        {
        }
    }
예제 #16
0
파일: Seed.cs 프로젝트: SiJiP/DatingApp
        public static async Task SeedUser(DataContext context)
        {
            if (await context.Users.AnyAsync())
            {
                return;
            }

            var userData = await System.IO.File.ReadAllTextAsync("Data/UserSeedData.json");

            var users = JsonConvert.DeserializeObject <List <AppUser> >(userData);

            foreach (var user in users)
            {
                using var hmac = new HMACSHA512();

                user.UserName     = user.UserName.ToLower();
                user.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes("qwerty"));
                user.PasswordSalt = hmac.Key;

                context.Users.Add(user);
            }

            await context.SaveChangesAsync();
        }
예제 #17
0
        public async Task <ActionResult <UserDto> > Login(LoginDto loginDto)
        {
            var user = await _context.Users.SingleOrDefaultAsync(x => x.UserName == loginDto.username.ToLower());

            if (user == null)
            {
                return(Unauthorized("Invalid username"));
            }

            using var hmac = new HMACSHA512(user.PasswordSalt);
            var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(loginDto.password));

            for (int i = 0; i < computedHash.Length; i++)
            {
                if (computedHash[i] != user.PasswordHash[i])
                {
                    return(Unauthorized("Invalid passwrod"));
                }
            }
            return(new UserDto {
                Username = user.UserName,
                Token = _tokenService.CreateToken(user)
            });
        }
예제 #18
0
        private static byte[] ComputeHmac(this HashAlgorithmEnum algorithm, byte[] key, byte[] input)
        {
            KeyedHashAlgorithm hmacAlgo = new HMACMD5();

            switch (algorithm)
            {
            case HashAlgorithmEnum.Md5: hmacAlgo = new HMACMD5(key);
                break;

            case HashAlgorithmEnum.Sha1: hmacAlgo = new HMACSHA1(key);
                break;

            case HashAlgorithmEnum.Sha2256: hmacAlgo = new HMACSHA256(key);
                break;

            case HashAlgorithmEnum.Sha2384: hmacAlgo = new HMACSHA384(key);
                break;

            case HashAlgorithmEnum.Sha2512: hmacAlgo = new HMACSHA512(key);
                break;
            }

            return(hmacAlgo.ComputeHash(input));
        }
예제 #19
0
        public async Task <ActionResult <UserDto> > LoginAsync(LoginDto loginDto)
        {
            var user = await _context.Users.SingleOrDefaultAsync(x => x.UserName == loginDto.Username);

            if (user == null)
            {
                return(Unauthorized("Invalid username"));
            }

            using var hmac = new HMACSHA512(user.PasswordSalt);

            var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(loginDto.Password));

            if (computedHash.Where((t, i) => t != user.PasswordHash[i]).Any())
            {
                return(Unauthorized("Invalid password"));
            }

            return(new UserDto
            {
                Username = user.UserName,
                Token = _tokenService.CreateToken(user)
            });
        }
예제 #20
0
        public async Task <IActionResult> UpdateUser(UserUpdateDto userUpdateDto)
        {
            var updateUser = _userRepository.Find(x => x.UserId == userUpdateDto.UserId);

            if (updateUser == null)
            {
                return(BadRequest("User Cant updated"));
            }
            else
            {
                using var hmac = new HMACSHA512();
                var addUser = _mapper.Map <User>(userUpdateDto);


                updateUser = _mapper.Map <User>(userUpdateDto);

                updateUser.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(userUpdateDto.Password));
                updateUser.PasswordSalt = hmac.Key;

                await _userRepository.UpdateAsync(updateUser);

                return(Ok(updateUser));
            }
        }
예제 #21
0
        public async Task <ActionResult <UserDto> > Register(RegisterDto registerDto)
        {
            if (await UserExists(registerDto.Username))
            {
                return(BadRequest("❌ username taken ❌"));
            }

            using var hmac = new HMACSHA512(); // disposes itself :)
            var user = new AppUser
            {
                UserName     = registerDto.Username.ToLower(),
                PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(registerDto.Password)),
                PasswordSalt = hmac.Key
            };

            _context.Users.Add(user);          // track this object in entity framework, does not yet add to db
            await _context.SaveChangesAsync(); // NOW we save to the db heehee

            return(new UserDto
            {
                Username = user.UserName,
                Token = _tokenService.CreateToken(user)
            });
        }
        private void btCalculateHash_Click(object sender, EventArgs e)
        {
            //TH - Grab the "Response" segment of the rawResponse string.
            var json_resp_string = txtParsedResponse.Text;

            //TH - You will need your Client Secret to hash the "Response".
            string clientSecret = "wtC5Ns0jbtiNA8sP";

            //TH - Set your variables
            Byte[] computedHash;
            string computedHashString = string.Empty;

            //TH - Build the hmac using the Client Secret.
            HMACSHA512 hmac = new HMACSHA512(Encoding.ASCII.GetBytes(clientSecret));

            //TH - Compute the hash of the "Response" segment.
            computedHash = hmac.ComputeHash(Encoding.ASCII.GetBytes(json_resp_string));

            //TH - Convert the hash to Base64.
            computedHashString = Convert.ToBase64String(computedHash);

            //TH - Display the hashed "Response" segment for comparison to original hash.
            txtCalculatedHash.Text = computedHashString;
        }
        public override Dictionary <string, string> AddAuthenticationToHeaders(string uri, HttpMethod method, Dictionary <string, object> parameters, bool signed, PostParameters postParameterPosition, ArrayParametersSerialization arraySerialization)
        {
            if (!signed)
            {
                return(new Dictionary <string, string>());
            }

            if (Credentials.Key == null)
            {
                throw new ArgumentException("ApiKey/Secret needed");
            }

            var nonce     = parameters.Single(n => n.Key == "nonce").Value;
            var paramList = parameters.OrderBy(o => o.Key != "nonce");
            var pars      = string.Join("&", paramList.Select(p => $"{p.Key}={p.Value}"));

            var result = new Dictionary <string, string> {
                { "API-Key", Credentials.Key.GetString() }
            };
            var np = nonce + pars;

            byte[] nonceParamsBytes;
            using (var sha = SHA256.Create())
                nonceParamsBytes = sha.ComputeHash(Encoding.UTF8.GetBytes(np));
            var pathBytes = Encoding.UTF8.GetBytes(uri.Split(new[] { ".com" }, StringSplitOptions.None)[1]);
            var allBytes  = pathBytes.Concat(nonceParamsBytes).ToArray();

            byte[] sign;
            lock (encryptor)
            {
                sign = encryptor.ComputeHash(allBytes);
            }

            result.Add("API-Sign", Convert.ToBase64String(sign));
            return(result);
        }
예제 #24
0
        public (string result, bool Success, string Error) PostToWeb(string apiKey, string apiSecret, string apiUrl, string message)
        {
            try
            {
                HMACSHA512 hmac        = new HMACSHA512(Encoding.UTF8.GetBytes(apiSecret));
                byte[]     hashmessage = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
                string     sign        = ToHexString(hashmessage);

                Client.Headers.Set("Content-Type", "application/json");
                Client.Headers.Add("api-key", apiKey);
                Client.Headers.Add("sign", sign);

                string result = Client.UploadString(apiUrl, message);
                if (!string.IsNullOrEmpty(result))
                {
                    return(result, true, "");
                }
                return("", false, "");
            }
            catch (Exception Ex)
            {
                return("", false, Ex.Message);
            }
        }
예제 #25
0
        public async Task AddClient(AddUserDto userDto)
        {
            var userFromDb = await _userRepository.GetUserByEmail(userDto.Email);

            if (userFromDb != null)
            {
                throw new Exception("Db contains this email ");
            }

            var hmac = new HMACSHA512();

            var newUser = new UserClient
            {
                Id           = Guid.NewGuid(),
                Email        = userDto.Email,
                FirstName    = userDto.FirstName,
                LastName     = userDto.LastName,
                PhoneNumber  = userDto.PhoneNumber,
                PasswordSalt = hmac.Key,
                PasswordHash = hmac.ComputeHash(Encoding.ASCII.GetBytes(userDto.Password))
            };

            await _userRepository.AddUser(newUser);
        }
        public static string krakenQuery(string urlParams, string postData = null)
        {
            string uri    = "https://api.kraken.com/0/private/" + urlParams;
            string key    = "";
            string secret = "";
            UInt64 nonce  = (UInt64)DateTime.Now.Ticks;
            //POST Data
            string data = "nonce=" + nonce.ToString() + postData;
            //set request properties
            var request = WebRequest.Create(new Uri(uri)) as HttpWebRequest;

            request.ContentLength = data.Length;
            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            //API-Sign = Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
            byte[]     base64DecodedSecret = Convert.FromBase64String(secret);
            HMACSHA512 hashMaker           = new HMACSHA512(base64DecodedSecret);
            var        uriPathByte         = Encoding.UTF8.GetBytes("/0/private/" + urlParams);
            var        np          = nonce + Convert.ToChar(0) + data;
            var        hashed256np = sha256_hash(np);
            var        z           = new byte[uriPathByte.Count() + hashed256np.Count()];

            uriPathByte.CopyTo(z, 0);
            hashed256np.CopyTo(z, uriPathByte.Count());
            var signature = hashMaker.ComputeHash(z);

            request.Headers.Add("API-Key", key);
            //do crypto stuff, append header
            request.Headers.Add("API-Sign", Convert.ToBase64String(signature));
            //execute
            using (var writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(data);
            }
            return(read(request));
        }
예제 #27
0
        public string Encrypt(string plainText, out string cipherText)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                cipherText = default(string);
                return(string.Empty);
            }

            byte[] cipherArray;
            using (HMACSHA512 hmac = new HMACSHA512(_key))
            {
                var plainTextArray = Encoding.ASCII.GetBytes(plainText);
                var hash           = hmac.ComputeHash(plainTextArray);
                var salt           = GenerateSalt();

                using (Aes aes = Aes.Create())
                {
                    aes.Key = _key;
                    aes.IV  = _iv;

                    ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(salt, 0, salt.Length);
                            cryptoStream.Write(plainTextArray, 0, plainTextArray.Length);
                            cryptoStream.FlushFinalBlock();
                        }
                        cipherArray = memoryStream.ToArray();
                    }
                }
                cipherText = Convert.ToBase64String(cipherArray);
                return(Convert.ToBase64String(hash));
            }
        }
        public static string btceQuery(string urlParams)
        {
            string     key           = "";
            string     secret        = "";
            HMACSHA512 hashMaker     = new HMACSHA512(Encoding.ASCII.GetBytes(secret));
            UInt32     unixTimestamp = (UInt32)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            if (unixTimestamp <= lastnonce)
            {
                unixTimestamp = lastnonce + 1;
            }
            //request url parameters
            string data = "nonce=" + unixTimestamp.ToString() + urlParams;

            byte[] dataStream = Encoding.ASCII.GetBytes(data);
            //set request properties
            var request = WebRequest.Create(new Uri("https://btc-e.com/tapi")) as HttpWebRequest;

            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = dataStream.Length;
            request.Headers.Add("Key", key);
            //do crypto stuff, append header
            byte[] hashed = hashMaker.ComputeHash(dataStream);
            string sign   = BitConverter.ToString(hashed);

            sign = sign.Replace("-", "");
            request.Headers.Add("Sign", sign.ToLower());
            lastnonce = unixTimestamp;
            //execute
            var reqStream = request.GetRequestStream();

            reqStream.Write(dataStream, 0, dataStream.Length);
            reqStream.Close();
            return(read(request));
        }
예제 #29
0
        public static string CreatePasswordHash(string password, string secretKey)
        {
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }
            if (secretKey == null)
            {
                throw new ArgumentNullException(nameof(secretKey));
            }
            StringBuilder hash = new StringBuilder();

            byte[] passwordBytes  = Encoding.UTF8.GetBytes(password);
            byte[] secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
            using (var hmac = new HMACSHA512(secretKeyBytes))
            {
                byte[] hashValue = hmac.ComputeHash(passwordBytes);
                foreach (var value in hashValue)
                {
                    hash.Append(value.ToString("x2"));
                }
            }
            return(hash.ToString());
        }
예제 #30
0
        public async Task <ActionResult <UserDto> > Register(RegisterDto registerDto)
        {
            if (await UserExists(registerDto.Username))
            {
                return(BadRequest("Username is taken"));
            }

            var user = _mapper.Map <AppUser>(registerDto);

            user.UserName     = registerDto.Username.ToLower();
            using var hmac    = new HMACSHA512(); // using disposes of the object when no longer needed
            user.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(registerDto.Password));
            user.PasswordSalt = hmac.Key;

            _context.Users.Add(user);          // the user is only tracked
            await _context.SaveChangesAsync(); // now it's saved in the DB

            return(new UserDto
            {
                Username = user.UserName,
                Token = _tokenService.CreateToken(user),
                KnownAs = user.KnowsAs
            });
        }
예제 #31
0
파일: HighScores.cs 프로젝트: GarethIW/LD33
    public void SubmitScore()
    {
        SubmitPanel.SetActive(false);
        AllScorePanels.SetActive(true);

        playerId = Guid.NewGuid().ToString().Replace("-", "");
        Hashtable data = new Hashtable();
        data.Add("playerId", playerId);
        data.Add("name", Name.text.Substring(0, Name.text.Length > 15 ? 15 : Name.text.Length));
        data.Add("score", GameManager.Instance.score);

        string key = LeaderboardId + data["playerId"] + data["score"];
        var bytes = Encoding.UTF8.GetBytes(LeaderboardSecret);
        using (var hmacsha512 = new HMACSHA512(bytes))
        {
            hmacsha512.ComputeHash(Encoding.UTF8.GetBytes(key));
            data.Add("signature", ByteToString(hmacsha512.Hash).ToLower());
        }

        #if UNITY_WEBPLAYER
        Application.ExternalCall("submitScore", LeaderboardId, data["playerId"], data["name"], data["score"],
            data["signature"], "ScoreBoardCanvas", "SubmitCallback");
        #else
        HTTP.Request theRequest = new HTTP.Request("put", "https://api.leaderboards.io/leaderboard/" + LeaderboardId + "/score", data);
        theRequest.Send((request) =>
        {
            Hashtable result = request.response.Object;
            if (result != null)
            {
                SubmitCallback();
            }
        });
        #endif
    }
예제 #32
0
	public static int Main()
	{
		byte[] key = ParseHexBytes(KeyStr);
		byte[] data = ParseHexBytes(DataStr);
		byte[] hash384Correct = ParseHexBytes(Hash384CorrectStr);
		byte[] hash384Legacy  = ParseHexBytes(Hash384LegacyStr);
		byte[] hash512Correct = ParseHexBytes(Hash512CorrectStr);
		byte[] hash512Legacy  = ParseHexBytes(Hash512LegacyStr);
		
		// HMAC-SHA-384 with legacy property set -> legacy result
		//
		HMACSHA384 hm384Legacy = new HMACSHA384(key);
		hm384Legacy.ProduceLegacyHmacValues = true;
		byte[] result384Legacy = hm384Legacy.ComputeHash(data);

		if (!CompareBytes(result384Legacy, hash384Legacy))
		{
			Console.WriteLine("HMACSHA384 - ProductLegacyHmacValues=true failed");
			return FailCode;
		}
		
		// HMAC-SHA-384 with legacy property not set -> correct result
		//
		HMACSHA384 hm384Correct = new HMACSHA384(key);
		hm384Correct.ProduceLegacyHmacValues = false;
		byte[] result384Correct = hm384Correct.ComputeHash(data);

		if (!CompareBytes(result384Correct, hash384Correct))
		{
			Console.WriteLine("HMACSHA384 - ProduceLegacyHmacValues=false failed");
			return FailCode;
		}
		
		// HMAC-SHA-384 with legacy property not set -> default result (correct)
		//
		HMACSHA384 hm384Default = new HMACSHA384(key);
		byte[] result384Default = hm384Default.ComputeHash(data);
		
		if (!CompareBytes(result384Default, hash384Correct))
		{
			Console.WriteLine("HMACSHA384 - ProduceLegacyHmacValues=default failed");
			return FailCode;
		}

		// HMAC-SHA-512 with legacy property set -> legacy result
		//
		HMACSHA512 hm512Legacy = new HMACSHA512(key);
		hm512Legacy.ProduceLegacyHmacValues = true;
		byte[] result512Legacy = hm512Legacy.ComputeHash(data);

		if (!CompareBytes(result512Legacy, hash512Legacy))
		{
			Console.WriteLine("HMACSHA512 - ProduceLegacyHmacValues=true failed");
			return FailCode;
		}

		// HMAC-SHA-512 with legacy property not set -> correct result
		//
		HMACSHA512 hm512Correct = new HMACSHA512(key);
		hm512Correct.ProduceLegacyHmacValues = false;
		byte[] result512Correct = hm512Correct.ComputeHash(data);

		if (!CompareBytes(result512Correct, hash512Correct))
		{
			Console.WriteLine("HMACSHA512 - ProduceLegacyHmacValues=false failed");
			return FailCode;
		}

		// HMAC-SHA-512 with legacy property not set -> default result (correct)
		//
		HMACSHA512 hm512Default = new HMACSHA512(key);
		byte[] result512Default = hm512Default.ComputeHash(data);

		if (!CompareBytes(result512Default, hash512Correct))
		{
			Console.WriteLine("HMACSHA512 - ProduceLegacyHmacValues=default failed");
			return FailCode;
		}

		Console.WriteLine("Test passed");
		return PassCode;
	}