public Request(SHA sha, string shaInSignature, string pspID, int orderID, decimal price, Encoding encoding, Environment environment) { if (string.IsNullOrWhiteSpace(shaInSignature)) { throw new ArgumentException("SHA-IN is required"); } if (string.IsNullOrWhiteSpace(pspID)) { throw new ArgumentException("PSPID is required"); } if (orderID < 1) { throw new ArgumentException("Invalid Order ID"); } if (price <= 0) { throw new ArgumentException("Invalid price"); } this._sha = sha; this._shaInSignature = shaInSignature; this._pspID = pspID; this._orderID = orderID; this._price = price; extrafields = new Dictionary<InFields, string>(); this.Encoding = encoding; this.Environment = environment; }
} // TODO rename to TransactionId public TransactionOutput(Key reciepient, decimal value, string parentTransactionId) { Reciepient = reciepient; Value = value; ParentTransactionId = parentTransactionId; Id = SHA.ComputeSHA256Hash(reciepient.ToString() + Value + parentTransactionId); }
public User Login(string username, string password) { using (var ctx = new BusinessContext()) { String hashedPassword = SHA.GenerateSHA256String(password); try { var query = ctx.Users.ToList(); var usr = query.Where(e => e.Username.Equals(username) && e.Password.Equals(hashedPassword)).FirstOrDefault(); return(usr); /* * var count = query.Count(); * * // Not the right way to do it. * if (count > 0) * { * User r = query.First(); * return r; * } * else * return null; */ } catch (Exception e) { Console.WriteLine(e); } return(null); } }
protected override object[] HttpCallAuth(HttpClient _http, string _method, ref string _url, object[] _keyValues) { Dictionary <string, string> _list = new Dictionary <string, string>(); for (int i = 0; i < _keyValues.Length; i += 2) { _list.Add(_keyValues[i].ToString(), _keyValues[i + 1].ToString()); } //string _time = DateTimePlus.DateTime2JSTime(DateTime.UtcNow.AddSeconds(-1)).ToString() + DateTime.UtcNow.Millisecond.ToString(); //_list.Add("timestamp", _time); string _sign = ""; foreach (var _item in _list) { _sign += $"{_item.Key}={_item.Value}&"; } if (_sign != "") { _sign = _sign.Remove(_sign.Length - 1); } _list.Add("signature", SHA.EncodeHMACSHA256ToHex(_sign, base.Secret).ToLower()); IList <string> _keyValueList = new List <string>(); foreach (KeyValuePair <string, string> _item in _list) { _keyValueList.Add(_item.Key); _keyValueList.Add(_item.Value); } _http.Headers.Add("X-MBX-APIKEY", base.Key); _http.Headers.Add("MediaType", "application/x-www-form-urlencoded"); return(_keyValueList.ToArray()); }
public void MyTestMethod() { string str = "Hello world!"; string[] types = Enum.GetNames(typeof(SHAAlgorithmTypes)); foreach (var item in types) { Console.WriteLine($"SHAAlgorithmType: {item}"); HashResult result = SHA.Encrypt((SHAAlgorithmTypes)Enum.Parse(typeof(SHAAlgorithmTypes), item), str); Type type = result.GetType(); var props = type.GetProperties(); foreach (var prop in props) { if (prop.PropertyType == typeof(string)) { Console.WriteLine($"{prop.Name}:{prop.GetValue(result, null)}"); } } Console.WriteLine(); } }
public users LoginCategory(LoginViewModel user) { var pass = SHA.GenerateSHA512String(user.Password); var result = _db.users.FirstOrDefault(e => e.email == user.Email && e.password == pass); return(result); }
public ActionResult Edit(UserEdit edit) { UserDb UserSession = (UserDb)Session["User"]; if (edit.Id == UserSession.Id) { if (ModelState.IsValid) { var editdb = db.Users.FirstOrDefault(f => f.Id == edit.Id); string Hashpassword = editdb.HashPassword; if (edit.LastPassword != null) { if (SHA.CustumSHA(edit.LastPassword) == Hashpassword && edit.NewPassword == edit.NewConfirmPassword) { Hashpassword = SHA.CustumSHA(edit.NewPassword); } } edit.ViewFromDb(editdb); editdb.HashPassword = Hashpassword; db.SaveChanges(); return(View());//helelik Accaunta return olacaq } return(View(edit)); } return(View(edit)); }
protected override object[] HttpCallAuth(HttpClient _http, string _method, ref string _url, object[] _keyValues) { Dictionary <string, string> _list = new Dictionary <string, string>(); for (int i = 0; i < _keyValues.Length - 1; i += 2) { _list.Add(_keyValues[i].ToString(), _keyValues[i + 1].ToString()); } KeyValuePair <string, string>[] _sorted = _list.ToArray().OrderBy(c => c.Key).ToArray(); string _ts = (DateTimePlus.DateTime2JSTime(DateTime.UtcNow) * 1000).ToString(); string _sign = _method + this.HttpUrl + _url + _ts; for (int i = 0; i < _sorted.Length; i++) { _sign += i == 0 ? "" : "&"; _sign += _sorted[i].Key + "=" + _sorted[i].Value; } _sign = Base64.Encode(Encoding.UTF8.GetBytes(_sign)); _sign = SHA.EncodeHMACSHA1ToBase64(_sign, base.Secret); _http.Headers.Add("FC-ACCESS-KEY", base.Key); _http.Headers.Add("FC-ACCESS-SIGNATURE", _sign); _http.Headers.Add("FC-ACCESS-TIMESTAMP", _ts); return(_keyValues); }
public bool ValidLoginUser(LoginViewModel user) { var pass = SHA.GenerateSHA512String(user.Password); var result = _db.users.FirstOrDefault(e => e.email == user.Email && e.password == pass && e.usersCategories.Id == 3); return(result == null ? false : true); }
private void createAccount() { String token = (_ticketRequired) ? ticketBox.Text : null; Tokens.IPAddress = ServerDropDownList.SelectedValue.ToString(); Tokens.ServerName = ServerDropDownList.SelectedItem.ToString(); if (_modernAuthSupport == false) { ClassicAuth.Register(registerEmail.Text, SHA.HashPassword(registerPassword.Text), token); } else { ModernAuth.Register(registerEmail.Text, registerPassword.Text, token); } if (!String.IsNullOrEmpty(Tokens.Success)) { MessageBox.Show(null, Tokens.Success, UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Warning); actionText.Text = Tokens.Success; tabControl1.Visible = true; } else { MessageBox.Show(null, Tokens.Error, UserAgent.AgentAltName, MessageBoxButtons.OK, MessageBoxIcon.Error); actionText.Text = Tokens.Error; } }
public ActionResult Index(UserSignUp SignUp) { if (ModelState.IsValid && SignUp.Condition == "true") { var userdb = db.Users.FirstOrDefault(f => f.UserName.ToUpper() == SignUp.UserName.ToUpper() || f.Mail == SignUp.Mail); if (userdb == null && SignUp.Password == SignUp.ConfirmPassword) { UserDb user = new UserDb(); SignUp.ViewFromDb(user); user.HashPassword = SHA.CustumSHA(SignUp.Password); db.Users.Add(user); db.SaveChanges(); var userCod = user.Id + 10000; user.UserCod = user.Id.ToString() + userCod.ToString(); db.UserRoles.Add(new UserRole() { UserDbId = user.Id, RoleId = 1 }); db.SaveChanges(); return(RedirectToAction("Login", "UserLogin")); } else { ViewBag.faq = db.Faqs.FirstOrDefault(f => f.FaqTitle == "Sifaris Sertleri"); return(View(SignUp)); } } ViewBag.faq = db.Faqs.FirstOrDefault(f => f.FaqTitle == "Sifaris Sertleri"); return(View(SignUp)); }
public static Address GetLegacyAddress(string _private = "", bool _mainnet = true) { _private = _private == "" ? RandomPlus.RandomHex(64) : _private; BigInteger _privateInt = BigInteger.Parse("0" + _private, NumberStyles.HexNumber); byte[] _public = Secp256k1.PrivateKeyToPublicKey(_privateInt, false); RIPEMD160Managed _ripemd = new RIPEMD160Managed(); byte[] _ripemdHashed = _ripemd.ComputeHash(SHA.EncodeSHA256(_public)); byte[] _addedVersion = new byte[_ripemdHashed.Length + 1]; _addedVersion[0] = (byte)(_mainnet ? 0x00 : 0x6f); Array.Copy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length); byte[] _shaHashed = SHA.EncodeSHA256(SHA.EncodeSHA256(_addedVersion)); Array.Resize(ref _shaHashed, 4); byte[] _result = new byte[_addedVersion.Length + _shaHashed.Length]; Array.Copy(_addedVersion, 0, _result, 0, _addedVersion.Length); Array.Copy(_shaHashed, 0, _result, _addedVersion.Length, _shaHashed.Length); string _key1 = string.Join("", (_mainnet ? "80" : "ef"), _private); string _key2 = HexPlus.ByteArrayToHexString(SHA.EncodeSHA256(SHA.EncodeSHA256(HexPlus.HexStringToByteArray(_key1))).Take(4).ToArray()); Address _address = new Address { Text = Base58.Encode(_result), Public = HexPlus.ByteArrayToHexString(_public), Private = Base58.Encode(_key1 + _key2) }; return(_address); }
public JsonResult Register(RegisterViewModel model) { DateTime localDate = DateTime.Now; if (ModelState.IsValid) { dataProvider.AddUser(new users() { name = model.Name, surname = model.Surname, email = model.Email, password = SHA.GenerateSHA512String(model.Password), registerDate = localDate, isActive = true, categoriesId = userData.GetUserCategory().Id, }); } if (ModelState.IsValid && dataProvider.ValidLoginUser(new LoginViewModel() { Email = model.Email, Password = model.Password })) { LoginHelper.CreateUser(new users() { password = model.Password, email = model.Email, categoriesId = userData.GetUserCategory().Id, }); return(Json(new { success = true })); } return(Json(model, JsonRequestBehavior.AllowGet)); }
private void btn_login_Click(object sender, EventArgs e) { try { usuario.login = txb_nome_usuario.Text; usuario.senha = txb_senha_acesso.Text; usuario.senha = SHA.GenerateSHA512String(usuario.senha); //ControleInterno controle = new ControleInterno(); //controle.autenticar(ref usuario); IOperadorREST op = new OperadorJson(); CtrlUsuario controle = new CtrlUsuario(); Conexao conexao = new Conexao() { host = "10.1.1.3" }; var currentUsuario = controle.consultar <Usuario>(usuario, op, conexao); if (currentUsuario.id == 0) { throw new Exception("Usuário inexistente."); } frm_dashboard formulario = new frm_dashboard(currentUsuario); formulario.ShowDialog(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Validando Login"); var usuario = _usuarioApplication.ObterUsuarioPorLogin(context.UserName); if (usuario != null) { Console.WriteLine($"Usuario Obtido do banco: " + usuario.Nome); } if (usuario == null) { context.Result = new GrantValidationResult(TokenRequestErrors.UnauthorizedClient, "Login inválido."); return(Task.FromResult(0)); } if (usuario.Senha != SHA.Encrypt(SHA.Algorithm.SHA512, context.Password)) { context.Result = new GrantValidationResult(TokenRequestErrors.UnauthorizedClient, "Senha inválida."); return(Task.FromResult(0)); } context.Result = new GrantValidationResult(subject: usuario.Id.ToString(), authenticationMethod: "custom", claims: AuthorizationConfig.GetClaims(usuario)); Console.WriteLine($"Usuario no Claims " + usuario.Nome); Console.ResetColor(); return(Task.FromResult(0)); }
private string generateKeyParama(string email) { DateTime now = DateTime.UtcNow; string key = email + now.ToShortDateString() + SECRET; return(SHA.ComputeSHA256Hash(key)); }
/// <summary> /// Attempts to obtain a new login from the given parameters. If possible it also sets a list of earlier readings, but doesn't crash if it wasn't possible /// </summary> /// <param name="customerId">Account number</param> /// <param name="password">Password</param> /// <returns>Tuple of success and security key</returns> public async Task <(bool, string)> NewLoginAsync(string customerId, string password) { return(await Task.Run(async() => { var key = SHA.SHA1Encrypt(string.Format("{0}{1}", customerId, _config.ApiKey)); var canConnect = await _connectService.CanConnect(); if (canConnect) { //TODO: change to something more meaningful (bool, string)result = (false, "Not ok"); var response = _client.newLogin(new NewLoginRequest() { NewLogin = new NewLogin { WebLogin = customerId, PassWord = password, EncryptedKey = key } }); result = response.ErrorCode.Equals("") ? (true, response.ResponseMessage) : (false, response.ResponseCode); if (result.Item1) { _config.Context.securityKey = result.Item2; _config.CustomerId = customerId; _config.MeterReadings = await GetMeterReadings(); } return result; } //TODO: Inconsistent with danish/english return (false, "Kunne ikke få forbindelse"); })); }
public async Task <IActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { User user = await _context.User.FirstOrDefaultAsync(u => u.Login == model.login); if (user == null) { user = new User { Login = model.login, Password = await SHA.GenerateSHA256String(model.password + model.login), addres = model.addres }; Role userRole = await _context.Roles.FirstOrDefaultAsync(r => r.Name == "User"); if (userRole != null) { user.Role = userRole; } _context.User.Add(user); await _context.SaveChangesAsync(); await Authenticate(user); return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "Некорректные логин и(или) пароль"); } } return(View(model)); }
public static void validateUser(int user_id, string login_hash) { string validate_query = "SELECT password_enc, enc_string FROM Users WHERE id = @user_id"; string _conn_str = System.Environment.GetEnvironmentVariable("sqldb_connection"); bool status = false; using (SqlConnection conn = new SqlConnection(_conn_str)) { conn.Open(); SqlCommand command = new SqlCommand(validate_query, conn); command.Parameters.AddWithValue("@user_id", user_id); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { string stored_login_hash = SHA.GenerateSHA256String((string)reader["password_enc"] + (string)reader["enc_string"]).ToLower(); if (stored_login_hash == login_hash) { status = true; } } } conn.Close(); } if (!status) { throw new UserNotVerified(user_id.ToString()); } }
private string GenerateOAuthSignature(string url, string method, ArrayList allParameters, string tokenSecret) { // The parameters must be sorted by key name before generating the signature hash //allParameters = (ArrayList)allParameters.OrderBy(s => s); //allParameters.OrderBy(s=>s). object[] sortedParameters = (object[])allParameters.OrderBy(s => s, (a, b) => ((IComparable)a).CompareTo(b)); // Get the parameters in the form of a query string string normalizedParameters = HTTPUtility.ParameterListToQueryString(sortedParameters); // Concatenate the HTTP method, URL, and parameter string string signatureBase = method + '&' + HTTPUtility.UrlEncode(url) + '&' + HTTPUtility.UrlEncode(normalizedParameters); // Get a byte array of the signatureBase byte[] data = Encoding.UTF8.GetBytes(signatureBase); // Get the key string key = consumerSecret + '&' + tokenSecret; byte[] keyBytes = Encoding.UTF8.GetBytes(key); // Compute the HMAC-SHA1 hash byte[] hashBytes = SHA.computeHMAC_SHA1(keyBytes, data); // The signature is a Base64 encoded version of the hash return(HTTPUtility.ConvertToBase64String(hashBytes)); }
public async Task <OpreationResult <Administrator> > LoginAsync(AdminLoginViewModel model) { var dbAdmin = await db.Set <Administrator>().Where(a => a.LoginName == model.LoginName).AsNoTracking().FirstOrDefaultAsync(); if (dbAdmin == null) { return(OpreationResult <Administrator> .Init(OpreationResuleType.QueryNull, null, "用户不存在")); } if (dbAdmin.Password != SHA.SHA512(model.Password).ToLower()) { return(OpreationResult <Administrator> .Init(OpreationResuleType.ValidtorError, null, "您的密码不正确")); } var updateModel = new AdministratorDto() { Id = dbAdmin.Id, LastLoginIp = model.LastLoginIp, LastLoginTime = DateTime.Now, Password = dbAdmin.Password, LoginName = dbAdmin.LoginName }; await CreateOrUpdate(updateModel); dbAdmin.Password = null; return(OpreationResult <Administrator> .Init(OpreationResuleType.Success, dbAdmin)); }
static string GetSharedAccessSignature(string keyName, string sharedAccessKey, string resource, TimeSpan tokenTimeToLive) { // http://msdn.microsoft.com/en-us/library/azure/dn170477.aspx // the canonical Uri scheme is http because the token is not amqp specific // signature is computed from joined encoded request Uri string and expiry string var exp = DateTime.UtcNow.ToUnixTimeSeconds() + (long)tokenTimeToLive.TotalSeconds; string expiry = exp.ToString(); string encodedUri = WebUtility.UrlEncode(resource); byte[] hmac = SHA.computeHMAC_SHA256(Convert.FromBase64String(sharedAccessKey), Encoding.UTF8.GetBytes(encodedUri + "\n" + expiry)); string sig = Convert.ToBase64String(hmac); if (keyName != null) { return(String.Format( "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", encodedUri, WebUtility.UrlEncode(sig), WebUtility.UrlEncode(expiry), WebUtility.UrlEncode(keyName))); } else { return(String.Format( "SharedAccessSignature sr={0}&sig={1}&se={2}", encodedUri, WebUtility.UrlEncode(sig), WebUtility.UrlEncode(expiry))); } }
public void SHA512_hash_is_equal_to_other_generator_using_default_encoding() { string wordToHash = "milk"; string milkHash = "7586A2A3DA04B9C2610906E936D0365EAA601AD8CDF26D30501AFA2A27A3D42AB0023912B488F408D457BD958EBB24140C2BA029CE93A9702D9197A6E30C331D"; Assert.AreEqual(milkHash, SHA.CreateSHA512Hash(wordToHash)); }
public bool TryDecryptLocal(byte[] encrypted, out byte[] decrypted) { decrypted = null; if (encrypted.Length <= 16 || (encrypted.Length & 0x0F) != 0) { return(false); } int fullLen = encrypted.Length - 16; byte[] encryptedActual = new byte[fullLen]; Array.Copy(encrypted, 16, encryptedActual, 0, fullLen); byte[] messageKey = new byte[16]; Array.Copy(encrypted, 0, messageKey, 0, 16); byte[] decryptedBlob = AesDecryptLocal(encryptedActual, fullLen, messageKey); if (!SHA.SHA1(decryptedBlob).CompareBytes(messageKey, 16)) { return(false); } uint dataLen = BitConverter.ToUInt32(decryptedBlob, 0); if (dataLen > decryptedBlob.Length || dataLen <= fullLen - 16 || dataLen < sizeof(uint)) { return(false); } decrypted = new byte[dataLen - 4]; Array.Copy(decryptedBlob, 4, decrypted, 0, decrypted.Length); return(true); }
public static string GenerateToken(string appkey, string uniqueId) { var guid = Guid.NewGuid(); var code = string.Format("{0}{1}{2}{3}", guid.ToString(), appkey, uniqueId, DateTime.UtcNow.Ticks); return(SHA.ComputeSHA1Hash(code)); }
public void SHA1_hash_is_equal_to_other_generator_using_default_encoding() { string wordToHash = "milk"; string milkHash = "cf5dbf0ec57dff5da56d86c45b3bdd11849a065a".ToUpperInvariant(); Assert.AreEqual(milkHash, SHA.CreateSHA1Hash(wordToHash)); }
protected override object[] HttpCallAuth(HttpClient _http, string _method, ref string _url, object[] _keyValues) { IList <object> _result = new List <object>(); JObject _json = new JObject(); Dictionary <string, string> _list = new Dictionary <string, string>(); for (int i = 0; i < _keyValues.Length; i += 2) { _json[_keyValues[i].ToString()] = _keyValues[i + 1].ToString(); _result.Add(_keyValues[i]); _result.Add(_keyValues[i + 1]); } string _sign = ""; string _time = DateTime.UtcNow.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"); _sign = $"{_time}{_method.ToUpper()}{_url}"; if (_keyValues.Length > 0) { _sign += _json.ToString(Newtonsoft.Json.Formatting.None); } _list.Add("timestamp", _time); _list.Add("method", _method.ToUpper()); _list.Add("requestPath", _url); _sign = SHA.EncodeHMACSHA256ToBase64(_sign, this.Secret); _http.Headers.Add("OK-ACCESS-KEY", this.Key); _http.Headers.Add("OK-ACCESS-SIGN", _sign); _http.Headers.Add("OK-ACCESS-TIMESTAMP", _time); _http.Headers.Add("OK-ACCESS-PASSPHRASE", this.PassPhrase); return(_result.ToArray()); }
string GetSharedAccessSignature(string keyName, string sharedAccessKey, string resource, TimeSpan tokenTimeToLive) { // http://msdn.microsoft.com/en-us/library/azure/dn170477.aspx // the canonical Uri scheme is http because the token is not amqp specific // signature is computed from joined encoded request Uri string and expiry string #if NETMF // needed in .Net Micro Framework to use standard RFC4648 Base64 encoding alphabet System.Convert.UseRFC4648Encoding = true; #endif string expiry = ((long)(DateTime.UtcNow - new DateTime(UtcReference, DateTimeKind.Utc) + tokenTimeToLive).TotalSeconds()).ToString(); string encodedUri = HttpUtility.UrlEncode(resource); byte[] hmac = SHA.computeHMAC_SHA256(Convert.FromBase64String(sharedAccessKey), Encoding.UTF8.GetBytes(encodedUri + "\n" + expiry)); string sig = Convert.ToBase64String(hmac); if (keyName != null) { return(Fx.Format( "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", encodedUri, HttpUtility.UrlEncode(sig), HttpUtility.UrlEncode(expiry), HttpUtility.UrlEncode(keyName))); } else { return(Fx.Format( "SharedAccessSignature sr={0}&sig={1}&se={2}", encodedUri, HttpUtility.UrlEncode(sig), HttpUtility.UrlEncode(expiry))); } }
public ActionResult Register(RegisterViewModel model) { DateTime localDate = DateTime.Now; if (ModelState.IsValid) { dataProvider.AddUser(new users() { name = model.Name, surname = model.Surname, email = model.Email, password = SHA.GenerateSHA512String(model.Password), registerDate = localDate, isActive = true, categoriesId = userData.GetUserCategory().Id, }); } if (ModelState.IsValid && dataProvider.ValidLoginUser(new LoginViewModel() { Email = model.Email, Password = model.Password })) { LoginHelper.CreateUser(new users() { password = model.Password, email = model.Email, categoriesId = userData.GetUserCategory().Id, }); return(RedirectToAction("UserList", "Admin")); } return(View(model)); }
public ClaimsPrincipal GetPrincipal(string secretKey, string token) { string sha = SHA.GenerateSHA256(secretKey); SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(sha)); TokenValidationParameters tokenValidationParameters = new TokenValidationParameters { ValidAudiences = new[] { Audience }, ValidIssuers = new[] { Issuer }, IssuerSigningKey = signingKey, RequireExpirationTime = true }; SecurityToken securityToken; JwtSecurityTokenHandler securityTokenHandler = new JwtSecurityTokenHandler(); ClaimsPrincipal principal = securityTokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken); JwtSecurityToken jwtSecurityToken = securityToken as JwtSecurityToken; if (jwtSecurityToken != null) { DateTime validTo = jwtSecurityToken.ValidTo; if (validTo < DateTime.UtcNow) { throw new SecurityTokenExpiredException(); } } return(principal); }
public static Address GenerateAddress(string _privateKey = "", bool _mainNet = true) { _privateKey = _privateKey == "" ? RandomPlus.RandomHex(64) : _privateKey; BigInteger _privateInt = BigInteger.Parse("0" + _privateKey, System.Globalization.NumberStyles.HexNumber); byte[] _publicKey = Secp256k1.PrivateKeyToPublicKey(_privateInt); SHA256Managed _sha256 = new SHA256Managed(); RIPEMD160Managed _ripemd = new RIPEMD160Managed(); byte[] _ripemdHashed = _ripemd.ComputeHash(_sha256.ComputeHash(_publicKey)); byte[] _addedVersion = new byte[_ripemdHashed.Length + 1]; _addedVersion[0] = (byte)(_mainNet ? 0x00 : 0x6f); Array.Copy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length); byte[] _shaHashed = _sha256.ComputeHash(_sha256.ComputeHash(_addedVersion)); Array.Resize(ref _shaHashed, 4); byte[] _result = new byte[_addedVersion.Length + _shaHashed.Length]; Array.Copy(_addedVersion, 0, _result, 0, _addedVersion.Length); Array.Copy(_shaHashed, 0, _result, _addedVersion.Length, _shaHashed.Length); string _key1 = string.Join("", (_mainNet ? "80" : "ef"), _privateKey); string _key2 = HexPlus.ByteArrayToHexString(SHA.EncodeSHA256(SHA.EncodeSHA256(HexPlus.HexStringToByteArray(_key1))).Take(4).ToArray()); Address _address = new Address(); _address.Text = Base58.Encode(_result); _address.PublicKey = HexPlus.ByteArrayToHexString(_publicKey); _address.PrivateKey = Base58.Encode(_key1 + _key2); _address.Text = (_mainNet ? (_address.Text.StartsWith("1") ? "" : "1") : "") + _address.Text; return(_address); }
public Response(SHA sha, string shaOutSignature, string shaSign, Encoding encoding) { if (string.IsNullOrWhiteSpace(shaSign)) { throw new ArgumentException("SHA is required"); } if (string.IsNullOrWhiteSpace(shaOutSignature)) { throw new ArgumentException("SHA OUT Signature is required"); } this._shaSign = shaSign; this._sha = sha; this._shaOutSignature = shaOutSignature; fields = new Dictionary<OutFields, string>(); this.Encoding = encoding; }
public static string GenerateHash(string value, Encoding encoding, SHA hashAlgorithm) { HashAlgorithm Algorithm; System.Text.Encoding TextEncoding; switch (hashAlgorithm) { case SHA.SHA1: Algorithm = new SHA1CryptoServiceProvider(); break; case SHA.SHA256: Algorithm = new SHA256CryptoServiceProvider(); break; case SHA.SHA512: Algorithm = new SHA512CryptoServiceProvider(); break; default: Algorithm = new SHA1CryptoServiceProvider(); break; } switch (encoding) { case Encoding.UTF8: TextEncoding = new System.Text.UTF8Encoding(); break; case Encoding.ISO_8859_1: TextEncoding = System.Text.Encoding.GetEncoding("iso-8859-1"); break; default: TextEncoding = new System.Text.UTF8Encoding(); break; } byte[] byteSourceText = TextEncoding.GetBytes(value); byte[] byteHash = Algorithm.ComputeHash(byteSourceText); string delimitedHexHash = BitConverter.ToString(byteHash); string hexHash = delimitedHexHash.Replace("-", ""); return hexHash; }
public Response(SHA sha, string shaOutSignature, string shaSign) : this(sha, shaOutSignature, shaSign, Encoding.UTF8) { }
public Request(SHA sha, string shaInSignature, string pspID, int orderID, decimal price) : this(sha, shaInSignature, pspID, orderID, price, Encoding.UTF8, Environment.Test) { }