Encrypting Data with SHA-1 Algorithm in JavaScript

Could someone please provide guidance on how to accomplish this task?

I have successfully implemented hashing using sha1 in c#, but I am uncertain of how to achieve the same functionality using javascript.

I am eager to learn different techniques for accomplishing this. Thank you!

Edit: I have attempted to use the following link:

I am confused as to why the results from SHA1CryptoServiceProvider in c# differ from the example provided in the link above.

Here is the code that I have tried : 1. Example mentioned in the above link (javascript) 2.

 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
 <asp:Button ID="Button1" runat="server" Text="Button_ServerSide" onclick="Button1_Click" />

Code Behind:

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Security.Cryptography;
    using System.Text;

   public partial class Default2 : System.Web.UI.Page
   {
   protected void Page_Load(object sender, EventArgs e)
   {

   } 
   protected void Button1_Click(object sender, EventArgs e)
   {
    string strText = String.Empty;
    strText = TextBox1.Text;
    //SHA512CryptoServiceProvider encrypt = new SHA512CryptoServiceProvider();
    SHA1CryptoServiceProvider encrypt = new SHA1CryptoServiceProvider();
    byte[] encryptText = encrypt.ComputeHash(Encoding.Default.GetBytes(strText));

    TextBox1.Text = "";


    foreach (byte tempData in strText)
    {
        TextBox1.Text = TextBox1.Text + "x";

    }
    string str = System.Text.Encoding.Default.GetString(encryptText);
    Response.Write("Entered Text: " + strText + "  Encrypted Text Length: " + encryptText.Length + "    enpwd: " + strText);
    Response.Write("           encryptText: " + encryptText.Equals(strcrypt.Value));
    Response.Write("           encryptText STR: " + str);


    //ProtectedData.Protect();
}

}

Answer №1

If you're looking to implement hashing functions in Javascript, you won't find them built-in. Instead, consider using an external library for this purpose.

For further information and examples on implementing hashing in Javascript, check out this thread on StackOverflow.

Answer №2

If you're looking to address your issue, consider checking out these helpful resources:

Answer №3

sha1 = function(r) {
    var t = function() {
        function r() {
            e[0] = 1732584193, e[1] = 4023233417, e[2] = 2562383102, e[3] = 271733878, e[4] = 3285377520, 
            s = c = 0;
        }
        function t(r) {
            var t, n, o, f, a, u, c, s;
            for (t = i, n = 0; 64 > n; n += 4) t[n / 4] = r[n] << 24 | r[n + 1] << 16 | r[n + 2] << 8 | r[n + 3];
            for (n = 16; 80 > n; n++) r = t[n - 3] ^ t[n - 8] ^ t[n - 14] ^ t[n - 16], t[n] = 4294967295 & (r << 1 | r >>> 31);
            for (r = e[0], o = e[1], f = e[2], a = e[3], u = e[4], n = 0; 80 > n; n++) 40 > n ? 20 > n ? (c = a ^ o & (f ^ a), 
            s = 1518500249) : (c = o ^ f ^ a, s = 1859775393) : 60 > n ? (c = o & f | a & (o | f), 
            s = 2400959708) : (c = o ^ f ^ a, s = 3395469782), c = (4294967295 & (r << 5 | r >>> 27)) + c + u + s + t[n] & 4294967295, 
            u = a, a = f, f = 4294967295 & (o << 30 | o >>> 2), o = r, r = c;
            e[0] = e[0] + r & 4294967295, e[1] = e[1] + o & 4294967295, e[2] = e[2] + f & 4294967295, 
            e[3] = e[3] + a & 4294967295, e[4] = e[4] + u & 4294967295;
        }
        function n(r, n) {
            if ("string" == typeof r) {
                for (var o = [], e = 0, i = (r = unescape(encodeURIComponent(r))).length; e < i; ++e) o.push(r.charCodeAt(e));
                r = o;
            }
            if (n || (n = r.length), o = 0, 0 == c) for (;o + 64 < n; ) t(r.slice(o, o + 64)), 
            o += 64, s += 64;
            for (;o < n; ) if (f[c++] = r[o++], s++, 64 == c) for (c = 0, t(f); o + 64 < n; ) t(r.slice(o, o + 64)), 
            o += 64, s += 64;
        }
        function o() {
            var r, o, i = [], u = 8 * s;
            for (n(a, 56 > c ? 56 - c : 64 - (c - 56)), r = 63; 56 <= r; r--) f[r] = 255 & u, 
            u >>>= 8;
            for (t(f), r = u = 0; 5 > r; r++) for (o = 24; 0 <= o; o -= 8) i[u++] = e[r] >> o & 255;
            return i;
        }
        var e, f, i, a, u, c, s;
        for (e = [], f = [], i = [], a = [ 128 ], u = 1; 64 > u; ++u) a[u] = 0;
        return r(), {
            reset: r,
            update: n,
            digest: o,
            digestString: function() {
                for (var r = o(), t = "", n = 0; n < r.length; n++) t += "0123456789ABCDEF".charAt(Math.floor(r[n] / 16)) + "0123456789ABCDEF".charAt(r[n] % 16);
                return t;
            }
        };
    }();
    return t.update(r), t.digestString().toLowerCase();
};

