Preface
With the increasing importance of information and data security, how to ensure the security of information data during transmission has become a key focus of developers. Front-end encryption usually refers to various encryption operations on various transmitted data in the browser. However, front-end encryption is more used to simply obfuscate the transmitted data, in order to ensure that the data is not easily tampered with and read during transmission. There are many encryption methods for us to choose, and we need to choose the encryption solution that suits us according to the actual scenario during the development process. Then, this article will introduce the commonly used encryption methods in front-end development in combination with application scenarios.
1. Base64 encoding
Strictly speaking, Base64 is not an encryption method, it is an encoding method. Base64 is a method of representing binary data based on 64 printable characters. Base64 is a character set that includes the lowercase letter a-z, capital letter A-Z, number 0-9, symbol "+","/" in total. Any symbol can be converted into characters in this character set. This conversion process is called base64 encoding.
Base64 encoding is a process from binary to character and can be used to pass longer identification information in an HTTP environment. Base64 encoding is unreadable and needs to be decoded before reading. Base64 is widely used in various fields of computers due to the above advantages. Base64 encoding can be used in JavaScript. The btoa function can convert binary data into Base64-encoded strings, and can also decode the encoded strings using the built-in function atob.
// Encodingconst base64Str = ('Hello World!'); (base64Str); // SGVsbG8gV29ybGQh // Decodeconst str = (base64Str); (str); // Hello World!
Of course, we can also use the base64 plugin.
pnpm add js-base64
How to use:
import { Base64 } from 'js-base64'; // Encoding const encode = ('Hello World!');? (encode); // Decode const decode = (encode);? (decode);
2. Hash algorithm
Hash algorithm (Hash Algorithm), also known as hash algorithm and hash algorithm, is a method to create small numbers "fingerprints" from any file. Like fingerprints, the hash algorithm is a sign that uses shorter information to ensure the uniqueness of the file. This sign is related to every byte of the file, and it is difficult to find the reverse pattern. Therefore, when the original file changes, its flag value will also change, thus telling the file user that the current file is no longer the file you need.
The Hash algorithm can map binary plaintexts of any length to shorter binary strings, and it is difficult for different plaintexts to map to the same Hash value.
Hash Algorithm is an algorithm that maps messages of any length into a fixed-length Message Digest. The hash algorithm can convert input data of any length into a fixed-length output, commonly known as a hash value or a digest, and meets the following characteristics:
(1) Determinism: For the same input data, the hash algorithm will generate the same hash value.
(2) Irreverability: The original input data cannot be derived from the hash value.
(3) Uniqueness: The hash values generated by different input data should be as different as possible.
(4) Hashing: Even if the input data only changes slightly, the generated hash value should be very different.
Therefore, hash algorithms are widely used in cryptography, data integrity verification, digital signature, data sharding and other fields.
(1) Digital signature: Store the hash value of the original data with the signature to verify the integrity and correctness of the signature.
(2) Password storage: Store the hash value of the user password in the database to avoid directly storing plaintext passwords and improve security.
(3) Data integrity verification: Compare the hash value of the original data with the hash value during transmission to determine whether the data has been tampered with.
(4) Data sharding: Divide the original data into several blocks, and calculate the hash value for each block separately to quickly detect the correctness of the data block.
The more common hashing algorithms include MD5, SHA-1, SHA-256, and SHA-512.
Install crypto-js:
pnpm add crypto-js
How to use:
import CryptoJS from "crypto-js"; // MD5 const hash = CryptoJS.MD5('Message'); // SHA-1 const hash = CryptoJS.SHA1('Message'); // SHA-256 const hash = CryptoJS.SHA256('Message'); // SHA-512 const hash = CryptoJS.SHA512('Message');
3. Symmetric encryption (AES/DES)
DES is the full name Data Encryption Standard, which is a data encryption standard, which is an algorithm that uses key encryption.
The full name of AES is Advanced Encryption Standard. The AES algorithm uses a packet cipher system, grouping plain texts according to a fixed size, and then encrypting each packet. During the encryption process, the AES algorithm adopts multiple rounds of encryption, and each round of encryption includes four operations: SubBytes, ShiftRows, MixColumns and AddRoundKey. Through these operations, the AES algorithm can encrypt data more securely and efficiently.
The AES and DES encryption algorithms are a symmetric encryption method. The so-called symmetric encryption means that the secret key (a set of strings) used for encryption and decryption is one. The encryption and decryption side must use the same key before encryption and decryption can be performed.
The most commonly used modes for AES encryption are ECB mode and CBC mode. Of course, there are many other modes, all of which belong to AES encryption. The difference between ECB mode and CBC mode is that ECB does not require iv offset, while CBC requires it.
ECB is a basic encryption method. The ciphertext is divided into blocks of equal group lengths (not enough to be filled), and then encrypted one by one, and output one by one to form the ciphertext. CBC is a loop mode, the ciphertext of the previous packet and the plaintext of the current packet are encrypted after being operated. The purpose of this is to increase the difficulty of cracking.
The parameter Mode is the working method of DES/AES.
The parameter padding is in the padding mode. If the encrypted ciphertext length cannot reach the specified integer multiple (8 bytes, 16 bytes), fill the corresponding characters, and the assignment of padding is fixed to .Pkcs7.
import CryptoJS from "crypto-js"; //The keyconst secretKey = .("12345678ABCDEFGH"); //16 bit// iv offsetconst iv = .("ABCDEFGH12345678"); // The parameters that require encryption, the data type is bytesconst secretMessage = "Hello World!"; // Encryptionconst encrypt = (secretMessage, secretKey, { iv: iv, mode: ,? padding: .Pkcs7? }).tostring(); (encrypt); //Decryptionconst decrypt = (encrypt, secretKey, { iv: iv, mode: , padding: .Pkcs7 }).toString(.Utf8); (decrypt);
IV. Asymmetric encryption (RSA)
The secret keys for asymmetric encryption, encryption and decryption are not the same secret key. Here, two keys, one public key and one private key, are required to send the public key to the client. The sending end encrypts the data with a public key and then sends it to the receiving end, which uses a private key to decrypt the data. Since the private key is only stored on the receiving end, even if the data is intercepted, it cannot be decrypted.
The public key and the private key are a pair. Since encryption and decryption use two different keys, this algorithm is called an asymmetric encryption algorithm. When using it, you will use public keys to encrypt and use private keys to decrypt. Public keys can be made public, while private keys can be kept by themselves. This public and private key is actually a set of numbers, and its binary bit length can be 1024 or 2048 bits. The longer the length, the greater the encryption strength, which is relatively safer. So far, this encryption algorithm has been widely used.
Common asymmetric encryption algorithms include RSA, DSA, etc. In this article, we will introduce an RSA encryption, which is also the most common encryption solution.
jsencrypt is a js library based on RSA encryption and decryption.
npm install jsencrypt? import JSEncrypt from 'jsencrypt'? // RSA encryption// Create an encrypted object instanceconst encryptor = new JSEncrypt();? //Be careful not to have spaces when copying the public key generated by SSLconst pubKey = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1QQRl0HlrVv6kGqhgonD6A9SU6ZJpnEN+Q0blT/ue6Ndt97WRfxtSAs0QoquTreaDtfC4RRX4o+CU6BTuHLUm+eSvxZS9TzbwoYZq7ObbQAZAY+SYDgAA5PHf1wNN20dGMFFgVS/y0ZWvv1UNa2laEz0I8Vmr5ZlzIn88GkmSiQIDAQAB-----END PUBLIC KEY-----'; //Set the public key(pubKey); // Encrypt contentconst encrypted = ('The content to be encrypted')? // RSA decryption//Create a decrypted object instanceconst decrypt = new JSEncrypt(); //The secret key generated by SSL beforeconst priKey ?= '-----BEGIN RSA PRIVATE KEY-----MIICXAIBAAKBgQC1QQRl0HlrVv6kGqhgonD6A9SU6ZJpnEN+Q0blT/ue6Ndt97WRfxtSAs0QoquTreaDtfC4RRX4o+CU6BTuHLUm+eSvxZS9TzbwoYZq7ObbQAZAY+SYDgAA5PHf1wNN20dGMFFgVS/y0ZWvv1UNa2laEz0I8Vmr5ZlzIn88GkmSiQIDAQABAoGBAKYDKP4AFlXkVlMEP5hS8FtuSrUhwgKNJ5xsDnFV8sc3yKlmKp1a6DETc7N66t/Wdb3JVPPSAy+7GaYJc7IsBRZgVqhrjiYiTO3ZvJv3nwAT5snCoZrDqlFzNhR8zvUiyAfGD1pExBKLZKNH826dpfoKD2fYlBVOjz6i6dTKBvCJAkEA/GtL6q1JgGhGLOUenFveqOHJKUydBAk/3jLZksQqIaVxoB+jRQNOZjeSO9er0fxgI2kh0NnfXEvH+v326WxjBwJBALfTRar040v71GJq1m8eFxADIiPDNh5JD2yb71FtYzH9J5/d8SUHI/CUFoROOhxr3DpagmrnTn28H0088vubKe8CQDKMOhOwx/tS5lqvN0YQj7I6JNKEaR0ZzRRuEmv1pIpAW1S5gTScyOJnVn1tXxcZ9xagQwlT2ArfkhiNKxjrf5kCQAwBSDN5+r4jnCMxRv/Kv0bUbY5YWVhw/QjixiZTNn81QTk3jWAVr0su4KmTUkg44xEMiCfjI0Ui3Ah3SocUAxECQAmHCjy8WPjhJN8y0MXSX05OyPTtysrdFzm1pwZNm/tWnhW7GvYQpvE/iAcNrNNb5k17fCImJLH5gbdvJJmCWRk=-----END RSA PRIVATE KEY----'; //Set the key(priKey); //The content encrypted with the public key before decryptingconst uncrypted = (encrypted)
RSA encryption and decryption can be used to encrypt the password with the public key when the user registers or logs in, and then pass it to the background. The background uses the private key to decrypt the encrypted content, and then performs password verification or save to the database.
-
Symmetric encryption
- Shared by both partiesKey (code)(secret key,あこう), encrypted transmission is based on key security rather than algorithm security.
- Encryption and decryption use the same algorithm.
- The difficulty of cracking mainly depends on the complexity of the key.
-
Asymmetric encryption(Public key encryption)
- Use key pairs (public key publickey, private key privatekey).
- No deliveryPrivate key。
- Encryption and decryption may use a variety of rules and algorithms.
- Security does not depend on the confidentiality of the algorithm or the way to pass the key.
Bitcoin and Ethereum crypto
Symmetric and asymmetric encryption are used extensively, as well as related technologies.
- Encryption, decryption (as mentioned above)
- Hash, Message digest (hash, SHA256, RIPEMD160)
- Checksum (checksum)
- Coding (Base64, Base58)
^ Hash: Abstract: Convert data of uncertain lengths to calculate the result that is not easy to conflict with fixed lengths.
^ Checksum: Checksum, perform redundant checksum integrity checks on the data.
^ Encoding: converts binary data into ordinary characters, making it easier to read and discern.
5. Add salt
Adding salt means introducing a randomly generated string in the hashing process, called salt, and combining it with the password before hashing. This salt value is individually associated with each user's password and stored in the database. Adding salt can increase the complexity of password hashing and improve password security. Even if two users use the same password, the hashing results will be different due to different salt values. This way, even if the hacker gets the hash value, it is difficult to find the original password.
The salt value is actually a random string we add (this value can be a fixed value, a random number, uuid...). The same string will be encrypted into a completely different string every time.
The following two points should be paid attention to when using salt encryption:
(1) Short Slat
If the salt value is too short, an attacker can pre-create a lookup table for all possible salt values. For example, if the salt value has only three ASCII characters, then there are only 95x95x95=857,375 possibilities, increasing the possibility of being attacked. Also, do not use predictable salt values, such as usernames, because usernames for a certain system are unique and are often used for other services.
(2) Salt Reuse
In project development, sometimes you will encounter the salt value being written in the program or only the first time is randomly generated, and it will be reused later. This method of adding salt does not work. Taking the login password as an example, if two users have the same password, they will have the same hash value, and the attacker can use the reverse table lookup method to perform a dictionary attack on each hash value, making the hash value easier to crack.
So the correct way to add salt is as follows:
(1) The salt value should be generated using an encrypted secure pseudo-Random Number Generator (CSPRNG), such as the rand() function in C language, so the random numbers generated are highly random and completely unpredictable;
(2) The salt value is mixed into the target text and used standard encryption functions for encryption together;
(3) The salt value should be long enough (experience shows that the salt value should be at least as long as the output of the hash function) and never be repeated;
(4) The salt value is best provided by the server and used by the front-end.
Let’s use SHA-256 as an example to implement salt-added encryption.
Install js-sha256
pnpm install js-sha256
How to use:
import { sha256 } from 'js-sha256'; const generateSalt = () => { const randomBytes = new Uint8Array(16); (randomBytes); return (randomBytes, (byte) => (16).padStart(2, '0') ).join(''); }; // Salt valueconst salt = generateSalt(); // If a passwordconst password = 'admin123456'; // Combine salt value and passwordconst saltedPassword = salt + password; // Hash calculationconst hash = sha256(saltedPassword); (hash);
6. Web Cryptography API
Web Cryptography API (WebCrypto API) is a encryption standard built in modern browsers that can be used for more secure cryptography operations. This API allows us to implement security functions such as encryption, decryption, and digital signature in web applications without relying on third-party libraries or plug-ins.
The WebCrypto API is the standard of W3C, which provides a set of low-level interfaces for performing various cryptographic operations. These interfaces include:
Generate and manage keys: such as RSA, AES, HMAC, etc.
Encryption and decryption: Supports multiple symmetric and asymmetric encryption algorithms.
Abstract and hash: such as SHA-1, SHA-256 and MD5.
Digital signature and verification: used to ensure the integrity and authenticity of the data.
Random number generation: used to create safe random numbers.
It is the SubtleCrypto interface. The latest mainstream browsers basically support this interface and are consistent, except for safari.
// fix safari crypto namespace if ( && ! && ) { = ;? } /** * Detect Web Cryptography API * @return {Boolean} true, if success? */ function isWebCryptoAPISupported() { return 'crypto' in window && 'subtle' in ; }
getRandomValues Synchronous method to get random numbers, which is a pseudo-random number generator (PRNG) due to performance requirements. Browsers also meet cryptographic usage requirements by adding system-level seeds to increase entropy (a measure of uncertainty).
const size = 10; const array = new Uint8Array(size); (array); // print values to console for (let i=0; i!==; ++i) { ? (array[i]); }
SubtleCrypto interface:
encrypt, decrypt (encryption method), algorithm supports: RSA-OAEP, AES-CTR, AES-CBC, AES-GCM, AES-CFB.
Sign, verify (signature verification and issuance method), algorithm supports: RSASSA-PKCS1-v1.5, RSA-PSS, ECDSA, AES-CMAC, HMAC.
Digest (Abstract Method), algorithm supports: SHA-1, SHA-256, SHA-384, SHA-512.
GenerateKey: Generates symmetric/asymmetric keys (CryptoKey object).
DeriveKey and deriveBits: Generate a key from the original key or from a password/password generated by a pseudo-random function.
WrapKey and unwrapKey: Methods used to protect keys stored in unsafe channels or untrusted environments.
ImportKey and exportKey: Import keys, convert and export different formats.
The above methods will return Promise.
Here is a simple encryption using the WebCrypto API, the code is as follows:
// Generate public and private keysconst keyPair = await ( { name: "RSA-OAEP", //Use RSA-OAEP algorithm modulusLength: 2048, // The key length is 2048 bits publicExponent: new Uint8Array([1, 0, 1]), // Public index is 65537 hash: "SHA-256" // The hashing algorithm is SHA-256 }, true, // Generate exportable key pairs ["encrypt", "decrypt"] // Can be used for encryption and decryption operations); (function(result) { // Process the generated key pair (); // Print the public key (); // Print private key}).catch(function(error) { // Handle errors (error); }); // Encryptionasync function encryptByRSA(message, publicKey) { // Encode the message into Uint8Array format const encodedMessage = new TextEncoder().encode(message); // Encrypt messages using the encrypt() method of the Web Crypto API const encrypted = await ( { name: "RSA-OAEP" // The encryption algorithm is RSA-OAEP }, publicKey, // Encrypt with incoming public key encodedMessage // Message to be encrypted ); // Convert encrypted data into Base64 encoded string return ((...new Uint8Array(encrypted))); } // Decrypt the ciphertext using RSA private keyasync function decryptByRSA(ciphertext, privateKey) { // Decode the Base64 encoded ciphertext into Uint8Array format const decodedCiphertext = ( atob(ciphertext), c => (0) ); // Decrypt the ciphertext using the decrypt() method of the Web Crypto API const decrypted = await ( { name: "RSA-OAEP" // The decryption algorithm is RSA-OAEP }, privateKey, // Use the incoming private key to decrypt decodedCiphertext // The cipher text to be decrypted ); // Convert the decrypted data into a string return new TextDecoder().decode(decrypted); }
7. Summary
The above encryption methods provide basic front-end encryption methods. Most of the time, in order to ensure the security of the data, some sensitive data (such as mobile phone number, ID number, bank card number, etc.) will be sent to the server, and then encrypted on the server. Front-end encryption does not ensure the security of data, because the client is exposed to the user, and any obfuscation or encryption measures may be bypassed (front-end encryption prevents gentlemen from letting go of villains). The correct way is to ensure that the data transmission is encrypted through HTTPS and other protocols, and perform necessary security checksum encryption processing on the server.
This is the end of this article about several commonly used methods of front-end encryption. For more related front-end encryption content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!