E-commerce Marketing Strategies to Drive Sales During the Holiday Season

The holiday season is a prime opportunity to implement Holiday E-commerce Marketing Strategies that drive sales and engage customers. To stand out, your e-commerce strategy should be well-thought-out and impactful. Here are some tried-and-true marketing tactics to boost your holiday sales and enhance customer engagement.

1. Optimize Your Website for Mobile

With more people shopping on their phones, having a mobile-optimized website is crucial for holiday success. A mobile-friendly site ensures smooth navigation, fast loading speeds, and an easy checkout experience across devices.

  • Pro Tip: Google’s Mobile-Friendly Test can help you assess your site’s mobile readiness.
  • Fast-loading mobile pages reduce bounce rates and increase conversions.

2. Create Holiday-Themed Landing Pages

Holiday-specific landing pages capture shoppers looking for festive deals and gift ideas. These pages can drive traffic and improve SEO if optimized for popular holiday keywords like “Black Friday deals,” “Cyber Monday sales,” or “Christmas gifts.”

  • Include holiday visuals and compelling calls-to-action.
  • Use relevant keywords to rank higher in search engine results.

3. Leverage Email Marketing with Personalized Offers

Email marketing remains one of the most effective channels for holiday campaigns. Target customers based on their preferences or purchase history, and consider sending exclusive offers for early access to holiday sales.

  • Personalized subject lines can boost open rates: “Your Holiday Discount Inside” or “Exclusive Deals Just for You.”
  • Schedule regular emails, like weekly countdowns or last-minute offers.

4. Implement a Sense of Urgency

Using urgency is an excellent way to motivate customers to act quickly, especially when holiday shopping windows are short. Countdowns and limited-stock notifications can drive sales faster.

  • Run flash sales and highlight limited-time discounts.
  • Include countdown timers on product pages or in emails to convey urgency.

5. Run Targeted Social Media Campaigns

