preface

What is encryption for?

In a certain scope of business, our front-end may use encryption related knowledge is relatively little, but it is inevitable that in some cases we still need to have a certain understanding of encryption, such as order information, user account information, secret key information and so on. Here are some common encryption methods. In subsequent updates, 🍗…

base64

Introduction to the

1 alphanumeric character = 1 byte = 8 bits, which is the unit of representation.

Base64 is one of the most common encoding methods for transmitting 8 bits on the network. Base64 is a method of representing binary data based on 64 printable characters.

In some network transport channels, sometimes some byte characters are not supported. For example, every byte of the binary stream of an image cannot be all visible characters, in which case it cannot be transmitted. Base64 is a good way to solve this problem. It does not change the original protocol, but makes an extension based on 64 printable characters to represent binary.

Moreover, sometimes we use notepad to open some pictures or applications, will get a lot of can’t read the code, because there are many binary file cannot display and print characters, so if you want to let the notepad to handle binary data, you can use the base64 for transcoding, will not be visible to visible.

Algorithm principle

  1. We get a string of characters like abcdef encoded in ASCII;
  2. It splits the string into groups of three bytes.
3 byte * 8 bit === 24bit.
Copy the code
  1. In this group, the 24-bit data was divided into 4 groups again according to the 6-bit group.
  2. Then add two zeros to each of the four groups of six digits to convert them into decimal numbers.
  3. Lookup table, get the corresponding character, is the corresponding base64 transformed character.

The problem is, if the number of bits in the original data is not a multiple of 3, base64 will use a “=” to fill in the missing bits, so the “=” will only exist at the end of the base64 code, and there will only be 1 or 2 bits, not in the middle.

Code implementation

/ / javaScript implementation

if(! Shotgun)var Shotgun = {};
if(! Shotgun.Js) Shotgun.Js = {}; Shotgun.Js.Base64 = {_table: [
        'A'.'B'.'C'.'D'.'E'.'F'.'G'.'H'.'I'.'J'.'K'.'L'.'M'.'N'.'O'.'P'.'Q'.'R'.'S'.'T'.'U'.'V'.'W'.'X'.'Y'.'Z'.'a'.'b'.'c'.'d'.'e'.'f'.'g'.'h'.'i'.'j'.'k'.'l'.'m'.'n'.'o'.'p'.'q'.'r'.'s'.'t'.'u'.'v'.'w'.'x'.'y'.'z'.'0'.'1'.'2'.'3'.'4'.'5'.'6'.'7'.'8'.'9'.'+'.'/'].encode: function (bin) {
        var codes = [];
        var un = 0;
        un = bin.length % 3;
        if (un == 1)
            bin.push(0.0);
        else if (un == 2)
            bin.push(0);
        for (var i = 2; i < bin.length; i += 3) {
            var c = bin[i - 2] < <16;
            c |= bin[i - 1] < <8;
            c |= bin[i];
            codes.push(this._table[c >> 18 & 0x3f]);
            codes.push(this._table[c >> 12 & 0x3f]);
            codes.push(this._table[c >> 6 & 0x3f]);
            codes.push(this._table[c & 0x3f]);
        }
        if (un >= 1) {
            codes[codes.length - 1] = "=";
            bin.pop();
        }
        if (un == 1) {
            codes[codes.length - 2] = "=";
            bin.pop();
        }
        return codes.join("");
    },
    decode: function (base64Str) {
        var i = 0;
        var bin = [];
        var x = 0, code = 0, eq = 0;
        while (i < base64Str.length) {
            var c = base64Str.charAt(i++);
            var idx = this._table.indexOf(c);
            if (idx == -1) {
                switch (c) {
                    case '=': idx = 0; eq++; break;
                    case ' ':
                    case '\n':
                    case "\r":
                    case '\t':
                        continue;
                    default:
                        throw { "message": "\u0062\u0061\u0073\u0065\u0036\u0034\u002E\u0074\u0068\u0065\u002D\u0078\u002E\u0063\u006E\u0020\u0045\u0072\u0072\u006 F\u0072\u003A\u65E0\u6548\u7F16\u7801\uFF1A"+ c }; }}if (eq > 0&& idx ! =0)
                throw { "message": "\u0062\u0061\u0073\u0065\u0036\u0034\u002E\u0074\u0068\u0065\u002D\u0078\u002E\u0063\u006E\u0020\u0045\u0072\u0072\u006 F\u0072\u003A\u7F16\u7801\u683C\u5F0F\u9519\u8BEF\uFF01" };
  
            code = code << 6 | idx;
            if(++x ! =4)
                continue;
            bin.push(code >> 16);
            bin.push(code >> 8 & 0xff);
            bin.push(code & 0xff)
            code = x = 0;
        }
        if(code ! =0)
            throw { "message": "\u0062\u0061\u0073\u0065\u0036\u0034\u002E\u0074\u0068\u0065\u002D\u0078\u002E\u0063\u006E\u0020\u0045\u0072\u0072\u006 F\u0072\u003A\u7F16\u7801\u6570\u636E\u957F\u5EA6\u9519\u8BEF" };
        if (eq == 1)
            bin.pop();
        else if (eq == 2) {
            bin.pop();
            bin.pop();
        } else if (eq > 2)
            throw { "message": "\u0062\u0061\u0073\u0065\u0036\u0034\u002E\u0074\u0068\u0065\u002D\u0078\u002E\u0063\u006E\u0020\u0045\u0072\u0072\u006 F\u0072\u003A\u7F16\u7801\u683C\u5F0F\u9519\u8BEF\uFF01" };
  
        returnbin; }};Copy the code