console.log(sha1("admin"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing asynchronous code when updating state using React hooks

Here's a scenario I'm dealing with: const [loading, setLoading] = useState(false); ... setLoading(true); doSomething(); // <--- at this point, loading remains false. Since setting state is asynchronous, what would be the best approach to ...

checkbox revision

I'm attempting to update some text indicating whether or not a checkbox is checked. The issue is that when the checkbox is checked, the textbox disappears and the text takes its place. <form name="myForm" id="myForm"> <input type="checkb ...

Encountered a TypeError: The super expression should be defined as null or a function, not undefined in a React application

Contents of package.json { "name": "react_playlist", "version": "1.0.0", "description": "All course files for the React tutorial playlist on YouTube by Net Ninja", "main": "index.js", "scripts": { "test": "echo \"Error: no test specifie ...

What is the significance of $() in jQuery?

I understand that $() is a selector, but I find it puzzling as to what it actually selects since there is nothing inside the parentheses. Is this a common practice or frowned upon in coding conventions? An example of where I have seen it used is when maki ...

Various gulp origins and destinations

I am attempting to create the following directory structure -- src |__ app |__ x.ts |__ test |__ y.ts -- build |__ app |__ js |__ test |__ js My goal is to have my generated js files inside buil ...

Content Management System editing plan

Have you ever wondered if there is a structured approach to editing content management systems like Wordpress and Joomla? When it comes to editing aspects such as CSS and JavaScript, what steps do you usually take? Personally, I have been creating files l ...

How can you display a doughnut chart with a custom color to represent empty or no data, including doughnut rings?

I have integrated a doughnut chart from chartjs into my Vue project using vue-chartjs. Currently, the doughnut chart does not display anything when there is no data or all values are empty. Is there a way to customize the color and show the entire doughnu ...

Issues with loading NextJS videos can occur when accessing a page through a link, as the videos may fail to load without

Issue Greetings. The problem arises when attempting to load muse.ai videos on-page, specifically when accessing the page with a video embedded through a NextJS link. To showcase this issue, I have provided a minimal reproducible example on StackBlitz her ...

Populate a dropdown menu using Javascript

[Code] $.ajax ({ 'method': 'GET', 'source': '/bpv-registratie/periods/show_period_list_by_year.html', 'charge': function () { }, 'finish': function (xmlHttp) { ...

Incorporate a video within the royal slider feature

Next is my deluxe slider code. This slider displays only images but I am looking to incorporate video as well. I have searched online and tried different solutions, but haven't found one that works for me. Can someone please guide me on how to achieve ...

Troubleshooting Mongoose and MongoDb Connectivity Issues

Previously, I had no trouble connecting to Atlas from my home wifi, but I encountered issues at Starbucks. After switching to google fiber, I am now facing this error. at Pool.<anonymous> (/Users/j/Desktop/projects/templateApp/node_modules/mong ...

Utilizing ThemeProvider in a Different Component in React

In my App.js file, I have a function that toggles between light and dark mode themes: import { createTheme, ThemeProvider } from '@mui/material/styles' import Button from '@mui/material/Button' import Header from './components/Head ...

Create an unordered Vue component object

In the data retrieved from the backend, there is an object containing various properties, one of which is the 'average' value. This object is ordered based on that value and when accessed through Postman, it appears as follows: ranking: ...

Correctly define the vm function within the Controller As scope

I am a newcomer to javascript and AngularJS. So... Maybe it's a simple question, but I've noticed two ways to define functions in javascript. In the following controllers, pay attention to "grupoCancha" and "grupoVisible" (I included the entire ...

Implement a function within a v-for iteration

Currently, I am facing a challenge in Vue 3 while attempting to design a menu with categories and corresponding subcategories. The objective is that upon clicking on a category, only the specific subcategories related to that category should be displayed b ...

Retrieve the boolean value associated with a checkbox

I inherited a project from another developer. The code is able to retrieve data from the text input fields in the form, but not from the checkbox inputs. The previous developer implemented these functions (among others): protected function getObjectStrin ...

Slideshow elements removed

I attempted to remove my links individually from the div id="wrapper", but unfortunately have encountered an issue while doing so: window.onload = function () { setInterval(function () { var wrapper = document.getElementById("wrapper"); var my_l ...

There was an unhandled rejection error stating: "TypeError - Unable to access property 'push' as it is undefined"

I am encountering an issue while trying to create a function that returns all indexes of an array. I'm not sure what mistake I might be making, as I keep getting an error stating that push cannot be used due to an undefined value. Here's the cod ...

Creating HighStock charts on the server-side using NodeJS

I'm currently utilizing HighStock to create charts within the browser. However, I now have a need to save some of these charts on the server. While I understand that HighCharts offers an export option to the server, I am interested in exploring other ...

Selecting from a variety of options presented as an array of objects

I am currently working on a component that allows users to select roles: https://i.stack.imgur.com/bnb9Y.png export const MultipleSelectChip = ({ options, label, error, onRolesUpdate, }: Props) => { const theme = useTheme(); const [selected ...