Example #1
0
 static OkcCNHelper()
 {
     api_key = SQL.get_value("cnokc_api_key");
     secret_key = SQL.get_value("cnokc_secret_key");
     hash_mark = new HMACSHA512(Encoding.ASCII.GetBytes(SQL.get_value("cnokc_hash_key")));
     nonce = UnixTime.unix_now;
 }
Example #2
0
 static HuobiHelper()
 {
     api_key = SQL.get_value("huobi_api_key");
     secret_key = SQL.get_value("houbi_secret_key");
     hash_mark = new HMACSHA512(Encoding.ASCII.GetBytes(SQL.get_value("huobi_hash_key")));
     nonce = UnixTime.unix_now;
 }
Example #3
0
 static BtctradeHelper()
 {
     api_key = SQL.get_value("btctrade_api_key");
     secret_key = SQL.get_value("btctrade_secret_key");
     hash_mark = new HMACSHA512(Encoding.ASCII.GetBytes(SQL.get_value("btctrade_hash_key")));
     nonce = UnixTime.unix_now;
 }
Example #4
0
        public async Task <ActionResult <UserDto> > Login(LoginDto loginDto)
        {
            var user = await _context.User.SingleOrDefaultAsync(x => x.UserName == loginDto.UserName.ToLower());

            if (user == null)
            {
                return(Unauthorized("UserName or Password Do not match! Please try again"));
            }

            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("UserName or Password Do not match! Please try again"));
                }
            }
            return(new UserDto {
                UserName = user.UserName,
                Token = _tokenService.CreateToken(user)
            });
        }
        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));
        }
Example #6
0
        public async Task <ActionResult <UserDto> > 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(System.Text.Encoding.UTF8.GetBytes(loginDto.Password));

            for (int i = 0; i < ComputeHash.Length; i++)
            {
                if (ComputeHash[i] != user.PasswordHash[i])
                {
                    return(Unauthorized("Invalid Password"));
                }
            }
            return(new UserDto
            {
                Username = user.UserName,
                Token = _tokenService.CreateToken(user)
            });
        }
Example #7
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)
            });
        }
Example #8
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> > Login(LoginDto model)
        {
            var user = await _context.Users.FirstOrDefaultAsync(x => x.UserName == model.Username.ToLower());

            if (user == null)
            {
                return(Unauthorized("username doesn't exists"));
            }
            using var hmac = new HMACSHA512(user.PasswordSalt);
            var computedhash = hmac.ComputeHash(Encoding.UTF8.GetBytes(model.Password));

            for (int i = 0; i < computedhash.Length; i++)
            {
                if (computedhash[i] != user.PasswordHash[i])
                {
                    return(Unauthorized("Invalid Password"));
                }
            }
            return(new UserDto
            {
                Username = user.UserName,
                Token = _tokenservice.CreateToken(user)
            });
        }
        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)
            });
        }
Example #11
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)
            });
        }
Example #12
0
        public async Task <ActionResult <UserDto> > Login(LoginDto loginDto)
        {
            var user = await _context.User.SingleOrDefaultAsync(x => x.UserName == loginDto.Username);

            if (user == null)
            {
                return(Unauthorized("'" + loginDto.Username + "' is an invalid username"));
            }

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

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

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

            return(new UserDto
            {
                Username = user.UserName,
                Token = _tokenService.CreateToken(user)
            });
        }
Example #13
0
        public bool VerifyPasswordHash(string password, string hash, string salt)
        {
            var hashBytes = Convert.FromBase64String(hash);
            var saltBytes = Convert.FromBase64String(salt);

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", nameof(password));
            }
            if (hashBytes.Length != 64)
            {
                throw new ArgumentException("Invalid length of password hash (64 bytes expected).", nameof(hashBytes));
            }
            if (saltBytes.Length != 128)
            {
                throw new ArgumentException("Invalid length of password salt (128 bytes expected).", nameof(saltBytes));
            }

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

            return(true);
        }
Example #14
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());
        }
Example #15
0
        public async Task <UserDto> Register(RegisterDto dto)
        {
            if (await _userRepository.UserExistsAsync(dto.Login))
            {
                throw new UnauthorizedException("Ten login jest już zajęty");
            }

            using var hmac = new HMACSHA512();
            var user = new User
            {
                Login        = dto.Login,
                PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(dto.Password)),
                PasswordSalt = hmac.Key
            };

            await _userRepository.AddAsync(user);

            return(new UserDto
            {
                Id = user.Id,
                Login = user.Login,
                Token = _tokenService.CreateToken(user)
            });
        }