application

  • Base64 encoding can be used to pass longer identity information in HTTP environments.
  • Email: Some text protocols do not support the transmission of invisible characters. Messages can only be transmitted with visible characters greater than 32 characters.
  • Base64 is also often used as a simple “encryption” to protect some data, and real encryption is often cumbersome.
  • Spammers use Base64 to get around anti-spam tools that usually don’t translate base64 messages.
  • When the front end realizes some small pictures on the page, it usually chooses to embed the picture content directly in the page to avoid unnecessary external resource loading and increase the page loading time. However, the picture data is binary data, how to embed it? Most modern browsers support a feature called Data URLs, which allows you to encode the binary Data of an image or other file in Base64 and embed it as a text string in a Web page. For example, the url-loader in the Webpack tool compiles images below 8KB into base64 code by default and embed them in reference files.

Front end use

crypto-js

Powerful function, more than processing base64, support a lot of modules, star number is currently 6K +, the front and back end available.

// Back-end NPM package management
npm install crypto-js

import sha256 from 'crypto-js/sha256';
import hmacSHA512 from 'crypto-js/hmac-sha512';
import Base64 from 'crypto-js/enc-base64';

const message, nonce, path, privateKey; // ...
const hashDigest = sha256(nonce + message);
const hmacDigest = Base64.stringify(hmacSHA512(path + hashDigest, privateKey));

// Front-end Brower management
bower install crypto-js
Copy the code

Js-base64 specifically deals with Base64, currently star number 2k+, both front and back ends are available

/ / installation
$ npm install --save js-base64
// If you are using ES6 syntax, you need to reprint this for syntax conversion
$ npm install --save babel-preset-env

//node.js
var Base64 = require('js-base64').Base64;
//es6+
import { Base64 } from 'js-base64';

// Very light experience
Base64.encode('dankogai');  // ZGFua29nYWk=
Base64.encode('Small band');    // 5bCP6aO85by+
Base64.encodeURI('Small band'); // 5bCP6aO85by-
Copy the code

decryption

If you understand the principle of the algorithm, then decryption is not too much of a problem, as long as you follow the rule of inverse calculation, you can get the original data. So base64 isn’t strictly encryption, just compiled instead of plain text.

MD5

Introduction to the

MD5 is a message-digest Algorithm that produces a 128bit hash.

12345 MD5 = = = > e10adc3949ba59abbe56e057f20f883e / / say good 128, why there are 32 characters. / / this string of code is hexadecimal representation, 1 = = 4 bit binary.Copy the code

Due to its algorithm, the length of MD5 encryption results in 32 characters regardless of the size of the file data (1 Chinese character is equal to 2 bytes, 1 alphabetic character is equal to 1 byte). If the data with the same content is encrypted, the result must be the same. If the content is changed, even if it is a byte, the MD5 value will also be changed.

So it can also be said that MD5 is a lossy algorithm, which is lost to a certain extent. For example, an assumption is compressed file, can be compressed and decompressed before and after, and the content can not be lost, if you use MD5 to do, then there must be a part of the data lost after decompression, certainly not desirable.

