Home Web Front-end JS Tutorial Data encryption and decryption using JavaScript

Data encryption and decryption using JavaScript

Jun 15, 2023 pm 08:55 PM
javascript Decrypt data encryption

In the era of network information, data security has become an issue that all walks of life must pay serious attention to and pay attention to. Data encryption technology plays a vital role in the field of data security, which can effectively protect users' sensitive information and ensure that data is not accessed and stolen by unauthorized persons. This article introduces how to use JavaScript to implement data encryption and decryption to ensure data security.

1. Overview of data encryption technology

Data encryption refers to converting original data through a certain algorithm so that the converted data cannot be directly read and understood. The data can only be decrypted using a specific key, thus protecting the confidentiality and security of the data.

Common data encryption algorithms include symmetric encryption algorithms and asymmetric encryption algorithms.

Symmetric encryption algorithm refers to an algorithm that uses the same key for encryption and decryption. Common symmetric encryption algorithms include DES, 3DES, AES, etc.

Asymmetric encryption algorithm refers to an algorithm that uses different keys for encryption and decryption. Common asymmetric encryption algorithms include RSA, DSA, etc.

In order to achieve secure transmission of data, a hybrid encryption mechanism is often used in practical applications, that is, an asymmetric encryption algorithm is used to transmit a symmetric key, and then a symmetric encryption algorithm is used to encrypt the message data.

2. Use JavaScript to implement data encryption

In Web development, JavaScript is a common programming language that can run on the client, so we can implement data encryption functions through JavaScript.

In JavaScript, we can use CryptoJS to implement standard data encryption and decryption. CryptoJS is an encryption library written in pure JavaScript, which supports various encryption and hashing algorithms, including AES, DES, SHA1, SHA256, etc.

  1. Use AES algorithm to encrypt data

When using CryptoJS for AES encryption, you first need to introduce CryptoJS into the page and then use the API functions it provides to encrypt the data. and decryption.

The following code demonstrates how to use CryptoJS for AES encryption:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>

<script>
// 加密数据
function encryptByAES(message, keyStr) {

  var key = CryptoJS.enc.Utf8.parse(keyStr);

  var encryptedData = CryptoJS.AES.encrypt(message, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });

  return encryptedData.toString();
}

// 解密数据
function decryptByAES(ciphertext, keyStr) {

  var key = CryptoJS.enc.Utf8.parse(keyStr);

  var decrypt = CryptoJS.AES.decrypt(ciphertext, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });

  return decrypt.toString(CryptoJS.enc.Utf8);
}

// 测试代码
var myMessage = "Hello World!";
var myKey = "1234567890123456";

var ciphertext = encryptByAES(myMessage, myKey);
console.log("加密后的数据:" + ciphertext);

var plaintext = decryptByAES(ciphertext, myKey);
console.log("解密后的数据:" + plaintext);
</script>
Copy after login

In the above code, we use the functions provided by CryptoJS to implement AES encryption and decryption, where the mode value indicates the encryption mode and padding The value indicates the padding method.

  1. Use RSA algorithm to encrypt data

When using CryptoJS for RSA encryption, you need to generate an RSA key pair first, then use the public key to encrypt the data, and use the private key to encrypt the data. key to decrypt the data.

The following code demonstrates how to use CryptoJS for RSA encryption:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>

<script>
// 生成RSA密钥对
var keyPair = CryptoJS.lib.CipherParams.create({
  ciphertext: CryptoJS.enc.Hex.parse("<public key>")
});

// 加密数据
function encryptByRSA(message, publicKey) {

  var key = CryptoJS.lib.CipherParams.create({
    ciphertext: CryptoJS.enc.Hex.parse(publicKey)
  });

  var encryptedData = CryptoJS.AES.encrypt(message, key, {
    mode: CryptoJS.mode.ECB
  });

  return encryptedData.toString();
}

// 解密数据
function decryptByRSA(ciphertext, privateKey) {

  var key = CryptoJS.lib.CipherParams.create({
    ciphertext: CryptoJS.enc.Hex.parse(privateKey)
  });

  var decrypt = CryptoJS.AES.decrypt(ciphertext, key, {
    mode: CryptoJS.mode.ECB
  });

  return decrypt.toString(CryptoJS.enc.Utf8);
}

// 测试代码
var myMessage = "Hello World!";
var myPublicKey = "<public key>";
var myPrivateKey = "<private key>";

var ciphertext = encryptByRSA(myMessage, myPublicKey);
console.log("加密后的数据:" + ciphertext);

var plaintext = decryptByRSA(ciphertext, myPrivateKey);
console.log("解密后的数据:" + plaintext);
</script>
Copy after login

In the above code, we first generated an RSA key pair, and used the public key to encrypt the data and the private key to Decrypt data.

3. Conclusion

This article introduces how to use JavaScript to implement data encryption and decryption, protect users' sensitive information through encryption, and ensure data security. We can use CryptoJS library to implement different encryption and decryption algorithms such as AES, RSA, etc. In order to protect the security of data, we should widely use encryption technology in web applications to protect user privacy and data security.

The above is the detailed content of Data encryption and decryption using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Revealing the causes of HTTP status code 460 Revealing the causes of HTTP status code 460 Feb 19, 2024 pm 08:30 PM

Decrypting HTTP status code 460: Why does this error occur? Introduction: In daily network use, we often encounter various error prompts, including HTTP status codes. These status codes are a mechanism defined by the HTTP protocol to indicate the processing of a request. Among these status codes, there is a relatively rare error code, namely 460. This article will delve into this error code and explain why this error occurs. Definition of HTTP status code 460: First, we need to understand the basics of HTTP status code

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to set up word decryption How to set up word decryption Mar 20, 2024 pm 04:36 PM

In today's work environment, everyone's awareness of confidentiality is getting stronger and stronger, and encryption operations are often performed to protect files when using software. Especially for key documents, the awareness of confidentiality should be increased, and the security of documents should be given top priority at all times. So I don’t know how well everyone understands word decryption. How to operate it specifically? Today we will actually show you the process of word decryption through the explanation below. Friends who need to learn word decryption knowledge should not miss today's course. A decryption operation is first required to protect the file, which means that the file is processed as a protective document. After doing this to a file, a prompt pops up when you open the file again. The way to decrypt the file is to enter the password, so you can directly

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Detailed introduction to the encryption and decryption methods of Vim text in CentOS Detailed introduction to the encryption and decryption methods of Vim text in CentOS Dec 31, 2023 pm 02:49 PM

CentOS uses vim/vi to encrypt and decrypt files 1. Use vim/vi to encrypt: Advantages: After encryption, if you don’t know the password, you cannot see the plain text, including root users; Disadvantages: It is obvious that others know the encryption , it is easy for others to destroy encrypted files, including content destruction and deletion; I believe everyone is familiar with the vi editor. There is a command in vi to encrypt files. For example: 1) First, in the root master Create an experimental file text.txt under the directory /root/: [root@www~]#vim/vitext.txt2) Enter the editing mode, press ESC after entering the content, and then enter: X (note the capital X), Enter; 3)

See all articles