Example #16
0
        public async Task <ActionResult <UserDto> > Register(RegisterDto registerDto)
        {
            if (await UserExists(registerDto.Username))
            {
                return(BadRequest("Username is taken"));
            }

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

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

            return(new UserDto
            {
                Username = user.UserName,
                Token = _tokenService.CreateToken(user)
            });
        }
Example #17
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());
        }
        public string GenerateOtp(int input)
        {
            // Since .net uses little endian numbers, we need to reverse the byte order to get big endian.
            var data = BitConverter.GetBytes((long)input);

            Array.Reverse(data);

            HMAC hmac = null;

            switch (this.digest)
            {
            case Digest.Sha256:
                hmac = new HMACSHA256();
                break;

            case Digest.Sha512:
                hmac = new HMACSHA512();
                break;

            default:     //case Digest.Sha1:
                hmac = new HMACSHA1();
                break;
            }
            hmac.Key = Base32.Decode(this.secret);
            byte[] hashedValue = hmac.ComputeHash(data);

            int  offset = hashedValue[hashedValue.Length - 1] & 0x0F;
            long result = (hashedValue[offset] & 0x7f) << 24
                          | (hashedValue[offset + 1] & 0xff) << 16
                          | (hashedValue[offset + 2] & 0xff) << 8
                          | (hashedValue[offset + 3] & 0xff) % 1000000;

            var truncatedValue = ((int)result % (int)Math.Pow(10, this.digits));

            return(truncatedValue.ToString().PadLeft(this.digits, '0'));
        }
Example #19
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);
            }
        }
Example #20
0
        /// <summary>
        /// Derives the locator.
        /// </summary>
        /// <returns>The locator.</returns>
        /// <param name="index_id">Index_id.</param>
        /// <param name="replication">Replication.</param>
        public string DeriveLocator(byte[] index_id, UInt32 replication)
        {
            string final;

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] replication_bytes = BitConverter.GetBytes(replication);
                if (replication_bytes.Length != 4)
                {
                    throw new Exception("replication length mismatch");
                }

                ms.Write(replication_bytes, 0, replication_bytes.Length);
                ms.Write(index_id, 0, index_id.Length);

                long written = ms.Position;
                using (var hmacAlgorithm = new HMACSHA512(identifier.PinpointingKey))
                {
                    byte[] result = Helpers.Cryptography.HashBlock(hmacAlgorithm, ms, 0, written);
                    final = Helpers.Encoding.ByteArrayToHexString(result);
                    return(final);
                }
            }
        }
Example #21
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));
            }
        }
Example #22
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);
        }
Example #23
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));
        }
Example #24
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);
        }
Example #25
0
        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);
        }
Example #26
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);
        }
Example #27
0
        public static async Task SeedUsers(DataContext context)
        {
            if (await context.Users.AnyAsync())
            {
                return;
            }

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

            var users = JsonSerializer.Deserialize <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("Pa$$w0rd"));
                user.PasswordSalt = hmac.Key;

                context.Users.Add(user);
            }

            await context.SaveChangesAsync();
        }
Example #28
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);
        }
        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));
        }
Example #30
0
 public static string Hash(string plainText, string privateKey, int cipherStrength)
 {
     try
     {
         byte[] KeyBytes = Encoder.GetBytes(privateKey);
         HMAC   Cipher   = null;
         if (cipherStrength == 1)
         {
             Cipher = new HMACSHA1(KeyBytes);
         }
         else if (cipherStrength == 256)
         {
             Cipher = new HMACSHA256(KeyBytes);
         }
         else if (cipherStrength == 384)
         {
             Cipher = new HMACSHA384(KeyBytes);
         }
         else if (cipherStrength == 512)
         {
             Cipher = new HMACSHA512(KeyBytes);
         }
         else
         {
             throw new Exception("Enter a valid cipher strength.");
         }
         byte[] PlainBytes  = Encoder.GetBytes(plainText);
         byte[] HashedBytes = Cipher.ComputeHash(PlainBytes);
         return(Convert.ToBase64String(HashedBytes));
     }
     catch (Exception ex)
     {
         //Don't log here.  Logging should be down in calling method.
         throw ex;
     }
 }
Example #31
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
            });
        }
    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
        {
        }
    }
        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)
            };
        }
Example #34
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;
	}
Example #35
0
 public void ProduceLegacyHmacValues()
 {
     using (var h = new HMACSHA512())
     {
         Assert.False(h.ProduceLegacyHmacValues);
         h.ProduceLegacyHmacValues = false; // doesn't throw
         Assert.Throws<PlatformNotSupportedException>(() => h.ProduceLegacyHmacValues = true);
     }
 }
Example #36
0
    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
    }