So the result of MD5 is not invertible, that is, it is almost impossible to reverse the original data from the MD5 value. Since files of any size are eventually converted to 128-bit values, it is possible to have different raw data converted to the same MD5 value. However, it is very difficult to actively search for two different data sets with the same MD5 value. Or if you have a raw data and its MD5 data, it’s almost impossible to find another original data that matches its MD5 data.

But that’s not to say THAT MD5 is completely unbreakable. Some professional hackers and even ordinary hackers can also use the principle that MD5 value is actually lossy compression technology, and use the value of MD5 inverse operation as a hash table commonly known as rainbow table to crack the password. There are also many MD5 cracking websites on the market, the general principle is similar, by looking up the dictionary to find.

application

Consistency test

For example, MD5 values of file contents are generated during file download. After the file is downloaded, compare the MD5 value of the file with that of the previous file to check the consistency of the file.

Many times, you will find that many files on the Internet are named as a hash with a suffix. The advantage of this process is that it can avoid the same name to some extent, but more useful is that it can be named according to the content of the file to obtain the exclusive MD5 value. Doing so, can be named after the content, can to a certain extent to avoid the waste of resources, duplicate files.

So MD5 is kind of like a fingerprint, each one is unique. If the contents are inconsistent, different MD5 values are generated.

MD5 algorithm is widely used in software download station, forum database, system file security and so on.

A digital signature

The typical use of MD5 is to generate a string of important private information to prevent it from being “tampered with.” You write a paragraph in a file, generate an MD5 value and record it, then you can spread the file to others, and if they change anything in the file, you will find it when you recalculate the MD5 of the file (two MD5 values are different). If there is a third party authentication authority, using MD5 can also prevent the author of the file “repudiation”, this is the so-called digital signature application.

Secure access Authentication

Login is required in most real-world scenarios. When a user logs in, the system hashes the password entered by the user and compares it with the MD5 value saved in the file system to determine whether the entered password is correct. Through such steps, the system can determine the validity of a user’s login without knowing the explicit password of the user. This prevents a user’s password from being known to a user with system administrator privileges.

The principle of

MD5 processes input information in 512-bit packets, and each packet is divided into 16 32-bit packets. After a series of processing, the output of the algorithm consists of four 32-bit packets, which are cascaded to generate a 128-bit hash value.

Quoted from – Liu Junhui. Implementation and Improvement of MD5 Message Digest Algorithm [J]. Fujian Computer, 2007 (4): 92-93.

