Encryption using sha in asp.net

Task: Encryption using SHA with encryptionkey in asp.net and c#..

Description: Encryption using SHA in asp.net and c#. Using below code we can generate message digest. In Web technology we need to save password of user, for this we can use this one. It is one way encryption, we can't decrypt it back.

using System.Security.Cryptography;
public string shaEncrption(string plainText, string encryptionkey)
        string key = encryptionkey;
        byte[] plainTextBytes = ASCIIEncoding.ASCII.GetBytes(plainText);
        // Allocate array, which will hold plain text and salt.
        byte[] plainTextWithkeyBytes = null;
        byte[] keyBytes;
        if (!string.IsNullOrEmpty(key))
            // Convert salt text into a byte array.
            keyBytes = ASCIIEncoding.ASCII.GetBytes(key);
            plainTextWithkeyBytes =
                new byte[plainTextBytes.Length + keyBytes.Length];
            // Define min and max salt sizes.
            int minkeySize = 4;
            int maxkeySize = 8;
            // Generate a random number for the size of the key.
            Random random = new Random();
            int keySize = random.Next(minkeySize, maxkeySize);
            // Allocate a byte array, which will hold the key.
            keyBytes = new byte[keySize];
            // Initialize a random number generator.
            RNGCryptoServiceProvider rngCryptoServiceProvider =
                        new RNGCryptoServiceProvider();
            // Fill the key with cryptographically strong byte values.
        // Copy plain text bytes into resulting array.
        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithkeyBytes[i] = plainTextBytes[i];
        // Append salt bytes to the resulting array.
        for (int i = 0; i < keyBytes.Length; i++)
            plainTextWithkeyBytes[plainTextBytes.Length + i] =
        // SHA256 hash = new SHA256CryptoServiceProvider();
        SHA384 hash = new SHA384CryptoServiceProvider();
        // SHA512 hash = new SHA512CryptoServiceProvider();

        byte[] hashBytes = hash.ComputeHash(plainTextWithkeyBytes);
        // Create array which will hold hash and original key bytes.
        byte[] hashWithkeyBytes =
            new byte[hashBytes.Length + keyBytes.Length];
        // Copy hash bytes into resulting array.
        for (int i = 0; i < hashBytes.Length; i++)
            hashWithkeyBytes[i] = hashBytes[i];
        // Append salt bytes to the result.
        for (int i = 0; i < keyBytes.Length; i++)
            hashWithkeyBytes[hashBytes.Length + i] = keyBytes[i];
        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(hashWithkeyBytes);
        return hashValue;
    catch (Exception ex)
        return null;

Post JSON data with Authorization header using asp.net and c#

Task: Post JSON data with Authorization header using asp.net and c#.

Description: Post JSON data with Authorization header using asp.net and c#. There is two methods for posting form, Get and Post. Here I used Post method with Basic Authorization header for submitting the form. 

using System.Net;
using System.IO;
using System.Web.Script.Serialization;
public class ProductResponse
    public string submitstatus { get; set; }
    public string reference { get; set; }

public void ProductSubmit( )
        string baseurl = "https://hemantrautela.blogspot.com/productsubmit";
        string Authkey = "ba1f3a6e97ceed3358c9b8a54d2a8f56efexy78d";
        string postString = @"{'productid': '7',
                          'quantity': '1',
                          'total_amount': 700.00,
                          'curruncy': 'INR',
                          'clientIpAddress': '" + Request.UserHostAddress + @"',
                          'clientUserAgent': '" + Request.UserAgent + @"' }";

        HttpWebRequest webReq = WebRequest.Create(baseurl) as HttpWebRequest;
        webReq.Method = "POST";
        webReq.ContentType = "application/json; charset=utf-8";
        webReq.ContentLength = postString.Length;
        webReq.Accept = "application/json";
        webReq.Headers.Add("API-Version", "4.1.0");

        byte[] authBytes = Encoding.UTF8.GetBytes((Authkey).ToCharArray());
        webReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(authBytes));

        StreamWriter requestWriter = new StreamWriter(webReq.GetRequestStream());

        StreamReader responseReader = new StreamReader(webReq.GetResponse().GetResponseStream());

        string responseData = responseReader.ReadToEnd();

        ProductResponse productresp = new JavaScriptSerializer().Deserialize<ProductResponse>(responseData);

        List<ProductResponse> resp_obj = new List<ProductResponse>();

        string referencevalue = productresp.reference;
        string submitstatus = productresp.submitstatus;

    catch (Exception ex)

Remove new line from title tag created dynamically

Task:  Remove extra new line from dynamically created title tag 