Social media is an ideal platform for holiday marketing. Run ads featuring seasonal content, gift ideas, or promotions and use targeted advertising to reach your ideal holiday shopper.

  • Use shoppable posts on Instagram and Facebook for direct purchases.
  • Include holiday hashtags (#HolidayDeals, #GiftIdeas) to broaden your reach.

6. Offer Gift Bundles and Discounts

Gift bundles provide shoppers with ready-made options for multiple people or larger gifts. These not only offer added value but can also increase your average order value.

  • Group complementary items and create special gift sets.
  • Market bundles with titles like “Perfect Gift Sets for Families” to capture interest.

7. Collaborate with Influencers

Holiday shopping guides created by influencers can be a great way to authentically showcase your products. Collaborate with influencers whose followers align with your target audience for more organic reach.

  • Look for influencers who have credibility in your industry.
  • Negotiate content like gift guide posts or unboxing videos.

8. Enhance Customer Support

High-quality customer service during the holidays can set you apart from competitors. Add a live chat feature to answer questions in real-time and extend your support hours if possible.

  • Address common inquiries about shipping, returns, and order status.
  • Consider offering live chat for an improved customer experience.

9. Offer Flexible Shipping and Returns

Shoppers prefer convenient and reliable shipping and return options during the holidays. Offering free shipping, faster delivery, or extended return policies can encourage more purchases.

  • Display shipping deadlines prominently on your website.
  • Offer incentives like “Free Shipping on Orders Over $50.”

10. Create a Remarketing Strategy

During the holiday season, shoppers often browse before they buy, making remarketing critical. Re-target visitors with tailored ads that remind them of products they viewed or abandoned in their carts.

  • Use remarketing to show discounts on items left in carts.
  • Offer special incentives like 10% off to encourage conversions.

11. Encourage User-Generated Content (UGC)

UGC is an effective tool for building trust and social proof. Encourage past customers to post pictures or reviews with a branded hashtag and showcase it on your social media or website.

  • Run a holiday contest to increase UGC participation.
  • Repost customer content as social proof for potential buyers.

12. Prepare Your Website for High Traffic

Holiday traffic surges can cause slow loading or even crashes if your website isn’t prepared. Optimize your site by compressing images, upgrading hosting if necessary, and stress-testing for speed.

  • Test Your Site Speed to ensure fast loading.
  • Prioritize optimizing your website’s checkout process for peak traffic times.

Final Thoughts

The holiday season offers a valuable chance to capture a large customer base. With these strategies—from creating holiday-specific landing pages and targeted social media campaigns to implementing urgency and flexible shipping options—you can optimize your e-commerce store for holiday success. By prioritizing these approaches, you’ll attract holiday shoppers and increase your sales, setting up your business for a prosperous season.

18 Comments

  1. Tarun Sharma

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web;
    using System.Web.Http.Controllers;
    using System.Web.Http.Filters;
    using System.Web.Http.Results;
    using SMSG.Business.EWaste.Contract.User;
    using SMSG.Common.Aspects;
    using SMSG.Common.Aspects.Enums;
    using SMSG.Common.Aspects.Utils;
    using SMSG.Common.Ioc;
    using SMSG.ServiceApp.EWaste.Security;

    namespace SMSG.ServiceApp.EWaste
    {
    public class AuthoriseAttribute : AuthorizationFilterAttribute
    {
    public IUserMasterManager UserMasterManager
    {
    get
    {
    IocManager IocEngine = new IocManager(DiscoveryStrategy.SearchBaseDirectory);
    return IocEngine.Resolve();
    }
    }
    private string RemoveUnwantedCharacters(string inputText)
    {
    return inputText.Replace(“\””, “”);
    }
    public override void OnAuthorization(HttpActionContext actionContext)
    {
    try
    {
    string apiKeyHeader = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APIKeyHeader))))[0].ToString();
    string apiTokenHeader = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APITokenHeader))))[0].ToString();
    string loginSession = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.LoginSession))))[0].ToString();
    string userID = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.UserID))))[0].ToString();
    if (!String.IsNullOrEmpty(apiKeyHeader) && !String.IsNullOrEmpty(apiTokenHeader))
    {
    bool isValid = false;
    isValid = TokenHandler.IsLoginSessionExists(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), userID);
    if (!isValid)
    {
    var userLoginSessionData = UserMasterManager.IsValidServiceUser(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader),Convert.ToInt32(userID));
    if (userLoginSessionData != null && userLoginSessionData.LogoutTime >= DateTime.Now)
    {
    TokenHandler.AddOrUpdate(userLoginSessionData);
    isValid = true;
    }
    }
    if (!isValid)
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
    Content = new StringContent(“Session Expired”),
    };
    }
    }
    }
    catch (Exception ex)
    {
    actionContext.Response =
    new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
    Content = new StringContent(“Missing Authorization-Token”)
    };
    return;
    }
    }

    }
    }

  2. Tarun

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Controllers;
    using System.Web.Http.Filters;
    using SMSG.Business.EWaste.Contract.User;
    using SMSG.Common.Aspects;
    using SMSG.Common.Aspects.Enums;
    using SMSG.Common.Aspects.Utils;
    using SMSG.Common.Ioc;
    using SMSG.ServiceApp.EWaste.Security;

    namespace SMSG.ServiceApp.EWaste
    {
    public class AuthoriseAttribute : AuthorizationFilterAttribute
    {
    public IUserMasterManager UserMasterManager
    {
    get
    {
    IocManager IocEngine = new IocManager(DiscoveryStrategy.SearchBaseDirectory);
    return IocEngine.Resolve();
    }
    }

    public List AllowedRoles { get; set; } = new List();

    private string RemoveUnwantedCharacters(string inputText)
    {
    return inputText.Replace(“\””, “”);
    }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
    try
    {
    string apiKeyHeader = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APIKeyHeader))))[0];
    string apiTokenHeader = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APITokenHeader))))[0];
    string loginSession = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.LoginSession))))[0];
    string userID = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.UserID))))[0];

    if (!String.IsNullOrEmpty(apiKeyHeader) && !String.IsNullOrEmpty(apiTokenHeader))
    {
    bool isValid = TokenHandler.IsLoginSessionExists(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), userID);

    if (!isValid)
    {
    var userLoginSessionData = UserMasterManager.IsValidServiceUser(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), Convert.ToInt32(userID));
    if (userLoginSessionData != null && userLoginSessionData.LogoutTime >= DateTime.Now)
    {
    TokenHandler.AddOrUpdate(userLoginSessionData);
    isValid = true;
    }
    }

    if (isValid)
    {
    // Role-based authorization
    var userRoles = UserMasterManager.GetUserRoles(userID); // Assume this method returns a list of roles for the user

    if (!userRoles.Any(role => AllowedRoles.Contains(role)))
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
    {
    Content = new StringContent(“User does not have the required role”)
    };
    return;
    }
    }
    else
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
    Content = new StringContent(“Session Expired”)
    };
    return;
    }
    }
    }
    catch (Exception ex)
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
    Content = new StringContent(“Missing Authorization-Token”)
    };
    return;
    }
    }
    }
    }

  3. Tarun Sharma

    public override void OnAuthorization(HttpActionContext actionContext)
    {
    try
    {
    string apiKeyHeader = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APIKeyHeader))))[0];
    string apiTokenHeader = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APITokenHeader))))[0];
    string loginSession = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.LoginSession))))[0];
    string userID = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.UserID))))[0];

    if (!String.IsNullOrEmpty(apiKeyHeader) && !String.IsNullOrEmpty(apiTokenHeader))
    {
    bool isValid = TokenHandler.IsLoginSessionExists(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), userID);

    if (!isValid)
    {
    var userLoginSessionData = UserMasterManager.IsValidServiceUser(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), Convert.ToInt32(userID));
    if (userLoginSessionData != null && userLoginSessionData.LogoutTime >= DateTime.Now)
    {
    TokenHandler.AddOrUpdate(userLoginSessionData);
    isValid = true;
    }
    }

    if (isValid)
    {

    var requiredRoles = GetRequiredRoles(actionContext);

    string userId = ((string[])(actionContext.Request.Headers.GetValues(“UserID”)))[0];

    // Role-based authorization
    var userRoles = UserMasterManager.GetUserRoles(userID); // this method returns a list of roles for the user

    if (!userRoles.Any(role => AllowedRoles.Contains(role)))
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
    {
    Content = new StringContent(“User does not have the required role”)
    };
    return;
    }
    }
    else
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
    Content = new StringContent(“Session Expired”),
    };
    return;
    }
    }
    }
    catch (Exception ex)
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
    Content = new StringContent(“Missing Authorization-Token”)
    };
    return;
    }
    }

  4. Jazz Tarun Sharma

    public override void OnAuthorization(HttpActionContext actionContext)
    {
    try
    {
    string apiKeyHeader = null, apiTokenHeader = null, loginSession = null, userID = null;

    // Step 1: Retrieve headers with error handling
    try
    {
    apiKeyHeader = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APIKeyHeader))?.FirstOrDefault();
    apiTokenHeader = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APITokenHeader))?.FirstOrDefault();
    loginSession = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.LoginSession))?.FirstOrDefault();
    userID = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.UserID))?.FirstOrDefault();
    }
    catch (Exception ex)
    {
    Console.WriteLine(“Error retrieving headers: ” + ex.Message);
    throw; // Re-throw to handle in main catch if necessary
    }

    if (string.IsNullOrEmpty(apiKeyHeader) || string.IsNullOrEmpty(apiTokenHeader))
    {
    throw new ArgumentException(“Required headers are missing”);
    }

    // Step 2: Validate the login session
    bool isValid = false;
    try
    {
    isValid = TokenHandler.IsLoginSessionExists(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), userID);

    if (!isValid)
    {
    var userLoginSessionData = UserMasterManager.IsValidServiceUser(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), Convert.ToInt32(userID));
    if (userLoginSessionData != null && userLoginSessionData.LogoutTime >= DateTime.Now)
    {
    TokenHandler.AddOrUpdate(userLoginSessionData);
    isValid = true;
    }
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(“Error validating session: ” + ex.Message);
    throw; // Re-throw for main catch if necessary
    }

    if (isValid)
    {
    // Step 3: Retrieve roles
    try
    {
    var requiredRoles = GetRequiredRoles(actionContext) ?? new string[0];
    var userRoles = UserMasterManager.GetUserRoles(userID) ?? new List();

    // Step 4: Check roles
    if (!userRoles.Any(role => requiredRoles.Contains(role)))
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
    {
    Content = new StringContent(“User does not have the required role”)
    };
    return;
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(“Error in role validation: ” + ex.Message);
    throw;
    }
    }
    else
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
    Content = new StringContent(“Session Expired”)
    };
    return;
    }
    }
    catch (Exception ex)
    {
    // Log the exception message for troubleshooting
    Console.WriteLine(“Unhandled exception in OnAuthorization: ” + ex.Message);

    actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
    Content = new StringContent(“Missing Authorization-Token”)
    };
    return;
    }
    }

  5. Jazz Tarun Sharma

    public override void OnAuthorization(HttpActionContext actionContext)
    {
    try
    {
    // Step 1: Retrieve headers
    string apiKeyHeader = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APIKeyHeader))?.FirstOrDefault();
    string apiTokenHeader = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APITokenHeader))?.FirstOrDefault();
    string loginSession = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.LoginSession))?.FirstOrDefault();
    string userID = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.UserID))?.FirstOrDefault();

    if (string.IsNullOrEmpty(apiKeyHeader) || string.IsNullOrEmpty(apiTokenHeader))
    {
    throw new ArgumentException(“Required headers are missing”);
    }

    // Step 2: Validate session
    bool isValid = TokenHandler.IsLoginSessionExists(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), userID);

    if (!isValid)
    {
    var userLoginSessionData = UserMasterManager.IsValidServiceUser(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), Convert.ToInt32(userID));
    if (userLoginSessionData != null && userLoginSessionData.LogoutTime >= DateTime.Now)
    {
    TokenHandler.AddOrUpdate(userLoginSessionData);
    isValid = true;
    }
    }

    if (isValid)
    {
    // Step 3: Get allowed roles from the Authorize attribute on the action or controller
    var requiredRoles = GetRolesFromAuthorizeAttribute(actionContext);
    var userRoles = UserMasterManager.GetUserRoles(userID) ?? new List();

    // Step 4: Check if user has any of the required roles
    if (requiredRoles.Any() && !userRoles.Any(role => requiredRoles.Contains(role)))
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
    {
    Content = new StringContent(“User does not have the required role”)
    };
    return;
    }
    }
    else
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
    Content = new StringContent(“Session Expired”)
    };
    return;
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(“Unhandled exception in OnAuthorization: ” + ex.Message);

    actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
    Content = new StringContent(“Missing Authorization-Token”)
    };
    }
    }

    // Helper method to get roles from the Authorize attribute
    private List GetRolesFromAuthorizeAttribute(HttpActionContext actionContext)
    {
    var roles = new List();

    // Check for Authorize attributes on the action
    var actionRoles = actionContext.ActionDescriptor
    .GetCustomAttributes(true)
    .SelectMany(attr => attr.Roles.Split(‘,’))
    .Select(role => role.Trim())
    .ToList();

    roles.AddRange(actionRoles);

    // If no roles are found on the action, check on the controller
    if (!roles.Any())
    {
    var controllerRoles = actionContext.ControllerContext.ControllerDescriptor
    .GetCustomAttributes(true)
    .SelectMany(attr => attr.Roles.Split(‘,’))
    .Select(role => role.Trim())
    .ToList();

    roles.AddRange(controllerRoles);
    }

    return roles;
    }

  6. Tarun Sharma

    public override void OnAuthorization(HttpActionContext actionContext)
    {
    try
    {
    string apiKeyHeader = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APIKeyHeader))))[0];
    string apiTokenHeader = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APITokenHeader))))[0];
    string loginSession = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.LoginSession))))[0];
    string userID = ((string[])(actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.UserID))))[0];

    if (String.IsNullOrEmpty(apiKeyHeader) || String.IsNullOrEmpty(apiTokenHeader))
    {
    throw new ArgumentException(“Missing required headers”);
    }
    bool isValid = false;

    isValid = TokenHandler.IsLoginSessionExists(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), userID);

    if (!isValid)
    {
    var userLoginSessionData = UserMasterManager.IsValidServiceUser(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), Convert.ToInt32(userID));
    if (userLoginSessionData != null && userLoginSessionData.LogoutTime >= DateTime.Now)
    {
    TokenHandler.AddOrUpdate(userLoginSessionData);
    isValid = true;
    }
    }

    if (isValid)
    {

    var requiredRoles = GetRequiredRoles(actionContext);

    string userId = ((string[])(actionContext.Request.Headers.GetValues(“UserID”)))[0];

    // Role-based authorization
    var userRoles = UserMasterManager.GetUserRoles(userID); // this method returns a list of roles for the user

    if (!userRoles.Any(role => AllowedRoles.Contains(role)))
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
    {
    Content = new StringContent(“User does not have the required role”)
    };
    return;
    }

    }
    else
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
    Content = new StringContent(“Session Expired”),
    };
    return;
    }
    }
    catch (Exception ex)
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
    Content = new StringContent(“Missing Authorization-Token”)
    };
    return;
    }
    }

    private string[] GetRequiredRoles(HttpActionContext actionContext)
    {
    var actionAttributes = actionContext.ActionDescriptor.GetCustomAttributes();
    if (actionAttributes.Any())
    {
    return actionAttributes.First().AllowedRoles;

    }

    var controllerAttributes = actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes();
    if (controllerAttributes.Any())
    {
    return controllerAttributes.First().AllowedRoles;
    }

    return new string[] { };
    }

    }

  7. Jazz Tarun Sharma

    public override void OnAuthorization(HttpActionContext actionContext)
    {
    try
    {
    string apiKeyHeader = null, apiTokenHeader = null, loginSession = null, userID = null;

    // Step 1: Retrieve headers with error handling
    try
    {
    apiKeyHeader = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APIKeyHeader))?.FirstOrDefault();
    apiTokenHeader = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.APITokenHeader))?.FirstOrDefault();
    loginSession = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.LoginSession))?.FirstOrDefault();
    userID = actionContext.Request.Headers.GetValues(AppUtil.GetAppSettings(ConfigKeys.UserID))?.FirstOrDefault();

    // Validate retrieved headers
    if (string.IsNullOrEmpty(apiKeyHeader) || string.IsNullOrEmpty(apiTokenHeader))
    {
    throw new ArgumentException(“Missing required headers”);
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(“Error retrieving headers: ” + ex.Message);
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
    Content = new StringContent(“Missing or invalid headers”)
    };
    return;
    }

    // Step 2: Validate the login session
    bool isValid = false;
    try
    {
    isValid = TokenHandler.IsLoginSessionExists(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), userID);

    if (!isValid)
    {
    var userLoginSessionData = UserMasterManager.IsValidServiceUser(RemoveUnwantedCharacters(loginSession), RemoveUnwantedCharacters(apiTokenHeader), Convert.ToInt32(userID));
    if (userLoginSessionData != null && userLoginSessionData.LogoutTime >= DateTime.Now)
    {
    TokenHandler.AddOrUpdate(userLoginSessionData);
    isValid = true;
    }
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(“Error validating session: ” + ex.Message);
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
    Content = new StringContent(“Session validation failed”)
    };
    return;
    }

    if (isValid)
    {
    // Step 3: Retrieve roles
    string[] requiredRoles;
    List userRoles;

    try
    {
    requiredRoles = GetRequiredRoles(actionContext);
    userRoles = UserMasterManager.GetUserRoles(userID);

    // Ensure roles are not null
    requiredRoles = requiredRoles ?? new string[0];
    userRoles = userRoles ?? new List();
    }
    catch (Exception ex)
    {
    Console.WriteLine(“Error retrieving roles: ” + ex.Message);
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
    {
    Content = new StringContent(“Role validation failed”)
    };
    return;
    }

    // Step 4: Check if the user has any of the required roles
    if (!userRoles.Any(role => requiredRoles.Contains(role)))
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
    {
    Content = new StringContent(“User does not have the required role”)
    };
    return;
    }
    }
    else
    {
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
    Content = new StringContent(“Session Expired”)
    };
    return;
    }
    }
    catch (Exception ex)
    {
    // Log the exception message for troubleshooting
    Console.WriteLine(“Unhandled exception in OnAuthorization: ” + ex.Message);

    actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
    Content = new StringContent(“Authorization failed due to an unexpected error”)
    };
    }
    }

    private string[] GetRequiredRoles(HttpActionContext actionContext)
    {
    var actionAttributes = actionContext.ActionDescriptor.GetCustomAttributes().ToList();
    if (actionAttributes.Any())
    {
    return actionAttributes.First().AllowedRoles;
    }

    var controllerAttributes = actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes().ToList();
    if (controllerAttributes.Any())
    {
    return controllerAttributes.First().AllowedRoles;
    }

    return new string[] { };
    }

  8. Jazz Tarun Sharma

    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    public class AesEncryption
    {
    // Encrypt a string using AES-256
    public static string Encrypt(string plainText, byte[] key, byte[] iv)
    {
    if (key == null || key.Length != 32)
    throw new ArgumentException(“Key must be 256 bits (32 bytes) long.”);
    if (iv == null || iv.Length != 16)
    throw new ArgumentException(“IV must be 128 bits (16 bytes) long.”);

    using (Aes aes = Aes.Create())
    {
    aes.Key = key;
    aes.IV = iv;
    aes.Mode = CipherMode.CBC;
    aes.Padding = PaddingMode.PKCS7;

    using (MemoryStream memoryStream = new MemoryStream())
    {
    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
    {
    using (StreamWriter writer = new StreamWriter(cryptoStream))
    {
    writer.Write(plainText);
    }
    }
    return Convert.ToBase64String(memoryStream.ToArray());
    }
    }
    }

    // Decrypt a string using AES-256
    public static string Decrypt(string cipherText, byte[] key, byte[] iv)
    {
    if (key == null || key.Length != 32)
    throw new ArgumentException(“Key must be 256 bits (32 bytes) long.”);
    if (iv == null || iv.Length != 16)
    throw new ArgumentException(“IV must be 128 bits (16 bytes) long.”);

    using (Aes aes = Aes.Create())
    {
    aes.Key = key;
    aes.IV = iv;
    aes.Mode = CipherMode.CBC;
    aes.Padding = PaddingMode.PKCS7;

    using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(cipherText)))
    {
    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
    {
    using (StreamReader reader = new StreamReader(cryptoStream))
    {
    return reader.ReadToEnd();
    }
    }
    }
    }
    }

    // Helper function to generate a random 256-bit key
    public static byte[] GenerateRandomKey()
    {
    using (Aes aes = Aes.Create())
    {
    aes.KeySize = 256;
    aes.GenerateKey();
    return aes.Key;
    }
    }

    // Helper function to generate a random 128-bit IV
    public static byte[] GenerateRandomIV()
    {
    using (Aes aes = Aes.Create())
    {
    aes.GenerateIV();
    return aes.IV;
    }
    }
    }

  9. Jazz Tarun Sharma

    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    public class HybridEncryption
    {
    // Encrypt data with AES, and AES key with RSA (public key)
    public static (string EncryptedData, string EncryptedAesKey, string Iv) Encrypt(string data, RSAParameters rsaPublicKey)
    {
    // Generate AES key and IV
    using (Aes aes = Aes.Create())
    {
    aes.KeySize = 256;
    aes.GenerateKey();
    aes.GenerateIV();

    // Encrypt the data using AES
    using (MemoryStream memoryStream = new MemoryStream())
    {
    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
    {
    using (StreamWriter writer = new StreamWriter(cryptoStream))
    {
    writer.Write(data);
    }
    }
    string encryptedData = Convert.ToBase64String(memoryStream.ToArray());

    // Encrypt the AES key using RSA
    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
    rsa.ImportParameters(rsaPublicKey);
    byte[] encryptedAesKey = rsa.Encrypt(aes.Key, false);

    return (encryptedData, Convert.ToBase64String(encryptedAesKey), Convert.ToBase64String(aes.IV));
    }
    }
    }
    }

    // Decrypt data with RSA (private key) to retrieve AES key, then decrypt data with AES
    public static string Decrypt(string encryptedData, string encryptedAesKey, string iv, RSAParameters rsaPrivateKey)
    {
    byte[] aesKey;
    byte[] aesIv = Convert.FromBase64String(iv);

    // Decrypt AES key using RSA private key
    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
    rsa.ImportParameters(rsaPrivateKey);
    aesKey = rsa.Decrypt(Convert.FromBase64String(encryptedAesKey), false);
    }

    // Decrypt the data using AES
    using (Aes aes = Aes.Create())
    {
    aes.Key = aesKey;
    aes.IV = aesIv;

    using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(encryptedData)))
    {
    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
    {
    using (StreamReader reader = new StreamReader(cryptoStream))
    {
    return reader.ReadToEnd();
    }
    }
    }
    }
    }

    // Generate RSA public and private keys
    public static RSAParameters GenerateRSAKeys(out RSAParameters privateKey)
    {
    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
    {
    privateKey = rsa.ExportParameters(true);
    return rsa.ExportParameters(false);
    }
    }
    }

  10. Jazz Tarun Sharma

    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    class AES256Encryption
    {
    // Encrypt the password using AES with a 256-bit key
    public static string EncryptPassword(string password, string key)
    {
    using (Aes aesAlg = Aes.Create())
    {
    aesAlg.Key = Encoding.UTF8.GetBytes(key); // Key must be 32 bytes for AES-256
    aesAlg.GenerateIV(); // Generate a new IV (Initialization Vector) for each encryption
    byte[] iv = aesAlg.IV;

    // Encrypt the data
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, iv);
    using (MemoryStream msEncrypt = new MemoryStream())
    {
    msEncrypt.Write(iv, 0, iv.Length); // Store IV at the beginning
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
    {
    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
    {
    swEncrypt.Write(password); // Write the password to be encrypted
    }
    }
    return Convert.ToBase64String(msEncrypt.ToArray());
    }
    }
    }

    // Decrypt the password using AES with a 256-bit key
    public static string DecryptPassword(string encryptedPassword, string key)
    {
    using (Aes aesAlg = Aes.Create())
    {
    aesAlg.Key = Encoding.UTF8.GetBytes(key); // Key must be 32 bytes for AES-256
    byte[] cipherBytes = Convert.FromBase64String(encryptedPassword);

    // Extract the IV (first 16 bytes)
    byte[] iv = new byte[16];
    Array.Copy(cipherBytes, 0, iv, 0, iv.Length);

    // Decrypt the data
    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, iv);
    using (MemoryStream msDecrypt = new MemoryStream(cipherBytes, iv.Length, cipherBytes.Length – iv.Length))
    {
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
    {
    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
    {
    return srDecrypt.ReadToEnd(); // Read the decrypted password
    }
    }
    }
    }
    }

    static void Main()
    {
    // Define a 256-bit key (32 bytes, 256 bits)
    string key = “12345678901234567890123456789012”; // 32 bytes key for AES-256

    // Example password to encrypt
    string password = “SecurePassword123!”;

    // Encrypt the password
    string encryptedPassword = EncryptPassword(password, key);
    Console.WriteLine(“Encrypted Password: ” + encryptedPassword);

    // Decrypt the password
    string decryptedPassword = DecryptPassword(encryptedPassword, key);
    Console.WriteLine(“Decrypted Password: ” + decryptedPassword);
    }
    }

  11. Jazz Tarun Sharma

    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    class AES256Encryption
    {
    // Encrypt the password using AES with a 256-bit key
    public static string EncryptPassword(string password, string key)
    {
    using (Aes aesAlg = Aes.Create())
    {
    aesAlg.Key = Encoding.UTF8.GetBytes(key); // Key must be 32 bytes for AES-256
    aesAlg.GenerateIV(); // Generate a new IV (Initialization Vector) for each encryption
    byte[] iv = aesAlg.IV;

    // Encrypt the data
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, iv);
    using (MemoryStream msEncrypt = new MemoryStream())
    {
    msEncrypt.Write(iv, 0, iv.Length); // Store IV at the beginning
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
    {
    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
    {
    swEncrypt.Write(password); // Write the password to be encrypted
    }
    }
    return Convert.ToBase64String(msEncrypt.ToArray());
    }
    }
    }

    // Decrypt the password using AES with a 256-bit key
    public static string DecryptPassword(string encryptedPassword, string key)
    {
    using (Aes aesAlg = Aes.Create())
    {
    aesAlg.Key = Encoding.UTF8.GetBytes(key); // Key must be 32 bytes for AES-256
    byte[] cipherBytes = Convert.FromBase64String(encryptedPassword);

    // Extract the IV (first 16 bytes)
    byte[] iv = new byte[16];
    Array.Copy(cipherBytes, 0, iv, 0, iv.Length);

    // Decrypt the data
    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, iv);
    using (MemoryStream msDecrypt = new MemoryStream(cipherBytes, iv.Length, cipherBytes.Length – iv.Length))
    {
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
    {
    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
    {
    return srDecrypt.ReadToEnd(); // Read the decrypted password
    }
    }
    }
    }
    }

    static void Main()
    {
    // Define a 256-bit key (32 bytes, 256 bits)
    string key = “12345678900987654321123456789000”; // 32 bytes key for AES-256

    // Test Case 1: Password = “Samsung@123”
    string password1 = “Samsung@123”;

    Console.WriteLine(“Test Case 1:”);
    string encryptedPassword1 = EncryptPassword(password1, key);
    Console.WriteLine(“Encrypted Password: ” + encryptedPassword1);

    string decryptedPassword1 = DecryptPassword(encryptedPassword1, key);
    Console.WriteLine(“Decrypted Password: ” + decryptedPassword1);

    Console.WriteLine(); // Line break

    // Test Case 2: Password = “SecurePass123”
    string password2 = “SecurePass123”;

    Console.WriteLine(“Test Case 2:”);
    string encryptedPassword2 = EncryptPassword(password2, key);
    Console.WriteLine(“Encrypted Password: ” + encryptedPassword2);

    string decryptedPassword2 = DecryptPassword(encryptedPassword2, key);
    Console.WriteLine(“Decrypted Password: ” + decryptedPassword2);

    Console.WriteLine(); // Line break

    // Test Case 3: Password = “Qwerty!@345”
    string password3 = “Qwerty!@345”;

    Console.WriteLine(“Test Case 3:”);
    string encryptedPassword3 = EncryptPassword(password3, key);
    Console.WriteLine(“Encrypted Password: ” + encryptedPassword3);

    string decryptedPassword3 = DecryptPassword(encryptedPassword3, key);
    Console.WriteLine(“Decrypted Password: ” + decryptedPassword3);
    }
    }

  12. Jazz Tarun Sharma

    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    class HybridEncryption
    {
    // Generate RSA Keys (public and private)
    public static (string publicKey, string privateKey) GenerateRSAKeys()
    {
    using (RSA rsa = RSA.Create(2048))
    {
    string publicKey = Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo());
    string privateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey());
    return (publicKey, privateKey);
    }
    }

    // Encrypt the password using AES and RSA hybrid encryption
    public static string EncryptPassword(string password, string rsaPublicKey)
    {
    // Step 1: Generate AES Key and IV
    using (Aes aes = Aes.Create())
    {
    aes.GenerateKey();
    aes.GenerateIV();

    // Step 2: Encrypt the password using AES
    ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
    using (MemoryStream msEncrypt = new MemoryStream())
    {
    // Store the AES IV and then the encrypted password
    msEncrypt.Write(aes.IV, 0, aes.IV.Length);
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
    {
    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
    {
    swEncrypt.Write(password);
    }
    }
    byte[] encryptedPassword = msEncrypt.ToArray();

    // Step 3: Encrypt the AES Key using RSA Public Key
    using (RSA rsa = RSA.Create())
    {
    rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(rsaPublicKey), out _);
    byte[] encryptedAesKey = rsa.Encrypt(aes.Key, RSAEncryptionPadding.OaepSHA256);

    // Combine encrypted AES Key and encrypted Password
    byte[] combined = new byte[encryptedAesKey.Length + encryptedPassword.Length];
    Array.Copy(encryptedAesKey, 0, combined, 0, encryptedAesKey.Length);
    Array.Copy(encryptedPassword, 0, combined, encryptedAesKey.Length, encryptedPassword.Length);

    return Convert.ToBase64String(combined);
    }
    }
    }
    }

    // Decrypt the password using AES and RSA hybrid encryption
    public static string DecryptPassword(string encryptedData, string rsaPrivateKey)
    {
    byte[] encryptedBytes = Convert.FromBase64String(encryptedData);

    // Step 1: Extract the encrypted AES Key and the encrypted Password
    byte[] encryptedAesKey = new byte[256]; // 2048-bit RSA key (256 bytes)
    Array.Copy(encryptedBytes, 0, encryptedAesKey, 0, encryptedAesKey.Length);

    byte[] encryptedPassword = new byte[encryptedBytes.Length – encryptedAesKey.Length];
    Array.Copy(encryptedBytes, encryptedAesKey.Length, encryptedPassword, 0, encryptedPassword.Length);

    // Step 2: Decrypt the AES Key using RSA Private Key
    using (RSA rsa = RSA.Create())
    {
    rsa.ImportRSAPrivateKey(Convert.FromBase64String(rsaPrivateKey), out _);
    byte[] aesKey = rsa.Decrypt(encryptedAesKey, RSAEncryptionPadding.OaepSHA256);

    // Step 3: Decrypt the password using AES
    using (Aes aes = Aes.Create())
    {
    aes.Key = aesKey;
    aes.IV = new byte[16]; // Set IV to the one used during encryption (extract from data)
    Array.Copy(encryptedPassword, 0, aes.IV, 0, 16);

    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
    using (MemoryStream msDecrypt = new MemoryStream(encryptedPassword, 16, encryptedPassword.Length – 16))
    {
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
    {
    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
    {
    return srDecrypt.ReadToEnd();
    }
    }
    }
    }
    }
    }

    static void Main()
    {
    // Generate RSA Key Pair
    var (publicKey, privateKey) = GenerateRSAKeys();

    // Test password
    string password = “Samsung@123”;

    // Encrypt password using RSA and AES hybrid encryption
    string encryptedPassword = EncryptPassword(password, publicKey);
    Console.WriteLine(“Encrypted Password: ” + encryptedPassword);

    // Decrypt password using RSA private key and AES
    string decryptedPassword = DecryptPassword(encryptedPassword, privateKey);
    Console.WriteLine(“Decrypted Password: ” + decryptedPassword);
    }
    }

  13. jazz

    public static string EncryptUpgrade(string plainText) // Servify document code snippet
    {
    byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

    PemReader pr = new PemReader(
    (StreamReader)File.OpenText(System.Web.Hosting.HostingEnvironment.MapPath(“~/Contents/RSAKeys/prod-public-key.pem”)) //PROD
    //(StreamReader)File.OpenText(System.Web.Hosting.HostingEnvironment.MapPath(“~/Contents/RSAKeys/servify_pubkey.pem”)) //UAT
    );

    RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject();

    // PKCS1 OAEP paddings
    OaepEncoding eng = new OaepEncoding(new RsaEngine());
    eng.Init(true, keys);

    int length = plainTextBytes.Length;
    int blockSize = eng.GetInputBlockSize();
    List cipherTextBytes = new List();
    for (int chunkPosition = 0;
    chunkPosition < length;
    chunkPosition += blockSize)
    {
    int chunkSize = Math.Min(blockSize, length – chunkPosition);
    cipherTextBytes.AddRange(eng.ProcessBlock(
    plainTextBytes, chunkPosition, chunkSize
    ));
    }
    return Convert.ToBase64String(cipherTextBytes.ToArray());
    }
    public static string DecryptUpgrade(string cipherText) // Servify document code snippet
    {
    byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

    PemReader pr = new PemReader(
    (StreamReader)File.OpenText(System.Web.Hosting.HostingEnvironment.MapPath("~/Contents/RSAKeys/prod-private-key.pem"))
    );
    AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject();

    // Pure mathematical RSA implementation
    // RsaEngine eng = new RsaEngine();

    // PKCS1 v1.5 paddings
    // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());

    // PKCS1 OAEP paddings
    OaepEncoding eng = new OaepEncoding(new RsaEngine());
    eng.Init(false, keys.Private);

    int length = cipherTextBytes.Length;
    int blockSize = eng.GetInputBlockSize();
    List plainTextBytes = new List();
    for (int chunkPosition = 0;
    chunkPosition < length;
    chunkPosition += blockSize)
    {
    int chunkSize = Math.Min(blockSize, length – chunkPosition);
    plainTextBytes.AddRange(eng.ProcessBlock(
    cipherTextBytes, chunkPosition, chunkSize
    ));
    }
    return Encoding.UTF8.GetString(plainTextBytes.ToArray());
    }

  14. Jazz

    import { Injectable } from ‘@angular/core’;
    import * as forge from ‘node-forge’;

    @Injectable({
    providedIn: ‘root’
    })
    export class RsaService {
    private publicKey!: CryptoKey;
    private privateKey!: CryptoKey;

    constructor() {}

    // Load public key from PEM format and import to CryptoKey
    async loadPublicKey(pem: string): Promise {
    const pemHeader = “—–BEGIN PUBLIC KEY—–“;
    const pemFooter = “—–END PUBLIC KEY—–“;
    const pemContents = pem.substring(
    pem.indexOf(pemHeader) + pemHeader.length,
    pem.indexOf(pemFooter)
    ).replace(/\s/g, ”);

    const binaryDer = forge.util.decode64(pemContents);
    const binaryDerArray = this.str2ab(binaryDer);

    this.publicKey = await crypto.subtle.importKey(
    “spki”,
    binaryDerArray,
    {
    name: “RSA-OAEP”,
    hash: { name: “SHA-1” }, // Use SHA-1 for OAEP padding
    },
    true,
    [“encrypt”]
    );
    }

    // Load private key from PEM format and import to CryptoKey
    async loadPrivateKey(pem: string): Promise {
    const pemHeader = “—–BEGIN PRIVATE KEY—–“;
    const pemFooter = “—–END PRIVATE KEY—–“;
    const pemContents = pem.substring(
    pem.indexOf(pemHeader) + pemHeader.length,
    pem.indexOf(pemFooter)
    ).replace(/\s/g, ”);

    const binaryDer = forge.util.decode64(pemContents);
    const binaryDerArray = this.str2ab(binaryDer);

    this.privateKey = await crypto.subtle.importKey(
    “pkcs8”,
    binaryDerArray,
    {
    name: “RSA-OAEP”,
    hash: { name: “SHA-1” }, // Use SHA-1 for OAEP padding
    },
    true,
    [“decrypt”]
    );
    }

    // Encrypt data with RSA public key
    async encryptData(data: string): Promise {
    const encoder = new TextEncoder();
    const encodedData = encoder.encode(data);

    const encryptedData = await crypto.subtle.encrypt(
    {
    name: “RSA-OAEP”,
    },
    this.publicKey,
    encodedData
    );

    return this.arrayBufferToBase64(encryptedData);
    }

    // Decrypt data with RSA private key
    async decryptData(encryptedData: string): Promise {
    const decodedData = this.base64ToArrayBuffer(encryptedData);

    const decryptedData = await crypto.subtle.decrypt(
    {
    name: “RSA-OAEP”,
    },
    this.privateKey,
    decodedData
    );

    const decoder = new TextDecoder();
    return decoder.decode(decryptedData);
    }

    // Helper function: Convert ArrayBuffer to Base64
    private arrayBufferToBase64(buffer: ArrayBuffer): string {
    let binary = ”;
    const bytes = new Uint8Array(buffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
    }

    // Helper function: Convert Base64 to ArrayBuffer
    private base64ToArrayBuffer(base64: string): ArrayBuffer {
    const binaryString = window.atob(base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
    }

    // Helper function: Convert string to ArrayBuffer
    private str2ab(str: string): ArrayBuffer {
    const buf = new ArrayBuffer(str.length);
    const bufView = new Uint8Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
    }
    return buf;
    }
    }

  15. Jazz

    import { Component, OnInit } from ‘@angular/core’;
    import { RsaService } from ‘./rsa.service’;

    @Component({
    selector: ‘app-rsa-demo’,
    templateUrl: ‘./rsa-demo.component.html’,
    styleUrls: [‘./rsa-demo.component.css’]
    })
    export class RsaDemoComponent implements OnInit {
    encryptedData!: string;
    decryptedMessage!: string;

    constructor(private rsaService: RsaService) {}

    async ngOnInit() {
    // Load public/private keys from PEM strings
    const publicKeyPem = `—–BEGIN PUBLIC KEY—–
    YOUR_PUBLIC_KEY_HERE
    —–END PUBLIC KEY—–`;

    const privateKeyPem = `—–BEGIN PRIVATE KEY—–
    YOUR_PRIVATE_KEY_HERE
    —–END PRIVATE KEY—–`;

    await this.rsaService.loadPublicKey(publicKeyPem);
    await this.rsaService.loadPrivateKey(privateKeyPem);

    // Encrypt and Decrypt Data
    const message = “Hello, RSA!”;
    this.encryptedData = await this.rsaService.encryptData(message);
    console.log(“Encrypted data:”, this.encryptedData);

    this.decryptedMessage = await this.rsaService.decryptData(this.encryptedData);
    console.log(“Decrypted message:”, this.decryptedMessage);
    }
    }

  16. Jazz

    import android.util.Base64;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import org.bouncycastle.util.io.pem.PemObject;
    import org.bouncycastle.util.io.pem.PemReader;

    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.security.KeyFactory;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.Security;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import javax.crypto.Cipher;

    public class RsaUtil {

    static {
    // Add BouncyCastle as a Security Provider
    Security.addProvider(new BouncyCastleProvider());
    }

    // Load Public Key from PEM file
    public static PublicKey loadPublicKey(InputStreamReader publicKeyPem) throws Exception {
    PemReader pemReader = new PemReader(publicKeyPem);
    PemObject pemObject = pemReader.readPemObject();
    byte[] keyBytes = pemObject.getContent();
    pemReader.close();

    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(“RSA”, “BC”);
    return keyFactory.generatePublic(spec);
    }

    // Load Private Key from PEM file
    public static PrivateKey loadPrivateKey(InputStreamReader privateKeyPem) throws Exception {
    PemReader pemReader = new PemReader(privateKeyPem);
    PemObject pemObject = pemReader.readPemObject();
    byte[] keyBytes = pemObject.getContent();
    pemReader.close();

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(“RSA”, “BC”);
    return keyFactory.generatePrivate(spec);
    }

    // Encrypt data with RSA Public Key using OAEP padding
    public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
    Cipher cipher = Cipher.getInstance(“RSA/ECB/OAEPWithSHA-1AndMGF1Padding”, “BC”);
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(“UTF-8”));
    return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
    }

    // Decrypt data with RSA Private Key using OAEP padding
    public static String decrypt(String cipherText, PrivateKey privateKey) throws Exception {
    Cipher cipher = Cipher.getInstance(“RSA/ECB/OAEPWithSHA-1AndMGF1Padding”, “BC”);
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] encryptedBytes = Base64.decode(cipherText, Base64.DEFAULT);
    byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
    return new String(decryptedBytes, “UTF-8”);
    }
    }

    // Load PEM files from assets or raw resources
    InputStreamReader publicKeyReader = new InputStreamReader(context.getAssets().open(“prod-public-key.pem”));
    InputStreamReader privateKeyReader = new InputStreamReader(context.getAssets().open(“prod-private-key.pem”));

    PublicKey publicKey = RsaUtil.loadPublicKey(publicKeyReader);
    PrivateKey privateKey = RsaUtil.loadPrivateKey(privateKeyReader);

    // Encrypt and Decrypt
    String message = “Hello, RSA!”;
    String encryptedMessage = RsaUtil.encrypt(message, publicKey);
    System.out.println(“Encrypted Message: ” + encryptedMessage);

    String decryptedMessage = RsaUtil.decrypt(encryptedMessage, privateKey);
    System.out.println(“Decrypted Message: ” + decryptedMessage);

  17. jazz

    public static String encrypt256RSA(String data) throws Exception {

    try {

    Key publicKey = importPublicKey(RSA_PUBLIC_KEY);

    Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”);

    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    byte[] encryptedBytes = cipher.doFinal(data.getBytes(“UTF-8”));

    return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP);

    } catch (Exception e) {

    e.printStackTrace();

    return “”;

    }

    }

    public static PublicKey importPublicKey(String publicKeyStr) throws Exception {

    byte[] keyBytes = Base64.decode(publicKeyStr, Base64.NO_WRAP);

    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);

    KeyFactory keyFactory = KeyFactory.getInstance(“RSA”);

    return keyFactory.generatePublic(spec);

    }

    public static String decrypt256RSA(String encryptedData) throws Exception {

    try{

    Key privateKey = importPrivateKey(RSA_PRIVATE_KEY);

    byte[] encryptedBytes = Base64.decode(encryptedData, Base64.NO_WRAP);

    Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”);

    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

    return new String(decryptedBytes, “UTF-8”);

    }catch (Exception e){

    e.printStackTrace();

    return “”;

    }

    }

    public static PrivateKey importPrivateKey(String privateKeyStr) throws Exception {

    byte[] keyBytes = Base64.decode(privateKeyStr, Base64.NO_WRAP);

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);

    KeyFactory keyFactory = KeyFactory.getInstance(“RSA”);

    return keyFactory.generatePrivate(spec);

    }

Leave a Reply

Your email address will not be published. Required fields are marked *

Let's connect