function md5(string) {
    function md5_RotateLeft(lValue, iShiftBits) {
        return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
    }
    function md5_AddUnsigned(lX, lY) {
        var lX4, lY4, lX8, lY8, lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000^ lX8 ^ lY8); }}else {
            return(lResult ^ lX8 ^ lY8); }}function md5_F(x, y, z) {
        return (x & y) | ((~x) & z);
    }
    function md5_G(x, y, z) {
        return (x & z) | (y & (~z));
    }
    function md5_H(x, y, z) {
        return (x ^ y ^ z);
    }
    function md5_I(x, y, z) {
        return (y ^ (x | (~z)));
    }
    function md5_FF(a, b, c, d, x, s, ac) {
        a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_F(b, c, d), x), ac));
        return md5_AddUnsigned(md5_RotateLeft(a, s), b);
    };
    function md5_GG(a, b, c, d, x, s, ac) {
        a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_G(b, c, d), x), ac));
        return md5_AddUnsigned(md5_RotateLeft(a, s), b);
    };
    function md5_HH(a, b, c, d, x, s, ac) {
        a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_H(b, c, d), x), ac));
        return md5_AddUnsigned(md5_RotateLeft(a, s), b);
    };
    function md5_II(a, b, c, d, x, s, ac) {
        a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_I(b, c, d), x), ac));
        return md5_AddUnsigned(md5_RotateLeft(a, s), b);
    };
    function md5_ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1 = lMessageLength + 8;
        var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
        var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
        var lWordArray = Array(lNumberOfWords - 1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while (lByteCount < lMessageLength) {
            lWordCount = (lByteCount - (lByteCount % 4)) / 4;
            lBytePosition = (lByteCount % 4) * 8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount - (lByteCount % 4)) / 4;
        lBytePosition = (lByteCount % 4) * 8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
        lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
        lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
        return lWordArray;
    };
    function md5_WordToHex(lValue) {
        var WordToHexValue = "",
        WordToHexValue_temp = "",
        lByte, lCount;
        for (lCount = 0; lCount <= 3; lCount++) {
            lByte = (lValue >>> (lCount * 8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2.2);
        }
        return WordToHexValue;
    };
    function md5_Utf8Encode(string) {
        string = string.replace(/\r\n/g."\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128); }}return utftext;
    };
    var x = Array(a);var k, AA, BB, CC, DD, a, b, c, d;
    var S11 = 7,
    S12 = 12,
    S13 = 17,
    S14 = 22;
    var S21 = 5,
    S22 = 9,
    S23 = 14,
    S24 = 20;
    var S31 = 4,
    S32 = 11,
    S33 = 16,
    S34 = 23;
    var S41 = 6,
    S42 = 10,
    S43 = 15,
    S44 = 21;
    string = md5_Utf8Encode(string);
    x = md5_ConvertToWordArray(string);
    a = 0x67452301;
    b = 0xEFCDAB89;
    c = 0x98BADCFE;
    d = 0x10325476;
    for (k = 0; k < x.length; k += 16) {
        AA = a;
        BB = b;
        CC = c;
        DD = d;
        a = md5_FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
        d = md5_FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
        c = md5_FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
        b = md5_FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
        a = md5_FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
        d = md5_FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
        c = md5_FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
        b = md5_FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
        a = md5_FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
        d = md5_FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
        c = md5_FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
        b = md5_FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
        a = md5_FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
        d = md5_FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
        c = md5_FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
        b = md5_FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
        a = md5_GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
        d = md5_GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
        c = md5_GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
        b = md5_GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
        a = md5_GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
        d = md5_GG(d, a, b, c, x[k + 10], S22, 0x2441453);
        c = md5_GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
        b = md5_GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
        a = md5_GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
        d = md5_GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
        c = md5_GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
        b = md5_GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
        a = md5_GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
        d = md5_GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
        c = md5_GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
        b = md5_GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
        a = md5_HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
        d = md5_HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
        c = md5_HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
        b = md5_HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
        a = md5_HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
        d = md5_HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
        c = md5_HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
        b = md5_HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
        a = md5_HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
        d = md5_HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
        c = md5_HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
        b = md5_HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
        a = md5_HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
        d = md5_HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
        c = md5_HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
        b = md5_HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
        a = md5_II(a, b, c, d, x[k + 0], S41, 0xF4292244);
        d = md5_II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
        c = md5_II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
        b = md5_II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
        a = md5_II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
        d = md5_II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
        c = md5_II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
        b = md5_II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
        a = md5_II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
        d = md5_II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
        c = md5_II(c, d, a, b, x[k + 6], S43, 0xA3014314);
        b = md5_II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
        a = md5_II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
        d = md5_II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
        c = md5_II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
        b = md5_II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
        a = md5_AddUnsigned(a, AA);
        b = md5_AddUnsigned(b, BB);
        c = md5_AddUnsigned(c, CC);
        d = md5_AddUnsigned(d, DD);
    }
    return (md5_WordToHex(a) + md5_WordToHex(b) + md5_WordToHex(c) + md5_WordToHex(d)).toLowerCase();
}
Copy the code

Front end use

JavaScript-MD5

Single function, dedicated to processing MD5. Star count is currently 3k+, very simple to use, and both front and back ends are available.

/ / the front
<script src="js/md5.min.js"></script>
var hash = md5("value"); // "2063c1608d6e0baf80249c42e2be5804"

/ / the back end
npm install blueimp-md5

require("http").createServer(function (req, res) {
    // The md5 module exports the md5() function:
    var md5 = require("./md5"),
    // Use the following version if you installed the package with npm:
    // var md5 = require("blueimp-md5"),
        url  = require("url"),
        query = url.parse(req.url).query;
    res.writeHead(200, {"Content-Type": "text/plain"});
    // Calculate and print the MD5 hash of the url query:
    res.end(md5(query));
}).listen(8080."localhost");
console.log("Server running at http://localhost:8080/");
Copy the code

crypto-js

Powerful function, not only processing MD5, support a lot of modules, star number is 6K +, front and back end available.

NPM install crypto-js import sha256 from 'crypto-js/sha256'; import hmacSHA512 from 'crypto-js/hmac-sha512'; import Base64 from 'crypto-js/enc-base64'; const message, nonce, path, privateKey; / /... const hashDigest = sha256(nonce + message); const hmacDigest = Base64.stringify(hmacSHA512(path + hashDigest, privateKey)); // Brower manages Bower install crypto-jsCopy the code

Improved security

Add salt

If you want to improve your security, you can take the raw data one step further and “salt” it is a complex string. The longer and more complex the salt you add, the harder it is to encrypt and break. You can try adding a complex string to the raw data and then do THE MD5 encryption. This way, even if you unlock MD5, you can’t know which segment of your original data is exactly.

But even this cannot be absolute security. The salt is still a risk of leakage. For example, apple end, Android end, front end, background and so on those technical personnel are known, are likely to leak out. Put on the server is not absolutely safe, there are also means to grab.

But relative or further improve the security of encryption.

SHA

Introduction to the

The five ALGORITHMS of the SHA family, sha-1, SHA-224, SHA-256, SHA-384, and SHA-512, were designed by the NATIONAL Security Agency (NSA) and published by the National Institute of Standards and Technology (NIST). It’s a government standard in the United States. The last four are sometimes referred to together as SHA-2.

Sha-1, the Hash algorithm, a very popular cryptographic Hash function. It is widely used in many security protocols, usually used for password encryption, file verification, etc. It was once regarded as the successor of MD5 and has irreversibility. (It is exported as MD4 with MD5, so it has certain similarity)

The idea is to input plaintext of unlimited length and produce a 160-bit digest of the message (32 bits more than MD5). It also compresses the original content, printing a fixed length hash value. In some strength, it is stronger than MD5.

As early as 2005, Professor Wang Xiaoyun in China successfully proposed MD5 successful collision (different original data get the same ciphertext), and then proposed SHA1 collision, but there was no instance.

In 2017, Google shook up the world by successfully bumping SHA-1, which meant that sha-1 was no longer so secure.

The successful collision can use two different original data to get the same summary. At this time, if a malicious attacker uses this conflict to replace the security file with malicious files, and the receiver cannot identify the nature of the file through the same information summary, it may cause serious consequences.

However, sha-1 is difficult to crack, and requires a certain level of conditioning to be able to do so.

Below is a list of some Numbers, let everybody understand the crack this algorithm needs computing scale: a total of 9 trillion (i.e. five millions of power and specific 9223372036854775808) SHA1 calculation. To complete the first stage of the attack would require 6500 years of computation on a single CPU. Completing the second stage of the attack requires 110 years of single GPU computing.

Md5: It only takes a smartphone 30 seconds to hack. Sha-1 Shattered: 110GPU takes 1 year Sha-1 BruteForce: 12000000GPU takes one year.

In short, only Google’s cloud infrastructure can handle it, not just anyone. And then there is the more secure SHA2 algorithm.

So starting with version 56, released in January 2017, Chrome will treat any website protected by a SHA-1 certificate as unsafe. Firefox, which had planned to launch this feature in early 2017, phased out SHA-1 on February 24, 2017.

Front end use

crypto-js

Powerful function, not only processing MD5, support a lot of modules, star number is 6K +, front and back end available.

// Back-end NPM package management
npm install crypto-js

import sha256 from 'crypto-js/sha256';
import hmacSHA512 from 'crypto-js/hmac-sha512';
import Base64 from 'crypto-js/enc-base64';

const message, nonce, path, privateKey; // ...
const hashDigest = sha256(nonce + message);
const hmacDigest = Base64.stringify(hmacSHA512(path + hashDigest, privateKey));

// Front-end Brower management
bower install crypto-js
Copy the code

jsSHA

Focus on SHA encryption, current star number 1K +. Can handle the SHA-1, SHA-224, SHA3-224, SHA-256, SHA3-256, SHA-384, SHA3-384, SHA-512, SHA3-512, SHAKE128, and SHAKE256, and HMAC.

npm install jssha
/ / reference
jsSHA = require("jssha");
/ / use
var shaObj = new jsSHA("SHA-512"."TEXT");
shaObj.update("This is a ");
shaObj.update("test");
var hash = shaObj.getHash("HEX");
Copy the code