protected override void FillUpdateParams(CustomSqlCommand in_sp) { base.FillUpdateParams(in_sp); Id = _doc.Id; in_sp.AddParameter("@in_docId", Id); in_sp.AddParameter("@in_timeSold", UnixEpoch.FromDateTime(_timeSold)); in_sp.AddParameter("@in_articleId", _articleId); in_sp.AddParameter("@in_articleName", _articleName); in_sp.AddParameter("@in_articlePriceOfPurchase", _articlePriceOfPurchase); in_sp.AddParameter("@in_articlePriceOfSell", _articlePriceOfSell); in_sp.AddParameter("@in_pointOfSaleId", _pointOfSaleId); in_sp.AddParameter("@in_pointOfSaleName", _pointOfSaleName); in_sp.AddParameter("@in_unitPrice", _unitPrice); in_sp.AddParameter("@in_unitCount", _unitCount); in_sp.AddParameter("@in_cellX", _cellX); in_sp.AddParameter("@in_cellY", _cellY); in_sp.AddParameter("@in_paymentByCard", _paymentByCard ? 1 : 0); }
public void DecodeToObject_Should_Throw_Exception_Before_NotBefore_Becomes_Valid() { var serializer = new JsonNetSerializer(); var dateTimeProvider = new UtcDateTimeProvider(); var validTor = new JwtValidator(serializer, dateTimeProvider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validTor, urlEncoder); var now = dateTimeProvider.GetNow(); var nbf = UnixEpoch.GetSecondsSince(now.AddHours(1)); var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder); var token = encoder.Encode(new { nbf }, "ABC"); Action action = () => decoder.DecodeToObject <Customer>(token, "ABC", verify: true); Assert.Throws <SignatureVerificationException>(action); }
public void DecodeToObject_Should_Throw_Exception_On_Expired_Claim() { var serializer = new JsonNetSerializer(); var dateTimeProvider = new UtcDateTimeProvider(); var validTor = new JwtValidator(serializer, dateTimeProvider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validTor, urlEncoder); var now = dateTimeProvider.GetNow(); var exp = UnixEpoch.GetSecondsSince(now.AddHours(-1)); var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder); var token = encoder.Encode(new { exp }, "ABC"); Action action = () => decoder.DecodeToObject <Customer>(token, "ABC", verify: true); Assert.Throws <TokenExpiredException>(action); }
/// <summary> /// Generate custom B2C Token /// </summary> public string GenerateCustomToken() { var privateKey = TestConfiguration.FakeTokenPrivateKey; var header = new Dictionary <string, object> { { "typ", "JWT" }, { "kid", "GvnPApfWMdLRi8PDmisFn7bprKu" } }; var provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var tokenIssued = UnixEpoch.GetSecondsSince(now); var expiry = tokenIssued + 3600; var payload = new Dictionary <string, object> { { "aud", $"{B2cConfig.TenantId}" }, { "iss", $"{B2cConfig.MicrosoftOnlineLoginUrl}{B2cConfig.TenantId}/v2.0/" }, { "iat", tokenIssued }, { "nbf", tokenIssued }, { "exp", expiry }, { "aio", "E2ZgYOD/bNfNzDaJjWGlunhesLAUAA==" }, { "azp", $"{B2cConfig.ClientId}" }, { "azpacr", "1" }, { "oid", "da599026-93fc-4d2a-92c8-94b724e26176" }, { "rh", "0.AT8A2Ihb28pF7EqgbHH88S3oGvAwypvZIDhLmevHr_a38FFAAAA." }, { "sub", "da599026-93fc-4d2a-92c8-94b724e26176" }, { "tid", $"{B2cConfig.TenantId}" }, { "uti", "C6oLcfz8e0mzZbv-6pRwAQ" }, { "ver", "2.0" } }; var privateKeyBytes = Convert.FromBase64String(privateKey); using var rsa = RSA.Create(); rsa.ImportRSAPrivateKey(privateKeyBytes, out _); IJwtAlgorithm algorithm = new RS256Algorithm(rsa, rsa); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return(encoder.Encode(header, payload, "")); }
public void DecodeToObject_Should_Decode_Token_After_NotBefore_Becomes_Valid() { var dateTimeProvider = new UtcDateTimeProvider(); const string key = TestData.Key; var serializer = new JsonNetSerializer(); var validator = new JwtValidator(serializer, new UtcDateTimeProvider()); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder); var now = dateTimeProvider.GetNow(); var nbf = UnixEpoch.GetSecondsSince(now); var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder); var token = encoder.Encode(new { nbf }, key); decoder.DecodeToObject <Customer>(token, key, verify: true); }
/// <summary> /// Gets key bundle from args or uses a default key bundle /// </summary> /// <param name="args"> the input arguments of the console program </param> /// <returns> key bundle </returns> public KeyBundle GetKeyBundle() { // Default Key Bundle var defaultKeyBundle = new KeyBundle { Key = new JsonWebKey() { Kty = GetKeyType(), }, Attributes = new KeyAttributes() { Enabled = true, Expires = UnixEpoch.FromUnixTime(int.MaxValue), NotBefore = UnixEpoch.FromUnixTime(0), } }; return(defaultKeyBundle); }
/// <summary> /// Gets the import key bundle /// </summary> /// <returns> key bundle </returns> internal KeyBundle GetImportKeyBundle() { var rsa = new RSACryptoServiceProvider(2048); var webKey = CreateJsonWebKey(rsa.ExportParameters(true)); // Default import Key Bundle var importKeyBundle = new KeyBundle { Key = webKey, Attributes = new KeyAttributes() { Enabled = true, Expires = UnixEpoch.FromUnixTime(int.MaxValue), NotBefore = UnixEpoch.FromUnixTime(0), } }; return(importKeyBundle); }
/// <summary> /// Converts the string representation of a <see cref="input"/> Unix /// time value to a <see cref="DateTime"/> value. /// </summary> /// <param name="input"> /// The object to convert. /// </param> /// <returns> /// Result of the conversion. /// </returns> /// <exception cref="InvalidDataException"> /// The <see cref="input"/> does not represent a <see cref="DateTime"/> /// value. /// </exception> public override DateTime Convert(object input) { var x = input as DateTime?; if (x != null) { return(x.Value); } Int64 value; if (Int64.TryParse(input.ToString(), result: out value)) { var dateTime = UnixEpoch.AddSeconds(value).ToLocalTime(); return(dateTime); } throw new InvalidDataException(string.Format("Expected {0}: {1}", TypeName, input)); // TODO: improved diagnostices }
public UserData ToUserData() { UserData data = new UserData(Id) { Surname = Surname, Name = Name, Login = Login, PasswordHash = PasswordHash, LastLogin = UnixEpoch.Add(TimeSpan.FromSeconds(LastLogin)), Notifications = new List <ReminderData>(), Email = Email }; foreach (var notification in Notifications) { data.Notifications.Add(notification.ToReminderData()); } return(data); }
public static DataTable ReadSalesJournal(PointOfSale in_pointOfSale, DateTime in_dateBegin, DateTime in_dateEnd, ShowRows in_displayMode) { using SQLiteConnection conn = ConnectionRegistry.Instance.OpenNewConnection(); using SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.Parameters.Add(new SQLiteParameter("@in_pointOfSaleId", in_pointOfSale.Id)); cmd.Parameters.Add(new SQLiteParameter("@in_dateBegin", UnixEpoch.FromDateTime(in_dateBegin))); cmd.Parameters.Add(new SQLiteParameter("@in_dateEndNext", UnixEpoch.FromDateTime(in_dateEnd.AddDays(1)))); string wherePayedByCard = string.Empty; if (in_displayMode == ShowRows.OnlyCash || in_displayMode == ShowRows.OnlyCard) { cmd.Parameters.Add(new SQLiteParameter("@in_payedByCard", in_displayMode == ShowRows.OnlyCash ? 0 : 1)); wherePayedByCard = " and s.payment_by_card = @in_payedByCard"; } cmd.CommandText = "select" + " s.id," + " date(s.time_sold, 'unixepoch', 'localtime') as time_sold," + " s.art_name," + " s.art_price_of_purchase," + " s.art_price_of_sell," + " s.unit_price," + " s.unit_count," + " (s.unit_price * s.unit_count) as price_sum," + " s.cell_x," + " s.cell_y" + " from doc_sale s" + " join doc d on d.id = s.id and d.time_cancelled is null" + " where s.point_of_sale_id = @in_pointOfSaleId" + " and @in_dateBegin <= s.time_sold and s.time_sold < @in_dateEndNext" + wherePayedByCard + " order by s.time_sold desc;"; DataTable table = new DataTable(); using (SQLiteDataAdapter a = new SQLiteDataAdapter(cmd)) a.Fill(table); return(table); }
/// <summary> /// Converts the string representation of a <paramref name="input"/> Unix /// time value to a <see cref="DateTime"/> value. /// </summary> /// <param name="input"> /// The object to convert. /// </param> /// <returns> /// Result of the conversion. /// </returns> /// <exception cref="InvalidDataException"> /// The <paramref name="input"/> does not represent a <see cref="DateTime"/> /// value. /// </exception> public override DateTime Convert(object input) { var x = input as DateTime?; if (x != null) { return(x.Value); } Double value; if (Double.TryParse(input.ToString(), result: out value)) { var dateTime = UnixEpoch.AddSeconds(value).ToLocalTime(); return(dateTime); } throw NewInvalidDataException(input); }
public static Summary GetSummary(PointOfSale in_pointOfSale, DateTime in_dateBegin, DateTime in_dateEnd, ShowRows in_displayMode) { using SQLiteConnection conn = ConnectionRegistry.Instance.OpenNewConnection(); using SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.Parameters.Add(new SQLiteParameter("@in_pointOfSaleId", in_pointOfSale.Id)); cmd.Parameters.Add(new SQLiteParameter("@in_dateBegin", UnixEpoch.FromDateTime(in_dateBegin))); cmd.Parameters.Add(new SQLiteParameter("@in_dateEndNext", UnixEpoch.FromDateTime(in_dateEnd.AddDays(1)))); string wherePayedByCard = string.Empty; if (in_displayMode == ShowRows.OnlyCash || in_displayMode == ShowRows.OnlyCard) { cmd.Parameters.Add(new SQLiteParameter("@in_payedByCard", in_displayMode == ShowRows.OnlyCash ? 0 : 1)); wherePayedByCard = " and s.payment_by_card = @in_payedByCard"; } cmd.CommandText = "select" + " COUNT(s.id) as cnt," + " IFNULL(SUM(s.unit_price * s.unit_count), 0) as sm," + " IFNULL(SUM(s.unit_price * s.unit_count - s.art_price_of_purchase * s.unit_count), 0) as profit" + " from doc_sale s" + " join doc d on d.id = s.id and d.time_cancelled is null" + " where s.point_of_sale_id = @in_pointOfSaleId" + " and @in_dateBegin <= s.time_sold and s.time_sold < @in_dateEndNext" + wherePayedByCard; DataTable table = new DataTable(); using (SQLiteDataAdapter a = new SQLiteDataAdapter(cmd)) a.Fill(table); DataRow row = table.Rows[0]; return(new Summary() { Count = (int)(long)row["cnt"], Sum = (int)(long)row["sm"], Profit = (int)(long)row["profit"] }); }
public void DecodeToObject_Should_Throw_Exception_Before_NotBefore_Becomes_Valid() { var serializer = new JsonNetSerializer(); var dateTimeProvider = new UtcDateTimeProvider(); var validator = new JwtValidator(serializer, dateTimeProvider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder, TestData.HMACSHA256Algorithm); var now = dateTimeProvider.GetNow(); var nbf = UnixEpoch.GetSecondsSince(now.AddHours(1)); var encoder = new JwtEncoder(TestData.HMACSHA256Algorithm, serializer, urlEncoder); var token = encoder.Encode(new { nbf }, TestData.Secret); Action decodeNotActiveJwt = () => decoder.DecodeToObject <Customer>(token, TestData.Secret, verify: true); decodeNotActiveJwt.Should() .Throw <SignatureVerificationException>(); }
public void Version2EncoderTest() { // Arrange var seed = new byte[32]; // signingKey RandomNumberGenerator.Create().GetBytes(seed); var sk = Ed25519.ExpandedPrivateKeyFromSeed(seed); //var secret = Convert.ToBase64String(sk); //BitConverter.ToString(sk).Replace("-", string.Empty); // Hex Encoded // Act var encoder = new PasetoEncoder(cfg => cfg.Use <Version2>(sk)); // defaul is public purpose var token = encoder.Encode(new PasetoPayload { { "example", HelloPaseto }, { "exp", UnixEpoch.ToUnixTimeString(DateTime.UtcNow.AddHours(24)) } }); // Assert Assert.IsNotNull(token); }
public string EncodeLogin(int ID) { IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var secondsExp = UnixEpoch.GetSecondsSince(now) + 432000; var payload = new Dictionary <string, object> { { "ID", ID }, { "exp", secondsExp } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); return(token); }
public void Decode_To_Encode_Expired() { var use = new User() { Name = "123" }; var serialize = new JsonNetSerializer(); var dateTimeProvider = new UtcDateTimeProvider(); var validTor = new JwtValidator(serialize, dateTimeProvider); var urlEncoder = new Base64UrlEncoder(); var endocer = new JwtEncoder(new HMACSHA256Algorithm(), serialize, urlEncoder); var decoder = new JwtDecoder(serialize, validTor, urlEncoder, new HMACSHAAlgorithmFactory()); var now = dateTimeProvider.GetNow(); var exp = UnixEpoch.GetSecondsSince(now.AddHours(-1)); var token = endocer.Encode(new { exp }, "wss"); var actual = decoder.Decode(token, "wss", true); var name = nameof(User.Name); Assert.NotEmpty(name); }
private static readonly int _expire = 60 * 60 * 60 * 600; // seconds public static string GenerateToken(Employee employee, int expire) { try { var keySec = _secret; if (string.IsNullOrWhiteSpace(AppGlobal.NexusConfig.Secret)) { keySec = AppGlobal.NexusConfig.Secret; } if (expire <= 0) { expire = _expire; } var provider = new UtcDateTimeProvider(); var createTime = provider.GetNow(); var expiredTime = provider.GetNow().AddSeconds(expire); var secondsSinceEpoch = UnixEpoch.GetSecondsSince(expiredTime); var payload = new Dictionary <string, object> { { "Employee", employee }, { "exp", secondsSinceEpoch } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric JWT.IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, keySec); return(token); } catch (Exception ex) { Logger.Write(ex.ToString(), true); } return(null); }
public void DecodeToObject_Should_Decode_Token_After_NotBefore_Becomes_Valid() { var dateTimeProvider = new UtcDateTimeProvider(); const string key = TestData.Secret; var serializer = new JsonNetSerializer(); var validator = new JwtValidator(serializer, new UtcDateTimeProvider()); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder, TestData.HMACSHA256Algorithm); var now = dateTimeProvider.GetNow(); var nbf = UnixEpoch.GetSecondsSince(now); var encoder = new JwtEncoder(TestData.HMACSHA256Algorithm, serializer, urlEncoder); var token = encoder.Encode(new { nbf }, key); var dic = decoder.DecodeToObject <Dictionary <string, object> >(token, key, verify: true); dic.Should() .Contain("nbf", nbf); }
public static CellInStock Restore(string in_x, string in_y, SkuInStock in_skuInStock) { using SQLiteConnection conn = ConnectionRegistry.Instance.OpenNewConnection(); using SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "select *" + " from cell_in_stock" + " where point_of_sale_id = @in_pointOfSaleId" + " and article_id = @in_articleId" + " and x = @in_x" + " and y = @in_y"; cmd.Parameters.Add(new SQLiteParameter("@in_pointOfSaleId", in_skuInStock.PointOfSale.Id)); cmd.Parameters.Add(new SQLiteParameter("@in_articleId", in_skuInStock.Article.Id)); cmd.Parameters.Add(new SQLiteParameter("@in_x", in_x)); cmd.Parameters.Add(new SQLiteParameter("@in_y", in_y)); DataTable table = new DataTable(); using (SQLiteDataAdapter a = new SQLiteDataAdapter(cmd)) a.Fill(table); if (table.Rows.Count == 0) { return(null); } else if (table.Rows.Count == 1) { DataRow row = table.Rows[0]; return(CellInStock.Restore((int)(long)row["id"], UnixEpoch.ToDateTime((long)row["modified"]), in_skuInStock, in_x, in_y, (int)(long)row["amount"])); } else { throw new ApplicationException("CellInStock.Restore(string in_x, string in_y, SkuInStock in_skuInStock) returned more than 1 row."); } }
public void DecodeToObject_Should_Throw_Exception_On_Expired_Claim() { const string key = TestData.Secret; const int timeDelta = -1; var dateTimeProvider = new UtcDateTimeProvider(); var serializer = new JsonNetSerializer(); var validator = new JwtValidator(serializer, dateTimeProvider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder, TestData.HMACSHA256Algorithm); var now = dateTimeProvider.GetNow(); var exp = UnixEpoch.GetSecondsSince(now.AddHours(timeDelta)); var encoder = new JwtEncoder(TestData.HMACSHA256Algorithm, serializer, urlEncoder); var token = encoder.Encode(new { exp }, key); Action action = () => decoder.DecodeToObject <Customer>(token, key, verify: true); action.Should() .Throw <TokenExpiredException>("because decoding an expired token should raise an exception when verified"); }
/// <summary> /// Converts a UNIX time value to a <see cref="DateTime"/> value /// </summary> public static DateTime FromUnixTime(uint unixTime) { return(UnixEpoch.AddSeconds(unixTime)); }
public static DateTime FromUnixTime(this long timestamp) { return(UnixEpoch.AddSeconds(timestamp)); }
public static DateTime FromUnixTime(this long self) { return(UnixEpoch.AddSeconds(self).ToLocalTime()); }
public DateTime ToUtcTime() { return(UnixEpoch.AddTicks((SecToNSec(Tv_sec) + Tv_nsec) / 100)); }
public override String ConvertFromNumber(Double value) { var dt = UnixEpoch.AddMilliseconds(value); return(ConvertFromDate(dt)); }
public static JwtBuilder ExpirationTime(this JwtBuilder builder, DateTime time) => builder.AddClaim(ClaimName.ExpirationTime, UnixEpoch.GetSecondsSinceAsString(time));
public static JwtBuilder IssuedAt(this JwtBuilder builder, DateTime time) => builder.AddClaim(ClaimName.IssuedAt, UnixEpoch.GetSecondsSinceAsString(time));
public static JwtBuilder NotBefore(this JwtBuilder builder, DateTime time) => builder.AddClaim(ClaimName.NotBefore, UnixEpoch.GetSecondsSinceAsString(time));
public override String ConvertFromNumber(Double value) { var dt = UnixEpoch.AddMonths((Int32)value); return(ConvertFromDate(dt)); }
/// <summary> /// 지정된 밀리초 수를 더한 새로운 (UTC) System.DateTime을 반환합니다. /// </summary> /// <param name="milliSeconds"></param> /// <returns></returns> public static DateTime ConvertToUtcTimeMilli(Int64 milliSeconds) { return(UnixEpoch.AddMilliseconds(milliSeconds).ToUniversalTime()); }