Description: Remove extra new line from dynamically created title tag.  As previously we created Title tag (Title of page) using code (Link) for SEO purpose. There is a little issue with Title tag, It takes extra new line but in SEO we want to remove this new line. we can use this in Master Page so that we needn't to rewrite it for every page.

using System.Reflection;
public static void InitializeTitleTag()
    Type type = typeof(HtmlTextWriter);
    FieldInfo field = type.GetField("_tagNameLookupArray", BindingFlags.Static | BindingFlags.NonPublic);
    Array lookup = (Array)field.GetValue(null);
    int index = (int)HtmlTextWriterTag.Title;
    object value = lookup.GetValue(index);
    type = value.GetType();
    field = type.GetField("tagType");
    field.SetValue(value, 0);
    lookup.SetValue(value, index);


Upload file via FTP using asp.net c#

Task: Generally we used FileZilla or any other FTP software for uploading a file on Web Server. Here we can also use our c# code for that. FTP file upload using asp.net and c#.

Description: We can upload our file via FTP using C#.

using System.Net;
using System.Text.RegularExpressions;
using System.IO;
public string UploadFile()
    string filePath = Server.MapPath(@"FolderName\file.jpg");
    string FtpUrl =  "ftp://ftp.domain.com/";
    string userName = "ftp_user";      
    string password =   "ftp_password";
    string UploadDirectory = "";
    string PureFileName = new FileInfo(filePath).Name;
    String uploadUrl = String.Format("{0}{1}/{2}", FtpUrl, UploadDirectory, PureFileName);
    FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
    req.Proxy = null;
    req.Method = WebRequestMethods.Ftp.UploadFile;
    req.Credentials = new NetworkCredential(userName, password);
    req.UseBinary = true;
    req.UsePassive = true;
    byte[] data = File.ReadAllBytes(filePath);
    req.ContentLength = data.Length;
    Stream stream = req.GetRequestStream();
    stream.Write(data, 0, data.Length);
    FtpWebResponse res = (FtpWebResponse)req.GetResponse();
    return res.StatusDescription;
catch (Exception ex)
    return "";


Get link from HTML code anchor tag

Task: Get Link from HTML code anchor <a> tag using Asp.net and C# code.

Description:  Sometime we need to retrieve link from HTML code <a> tag Or sometime we need to modify/append/alter that link.
So in this function the HTML code is use as input and then we can retrieve link in that html code <a> tag.


public void getlinkfromhtml(string content)
  int index = 0;
    int newindex = index + 5;
    index = content.IndexOf("href=", newindex);
    if (index > 0)
      int index2 = content.IndexOf('\'', index + 6);
      int index3 = content.IndexOf('\"', index + 6);

      if (index3 > 0)
        if (index2 > index3 || index2 == (-1))
            index2 = index3;
      if (index2 > 0)
        string href = content.Substring(index+6,(index2-(index + 6))).ToLower();

// Save/Use or do anything with this link href. You Can replace also this with another link.

  while (index > 1);

View Pdf on browser using asp.net

Task: View Pdf on browser using asp.net.

Description: Here I show how we can view the pdf file on browser using asp.net and c#.

using System.Net;
public void viewebook(string pdf_filepath)
    string FilePath = Server.MapPath(pdf_filepath);
    WebClient User = new WebClient();
    Byte[] FileBuffer = User.DownloadData(FilePath);
    if (FileBuffer != null)
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", FileBuffer.Length.ToString());


Facebook feed using graph api

Task: Get Facebook page feed using graph api.

Description: As facebook depreciated old feed url (https://www.facebook.com/feeds/page.php?format=rss20&id=page_id). So now we need to use its graph api for this.

Here I describe how to get facebook page feed using graph api using javascript code. You just need to update your access token ( use app token as access token from here https://developers.facebook.com/tools/accesstoken/ ). 

you can run below url on your browser for all fields and can use as your requirements. In below code limit is use for how many post will return.



<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="https://connect.facebook.net/en/all.js" type="text/javascript"></script>
 FB.api('https://graph.facebook.com/page_id/feed?access_token=yourapptoken', { limit: 20 }, function (response) {

 if (response && !response.error) {
 var msg='';
            for (var i = 0, l = response.data.length; i < l; i++) {
                var post = response.data[i];
                var userid = post.from.id;
                if (post.message) {                       
                    msg += '<span style="word-break: break-all;">'+ post.message  + '<br/><a  rel="nofollow" href='+post.link+'><img src=' +  post.picture  +' /></a>' + '</span><br/><br/>';                       
               // alert('Error Occure');

<div id="fb-root"></div>
<div id="sFbFeeds"></div>