Data encryption is a technology with a long history, which means that plaintext is transformed into ciphertext through encryption algorithm and encryption key, while decryption is to recover ciphertext into plaintext through decryption algorithm and decryption key. Its core is cryptography. Data encryption is still the most reliable way for computer system to protect information. It uses password technology to encrypt information and realize information concealment, so as to protect the security of information.
This article will introduce how to encrypt the data in a mixed way, that is, using symmetric encryption algorithm and asymmetric encryption algorithm to encrypt data, so as to further ensure the security of data. After reading this article, you will learn the following:
- What are the advantages and disadvantages of symmetric encryption, symmetric encryption process and symmetric encryption algorithm;
- What is asymmetric encryption, the process of asymmetric encryption, the advantages and disadvantages of asymmetric encryption and the use of RSA asymmetric encryption algorithm;
- What is hybrid encryption, hybrid encryption process and how to achieve hybrid encryption.
In the lastBrother Bao has something to sayIn the link, a Bao Ge will also briefly introduce what is the message digest algorithm and what is the MD5 algorithm, as well as their uses and defects. OK, now let’s get to the point. In order to let the partners who have just come into contact with hybrid encryption better understand and master the hybrid encryption, a Bao Ge will take the“Time machine”Take you to a publishing night
That night, our team’s partners were waiting for the server-side data upgrade, in order to let everyone“Forget”This long upgrade process, a Bao Ge immediately organized a technology sharing meeting on hybrid encryption. In a Bao Ge“Coercion and inducement”After that, the team’s partners arrived quickly. After that, Bao opened the sharing meeting with the following dialogue:
A few minutes later, the younger brother finished speaking, and the basic key points were answered, but some contents were omitted. In order to let the partners better understand symmetric encryption, Bao Ge has reorganized the content of his statement. Let’s have a look at symmetric encryption.
1、 Symmetric encryption
1.1 what is symmetric encryption
Symmetric key algorithm, also known as symmetric encryption, private key encryption and shared key encryption, is a kind of encryption algorithm in cryptography.This kind of algorithm uses the same key in encryption and decryption, or uses two keys that can be easily calculated from each other.
1.2 advantages of symmetric encryption
The algorithm is open, the amount of calculation is small, the encryption speed is fast, and the encryption efficiency is high, which is suitable for the scenario of large amount of data encryption.For example, in HLS (HTTP live streaming) common encryption scenario, AES-128 symmetric encryption algorithm is generally used to encrypt TS slices to ensure the security of multimedia resources.
1.3 symmetric encryption process
The sender uses the key to encrypt the plaintext data into ciphertext, and then sends it out. After receiving the ciphertext, the receiver uses the same key to decrypt the ciphertext into plaintext to read.
1.4 examples of symmetric encryption
The common symmetric encryption algorithms are AES, chachacha20, 3DES, salsa20, DES, blowfish, idea, RC5, RC6, camellia. Here we take the common AES algorithm as an example to introduce the process of AES (Advanced Encryption Standard) symmetric encryption and decryption.
Next, Bao Ge will use crypto JS library to introduce the encryption and decryption of AES algorithm. The library providesCryptoJS.AES.encrypt()
Method is used to implement AES encryption, and the corresponding method of AES decryption isCryptoJS.AES.decrypt()
。
Based on the above two methods, apogee further encapsulates theaesEncrypt()
andaesDecrypt()
These two methods are respectively used for AES encryption and decryption, and their specific implementation is as follows:
1.4.1 AES encryption method
//AES encryption
function aesEncrypt(content) {
let text = CryptoJS.enc.Utf8.parse(JSON.stringify(content));
let encrypted = CryptoJS.AES.encrypt(text, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
}
1.4.2 AES decryption method
//AES decryption
function aesDecrypt(content) {
let decrypt = CryptoJS.AES.decrypt(content, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return decrypt.toString(CryptoJS.enc.Utf8);
}
1.4.3 AES encryption and decryption example
In the above example, we create three textareas on the page to store plaintext, encrypted ciphertext and decrypted plaintext. When the user clicksencryptionButton, AES encryption will be applied to the plaintext input by the user. After encryption, the ciphertext will be displayed in the textarea corresponding to the ciphertext. When the user clicksdecryptButton, AES will be used to decrypt the ciphertext. After decryption, the decrypted plaintext will be displayed in the corresponding textarea.
The complete code for the above example is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
< title > AES symmetric encryption and decryption example
<style>
.block {
flex: 1;
}
</style>
</head>
<body>
<h3>Bao Ge: AES symmetric encryption and decryption example (CBC mode)</h3>
<div style="display: flex;">
<div class="block">
<p>① Plaintext encryption = > < button onclick = "encrypt()" > encryption < / button ></p>
<textarea id="plaintext" rows="5" cols="15"></textarea>
</div>
<div class="block">
<p>② Ciphertext decryption = > < button onclick = "decrypt()" > decryption < / button ></p>
<textarea id="ciphertext" rows="5" cols="15"></textarea>
</div>
<div class="block">
<p>③ Decrypted plaintext</p>
<textarea id="decryptedCiphertext" rows="5" cols="15"></textarea>
</div>
</div>
<! -- introducing CDN Crypto.js AES encryption -- >
<script></script>
<script></script>
<script></script>
<script></script>
<script></script>
<script></script>
<! -- introducing CDN Crypto.js End -- >
<script>
const key = CryptoJS.enc.Utf8 . parse ("0123456789abcdef"); // key
const iv = CryptoJS.enc.Utf8 . parse ("abcdef0123456789"); // initial vector
const plaintextEle = document.querySelector("#plaintext");
const ciphertextEle = document.querySelector("#ciphertext");
const decryptedCiphertextEle = document.querySelector(
"#decryptedCiphertext"
);
function encrypt() {
let plaintext = plaintextEle.value;
ciphertextEle.value = aesEncrypt(plaintext);
}
function decrypt() {
let ciphertext = ciphertextEle.value;
decryptedCiphertextEle.value = aesDecrypt(ciphertext).replace(/\"/g,'');
}
//AES encryption
function aesEncrypt(content) {
let text = CryptoJS.enc.Utf8.parse(JSON.stringify(content));
let encrypted = CryptoJS.AES.encrypt(text, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
}
//AES decryption
function aesDecrypt(content) {
let decrypt = CryptoJS.AES.decrypt(content, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return decrypt.toString(CryptoJS.enc.Utf8);
}
</script>
</body>
</html>
In the above example, we use AES symmetric encryption algorithm to encrypt “I am a Bao Ge” plaintext, so as to achieve information hiding.
So can symmetric encryption algorithm solve the problem in front of us? The answer is no, because symmetric encryption has some disadvantages.
Disadvantages of 1.5 symmetric encryption
By using symmetric encryption algorithm, we have encrypted plaintext into ciphertext. Although this solves the security of data, it also brings about another new problem. Because the symmetric encryption algorithm uses the same key for encryption and decryption, the security of symmetric encryption depends not only on the strength of the encryption algorithm itself, but also on whether the key is transmitted or kept safely.
In addition, for the actual application scenario, in order to avoid a single key being broken, resulting in all encrypted data being cracked, for different data, we generally use different keys for encryption, which improves the security, but also increases the difficulty of key management.
Because of the above problems, symmetric encryption is not a good solution. In order to find a better solution, a Bao Ge started another round of new dialogue.
2、 Asymmetric encryption
2.1 what is asymmetric encryption
Asymmetric encryption algorithm needs two keys: public key and private key.The public key and the private key are a pair. If the public key is used to encrypt the data, only the corresponding private key can be decrypted.Because encryption and decryption use two different keys, this algorithm is called asymmetric encryption algorithm.
2.2 advantages of asymmetric encryption
The security is higher. The public key is public, and the private key is kept by oneself. It is unnecessary to provide the private key to others.
2.3 process of asymmetric encryption
2.4 examples of using asymmetric encryption
The common asymmetric encryption algorithms are RSA, ElGamal, knapsack algorithm, Rabin, D-H, ECC (elliptic curve encryption algorithm). Here we take the common RSA algorithm as an example to introduce the process of RSA asymmetric encryption and decryption.
RSA was proposed by Ron Rivest, ADI Shamir and Leonard Adleman in 1977. All three of them worked at MIT. RSA is made up of the first letters of their surnames.
Next, a Bao Ge will usejsencryptThis library introduces the encryption and decryption of RSA algorithmencrypt()
Method is used to implement RSA encryption, and the corresponding method of RSA decryption isdecrypt()
。
2.4.1 creating public and private keys
usejsencryptBefore this library, we need to master the public key and private key. Next, Bao Ge takes MacOS system as an example to introduce how to generate public and private keys.
First, we will generate the private key and enter the following command on the command line:
$ openssl genrsa -out rsa_1024_priv.pem 1024
After the command runs successfully, arsa_1024_priv.pemThe contents of the document are as follows:
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDocWYwnJ4DYur0BjxFjJkLv4QRJpTJnwjiwxkuJZe1HTIIuLbu
/yHyHLhc2MAHKL0Ob+8tcKXKsL1oxs467+q0jA+glOUtBXFcUnutWBbnf9qIDkKP
...
bKkRJNJ2PpfWA45Vdq6u+izrn9e2TabKjWIfTfT/ZQ==
-----END RSA PRIVATE KEY-----
Then we will generate the public key, and also enter the following command on the command line:
$ openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem
After the command runs successfully, arsa_1024_pub.pemThe contents of the document are as follows:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDocWYwnJ4DYur0BjxFjJkLv4QR
JpTJnwjiwxkuJZe1HTIIuLbu/yHyHLhc2MAHKL0Ob+8tcKXKsL1oxs467+q0jA+g
lOUtBXFcUnutWBbnf9qIDkKP2uoDdZ//LUeW7jibVrVJbXU2hxB8bQpBkltZf/xs
cyhRIeiXxs13vlSHVwIDAQAB
-----END PUBLIC KEY-----
2.4.2 creating RSA encryptor and decryptor
After creating the public private key, we can further create the RSA encryptor and decryptor. The specific code is as follows:
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDocWYwnJ4DYur0BjxFjJkLv4QR
...
cyhRIeiXxs13vlSHVwIDAQAB
-----END PUBLIC KEY-----`;
const PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDocWYwnJ4DYur0BjxFjJkLv4QRJpTJnwjiwxkuJZe1HTIIuLbu
...
bKkRJNJ2PpfWA45Vdq6u+izrn9e2TabKjWIfTfT/ZQ==
-----END RSA PRIVATE KEY-----`;
Const encryptor = new jsencrypt(); // RSA encryptor
encryptor.setPublicKey(PUBLIC_KEY);
Const decryptor = new jsencrypt(); // RSA decryptor
decryptor.setPrivateKey(PRIVATE_KEY);
2.4.3 RSA encryption and decryption example
In the above example, we create three textareas on the page to store plaintext, encrypted ciphertext and decrypted plaintext. When the user clicksencryptionButton, the plaintext input by the user will be encrypted by RSA. After encryption, the ciphertext will be displayed in the textarea corresponding to the ciphertext. When the user clicksdecryptButton, the ciphertext will be decrypted by RSA. After decryption, the decrypted plaintext will be displayed in the corresponding textarea.
The complete code for the above example is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
< title > RSA symmetric encryption and decryption examples
<style>
.block {
flex: 1;
}
</style>
</head>
<body>
<h3>Bao Ge: RSA symmetric encryption and decryption example</h3>
<div style="display: flex;">
<div class="block">
<p>① Plaintext encryption = > < button onclick = "encrypt()" > encryption < / button ></p>
<textarea id="plaintext" rows="5" cols="15"></textarea>
</div>
<div class="block">
<p>② Ciphertext decryption = > < button onclick = "decrypt()" > decryption < / button ></p>
<textarea id="ciphertext" rows="5" cols="15"></textarea>
</div>
<div class="block">
<p>③ Decrypted plaintext</p>
<textarea id="decryptedCiphertext" rows="5" cols="15"></textarea>
</div>
</div>
<script></script>
<script>
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDocWYwnJ4DYur0BjxFjJkLv4QR
JpTJnwjiwxkuJZe1HTIIuLbu/yHyHLhc2MAHKL0Ob+8tcKXKsL1oxs467+q0jA+g
lOUtBXFcUnutWBbnf9qIDkKP2uoDdZ//LUeW7jibVrVJbXU2hxB8bQpBkltZf/xs
cyhRIeiXxs13vlSHVwIDAQAB
-----END PUBLIC KEY-----`;
const PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDocWYwnJ4DYur0BjxFjJkLv4QRJpTJnwjiwxkuJZe1HTIIuLbu
/yHyHLhc2MAHKL0Ob+8tcKXKsL1oxs467+q0jA+glOUtBXFcUnutWBbnf9qIDkKP
2uoDdZ//LUeW7jibVrVJbXU2hxB8bQpBkltZf/xscyhRIeiXxs13vlSHVwIDAQAB
AoGAKOarYKpuc5IYXdArEuHmnFaa2pm7XK8LVTuXVrNuuoPkpfw61Fs4ke3T0yKg
x6G3gq7Xm1tTEROAgMtaxqwo1D5n1H0nkyDFggLB0K9Ws0frp7HENtSQwdNSry1A
iD8TLxkhoWo7BS0VViLT1gKOfnw4YeMJP+CcOQ+DQjCsUMECQQD0Nc0vKBTlK6GT
28gcIMVoQy2KicjiH222A9/TLCNAQ9DEeZDYEptuTfrlbggfWdgQ3nc6CyvGf6c5
6uBPi/+5AkEA86oqqZPi7ekkUVHx0VSkp0mTlD1tAPhDE8cLX8vyImGExS+tTznz
ROyzm3T1M1PisdQIU8Wd5rqvHP6dB0enjwJAauhKpMQ1MYYCPApQ9g9anCQcgbOD
34nGq5HSoE2IOQ/3Cqv1PsIWjRlSJrIemCrqrafWJfDR/xnPCUnLXMd68QJAPNwG
1d4zMvslcA5ImOFMUuBEtST2geSAVINFqwK0krPKxrmWzxAJW/DHF5AJ4m0UVRhB
kDLusn90V4iczgGurwJAZUz6w01OeoLhsOuWNvkbTq+IV0NQ5GAEGA721Ck5zp86
bKkRJNJ2PpfWA45Vdq6u+izrn9e2TabKjWIfTfT/ZQ==
-----END RSA PRIVATE KEY-----`;
Const encryptor = new jsencrypt(); // RSA encryptor
encryptor.setPublicKey(PUBLIC_KEY);
Const decryptor = new jsencrypt(); // RSA decryptor
decryptor.setPrivateKey(PRIVATE_KEY);
const plaintextEle = document.querySelector("#plaintext");
const ciphertextEle = document.querySelector("#ciphertext");
const decryptedCiphertextEle = document.querySelector(
"#decryptedCiphertext"
);
function encrypt() {
let plaintext = plaintextEle.value;
ciphertextEle.value = encryptor.encrypt(plaintext);
}
function decrypt() {
let ciphertext = ciphertextEle.value;
decryptedCiphertextEle.value = decryptor.decrypt(ciphertext);
}
</script>
</body>
</html>
In the above example, we use RSA asymmetric encryption algorithm to encrypt “I am a Bao Ge” plaintext, so as to achieve information hiding.
Can asymmetric encryption algorithm solve the problem in front of us? The answer is no, because asymmetric encryption also has some disadvantages.
Disadvantages of 2.5 asymmetric encryption
Asymmetric encryption algorithm takes a long time to encrypt and decrypt, which is only suitable for a small amount of data encryption. Because we want to provide a general solution, that is to consider a small amount of data and a large amount of data at the same time, so asymmetric encryption is not a good solution. In order to solve the problem again, Bao opened a new round of dialogue.
3、 Hybrid encryption
3.1 what is hybrid encryption
Hybrid encryption is a combinationSymmetric encryptionandAsymmetric encryptionAn encryption method with respective advantages. The concrete realization idea is to use it firstSymmetric encryption algorithmThe data is encrypted, and then the asymmetric encryption algorithm is used to encrypt the dataSymmetric encryption keyAfter asymmetric encryption, the encrypted key and encrypted data are sent to the receiver.
In order to let the partners more intuitive understanding of the above process, a Bao Ge spent some thought to draw a graph to further explain the process of mixed encryption. Let’s take a look at the picture.
3.2 mixed encryption process
Implementation of 3.3 hybrid encryption
After learning about the “mixed encryption data transmission process”, a Bao Ge and his partners together to achieve the above-mentioned mixed encryption process. Here we will develop based on the examples of symmetric encryption and asymmetric encryption described above, that is, the following examples will directly use the public and private keys used in the previous asymmetric encryption examples.
3.3.1 create function to generate random AES key
function getRandomAESKey() {
return (
Math.random().toString(36).substring(2, 10) +
Math.random().toString(36).substring(2, 10)
);
}
3.3.2 create AES encryption and decryption functions
//AES encryption
function aesEncrypt(key, iv, content) {
let text = CryptoJS.enc.Utf8.parse(JSON.stringify(content));
let encrypted = CryptoJS.AES.encrypt(text, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
}
//AES decryption
function aesDecrypt(key, iv, content) {
let decrypt = CryptoJS.AES.decrypt(content, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return decrypt.toString(CryptoJS.enc.Utf8);
}
3.3.3 creating RSA encryptor and decryptor
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDocWYwnJ4DYur0BjxFjJkLv4QR
...
cyhRIeiXxs13vlSHVwIDAQAB
-----END PUBLIC KEY-----`;
const PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDocWYwnJ4DYur0BjxFjJkLv4QRJpTJnwjiwxkuJZe1HTIIuLbu
...
bKkRJNJ2PpfWA45Vdq6u+izrn9e2TabKjWIfTfT/ZQ==
-----END RSA PRIVATE KEY-----`;
Const RSA encryptor = new jsencrypt(); // RSA encryptor
rsaEncryptor.setPublicKey(PUBLIC_KEY);
Const RSA decryptor = new jsencrypt(); // RSA decryptor
rsaDecryptor.setPrivateKey(PRIVATE_KEY);
3.3.4 create mixed encryption and decryption functions
function hybirdEncrypt(data) {
const iv = getRandomAESKey();
const key = getRandomAESKey();
const encryptedData = aesEncrypt(key, iv, data);
const encryptedIv = rsaEncryptor.encrypt(iv);
const encryptedKey = rsaEncryptor.encrypt(key);
return {
iv: encryptedIv,
key: encryptedKey,
data: encryptedData,
};
}
function hybirdDecrypt(encryptedResult) {
const iv = rsaDecryptor.decrypt(encryptedResult.iv);
const key = rsaDecryptor.decrypt(encryptedResult.key);
const data = encryptedResult.data;
return aesDecrypt(key, iv, data);
}
3.3.5 mixed encryption and decryption example
After the above steps are completed, we have basically completed the mixed encryption function. Before looking at the complete code, let’s take a look at the actual running effect
Note: in the textarea text box below the ciphertext decryption, in addition to the encrypted data, there will also be IV and key in AES CBC mode encrypted by RSA.
In the above example, we create three textareas on the page to store plaintext, encrypted data and decrypted plaintext. When the user clicksencryptionButton, the plaintext input by the user will be mixed encrypted. After encryption, the encrypted data will be displayed in the textarea corresponding to the ciphertext. When the user clicksdecryptButton, the ciphertext will be mixed decrypted, that is, the key and IV of AES will be decrypted with RSA private key first, and then AES decryption of AES encrypted ciphertext will be performed with them. After decryption, the decrypted plaintext will be displayed in the corresponding textarea.
The complete code for the above example is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
< title > mixed encryption and decryption example
<style>
.block {
flex: 1;
}
</style>
</head>
<body>
<h3>Apogee: mixed encryption and decryption example</h3>
<div style="display: flex;">
<div class="block">
<p>① Plaintext encryption = > < button onclick = "encrypt()" > encryption < / button ></p>
<textarea id="plaintext" rows="5" cols="15"></textarea>
</div>
<div class="block">
<p>② Ciphertext decryption = > < button onclick = "decrypt()" > decryption < / button ></p>
<textarea id="ciphertext" rows="5" cols="15"></textarea>
</div>
<div class="block">
<p>③ Decrypted plaintext</p>
<textarea id="decryptedCiphertext" rows="5" cols="15"></textarea>
</div>
</div>
<! -- introducing CDN Crypto.js AES encryption -- >
<script></script>
<script></script>
<script></script>
<script></script>
<script></script>
<script></script>
<script></script>
<script></script>
<! -- introducing CDN Crypto.js End -- >
<script></script>
<script>
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDocWYwnJ4DYur0BjxFjJkLv4QR
JpTJnwjiwxkuJZe1HTIIuLbu/yHyHLhc2MAHKL0Ob+8tcKXKsL1oxs467+q0jA+g
lOUtBXFcUnutWBbnf9qIDkKP2uoDdZ//LUeW7jibVrVJbXU2hxB8bQpBkltZf/xs
cyhRIeiXxs13vlSHVwIDAQAB
-----END PUBLIC KEY-----`;
const PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDocWYwnJ4DYur0BjxFjJkLv4QRJpTJnwjiwxkuJZe1HTIIuLbu
/yHyHLhc2MAHKL0Ob+8tcKXKsL1oxs467+q0jA+glOUtBXFcUnutWBbnf9qIDkKP
2uoDdZ//LUeW7jibVrVJbXU2hxB8bQpBkltZf/xscyhRIeiXxs13vlSHVwIDAQAB
AoGAKOarYKpuc5IYXdArEuHmnFaa2pm7XK8LVTuXVrNuuoPkpfw61Fs4ke3T0yKg
x6G3gq7Xm1tTEROAgMtaxqwo1D5n1H0nkyDFggLB0K9Ws0frp7HENtSQwdNSry1A
iD8TLxkhoWo7BS0VViLT1gKOfnw4YeMJP+CcOQ+DQjCsUMECQQD0Nc0vKBTlK6GT
28gcIMVoQy2KicjiH222A9/TLCNAQ9DEeZDYEptuTfrlbggfWdgQ3nc6CyvGf6c5
6uBPi/+5AkEA86oqqZPi7ekkUVHx0VSkp0mTlD1tAPhDE8cLX8vyImGExS+tTznz
ROyzm3T1M1PisdQIU8Wd5rqvHP6dB0enjwJAauhKpMQ1MYYCPApQ9g9anCQcgbOD
34nGq5HSoE2IOQ/3Cqv1PsIWjRlSJrIemCrqrafWJfDR/xnPCUnLXMd68QJAPNwG
1d4zMvslcA5ImOFMUuBEtST2geSAVINFqwK0krPKxrmWzxAJW/DHF5AJ4m0UVRhB
kDLusn90V4iczgGurwJAZUz6w01OeoLhsOuWNvkbTq+IV0NQ5GAEGA721Ck5zp86
bKkRJNJ2PpfWA45Vdq6u+izrn9e2TabKjWIfTfT/ZQ==
-----END RSA PRIVATE KEY-----`;
Const RSA encryptor = new jsencrypt(); // RSA encryptor
rsaEncryptor.setPublicKey(PUBLIC_KEY);
Const RSA decryptor = new jsencrypt(); // RSA decryptor
rsaDecryptor.setPrivateKey(PRIVATE_KEY);
const plaintextEle = document.querySelector("#plaintext");
const ciphertextEle = document.querySelector("#ciphertext");
const decryptedCiphertextEle = document.querySelector(
"#decryptedCiphertext"
);
function getRandomAESKey() {
return (
Math.random().toString(36).substring(2, 10) +
Math.random().toString(36).substring(2, 10)
);
}
//AES encryption
function aesEncrypt(key, iv, content) {
let text = CryptoJS.enc.Utf8.parse(JSON.stringify(content));
let encrypted = CryptoJS.AES.encrypt(text, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
}
//AES decryption
function aesDecrypt(key, iv, content) {
let decrypt = CryptoJS.AES.decrypt(content, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return decrypt.toString(CryptoJS.enc.Utf8);
}
function hybirdEncrypt(data) {
const iv = getRandomAESKey();
const key = getRandomAESKey();
const encryptedData = aesEncrypt(key, iv, data);
const encryptedIv = rsaEncryptor.encrypt(iv);
const encryptedKey = rsaEncryptor.encrypt(key);
return {
iv: encryptedIv,
key: encryptedKey,
data: encryptedData,
};
}
function hybirdDecrypt(encryptedResult) {
const iv = rsaDecryptor.decrypt(encryptedResult.iv);
const key = rsaDecryptor.decrypt(encryptedResult.key);
const data = encryptedResult.data;
return aesDecrypt(key, iv, data);
}
function encrypt() {
let plaintext = plaintextEle.value;
const encryptedResult = hybirdEncrypt(plaintext);
ciphertextEle.value = JSON.stringify(encryptedResult);
}
function decrypt() {
let ciphertext = ciphertextEle.value;
const encryptedResult = JSON.parse(ciphertext);
decryptedCiphertextEle.value = hybirdDecrypt(encryptedResult).replace(/\"/g,'');
}
</script>
</body>
</html>
Analysis of 3.4 hybrid encryption scheme
Through this example, I believe you have a certain understanding of hybrid encryption. But in the actual web project, we will not decrypt the data in the client, but will submit the data to the server, and then the server will decrypt and process the data.
The HTTP protocol is familiar to most web developers. HTTP protocol is based on request and response, as shown in the following figure:
In the scenario of high data security requirements or transmission of sensitive data, we can consider using the previous hybrid encryption scheme to encrypt the data submitted to the server. When the server receives the corresponding encrypted data, the corresponding decryption algorithm is used to decrypt the encrypted data for further data processing.
But what should be done if the server also wants to return sensitive data? Here, a Bao Ge introduces a scheme, which only needs to use a pair of public and private keys. Of course, this program is for your reference only. If you have a good plan, please leave a message or communicate with brother a Bao.
Let’s take a look at the specific operation process of the scheme
① A unique reqid (request ID) is generated to identify the current request;
② Generate a random AES key and AES IV (using AES CBC mode) respectively;
③ RSA asymmetric encryption algorithm is used to encrypt AES key and AES IV respectively;
④ AES key and AES IV are randomly generated for AES symmetric encryption of sensitive data;
⑤ Save reqid as key and AES key and AES IV as value to map or {} object;
⑥ The reqid, encrypted AES key, AES IV and encrypted data are saved to the object and submitted to the server;
⑦ After receiving the data, the server decrypts the received data, and then uses the decrypted AES key and AES IV from the client to encrypt the response data symmetrically;
⑧ After encrypting the data, the server packages the reqid and encrypted data into response objects and returns them to the client;
⑨ When the client successfully receives the response from the server, it first obtains the reqid, and then obtains the AES encryption information corresponding to the reqid from the map that stores the AES key and IV;
⑩ The client decrypts the data returned by the server using the encrypted information corresponding to the current reqid. After decryption, the existing records are deleted from the map or {} object.
Now let’s make a simple analysis of the above process. First of all, AES encrypted information is generated randomly and saved to memory independently according to each request. When the key and IV of AES encrypted information are submitted to the server, RSA asymmetric encryption algorithm will be used for encryption.
When the server returns data, it encrypts the returned result with AES encryption information corresponding to the current request, and returns the reqid (request ID) corresponding to the current request. That is, the server does not need to regenerate new AES encryption information to encrypt the response data, so it does not need to transmit AES encryption information in the response object.
The scheme seems to be perfect. Since the encrypted information is still in memory, if we use developer tools to debug web applications, we can still see the encrypted information corresponding to each request. So how to solve this problem? Can we prevent the use of developer tools to debug our web applications? The answer is yes.
However, I will not continue to expand here. I will write a separate article to introduce how to prevent using developer tools to debug web applications. Interested partners can leave me a message.
4、 Brother Bao has something to say
4.1 what is message digest algorithm
In fact, in daily work, in addition to symmetric encryption and asymmetric encryption algorithm. There is also a widely used message digest algorithm. Message digest algorithm is a very important branch of cryptography. It extracts fingerprint information from all data to realize data signature, data integrity check and other functions. Because of its irreversibility, it is sometimes used to encrypt sensitive information. Message digest algorithm is also called hash algorithm or hash algorithm.
After any message is processed by hash function, the unique hash value will be obtained. This process is called “message digest”, and its hash value is called “digital fingerprint”, and its algorithm is naturally “message digest algorithm”.In other words, if their digital fingerprints are consistent, their messages are consistent.
(image source——https://zh.wikipedia.org/wiki…）
The main feature of message digest algorithm is that the encryption process does not need a key, and the encrypted data cannot be decrypted. At present, only CRC32 algorithm can decrypt the reverse, and only the same plaintext data can be obtained by the same message digest algorithm.Message digest algorithm has no key management and distribution problem, and is suitable for distributed network. Message digest algorithm is mainly used in the field of “digital signature”, as a plaintext digest algorithm. The famous Abstract algorithms are MD5 algorithm and SHA-1 algorithm of RSA company and a large number of variants.
Message digest algorithm has the following characteristics:
- Regardless of the length of the input message, the length of the calculated message digest is always fixed.For example, the message digested by MD5 algorithm has 128 bits, and the message summarized by SHA-1 algorithm has 160 bits. The variant of SHA-1 can produce 192 bit and 256 bit message digest. Generally speaking, the longer the final output of the digest, the more secure the digest algorithm is.
- The message digest appears to be “random.”.These bits seem to be jumbled together, and a large number of inputs can be used to check whether their outputs are the same. Generally, different inputs will have different outputs, and the output summary messages can pass the randomness test.Generally, as long as the input messages are different, the summary messages generated after summarizing them must be different; however, the same input must produce the same output.
- Message digest function is a one-way function, that is, it can only carry out forward information summarization, but can not recover any message from the digest, or even can not find any information related to the original information.
- A good summary algorithm, no one can find “collision” or extremely difficult to find, although “collision” is sure to exist (collision means different contents produce the same summary).
4.2 what is MD5 algorithm
MD5 (message digest algorithm 5), which is developed from MD2, MD3 and MD4, was proposed by Ron Rivest (RSA company) in 1992. It is widely used in data integrity check, data (message) digest, data signature and so on.MD2, MD4, MD5 all produce 16 byte (128 bit) check value, which is generally expressed by 32-bit hexadecimal number. MD2 algorithm is slow but relatively safe, MD4 is fast, but security is reduced, MD5 is safer and faster than MD4.
With the development of computer technology and the improvement of computing level, there are more and more loopholes in MD5 algorithm. After 1996, it has been proved that there are weaknesses that can be cracked. For data that requires high security, experts generally recommend using other algorithms, such as SHA-2. In 2004, it was proved that MD5 algorithm can not prevent collision, so it is not suitable for security authentication, such as SSL public key authentication or digital signature.
4.2.1 MD5 features
- It is stable and fast.
- Compressibility: input any length of data, output length fixed (128 bits).
- Operation irreversibility: when the result of the operation is known, the original string cannot be obtained by inverse operation.
- Highly discrete: small changes in input can lead to huge differences in operation results.
4.2.2 MD5 hash
A 128 bit MD5 hash is represented in most cases as a 32-bit hexadecimal number. Here is a 43 bit MD5 hash of only ASCII alphabetic columns:
MD5("The quick brown fox jumps over the lazy dog")
= 9e107d9d372bb6826bd81d3542a419d6
Even if you make a small change in the original text (such as changing dog to cog, only changing one character), the hash will change greatly
MD5("The quick brown fox jumps over the lazy cog")
= 1055d3e698d289f2af8663725127bd4b
Next, let’s take a few examples of MD5 hash:
MD5("") -> d41d8cd98f00b204e9800998ecf8427e
MD5("semlinker") -> 688881f1c8aa6ffd3fcec471e0391e4d
MD5("kakuqo") -> e18c3c4dd05aef020946e6afbf9e04ef
4.2.3 use of MD5 algorithm
File distribution tamper proof
When distributing the software installation package on the Internet, for security consideration, in order to prevent the software from being tampered with, for example, adding Trojan to the software installation program. Software developers usually use message digest algorithm, such as MD5 algorithm, to generate a digital fingerprint matching the file, so that the receiver can use some ready-made tools to check the integrity of the file after receiving the file.
Message transmission tamper proof
Suppose you need to send an electronic document to your friend on the network. Before sending the document, MD5 operation is performed on the content of the document to obtain the “digital fingerprint” of the electronic document, and the “digital fingerprint” is sent to the other party along with the electronic document. When the other party receives the electronic document, it also uses MD5 algorithm to hash the content of the document. After the operation is completed, a corresponding “digital fingerprint” will be obtained. When the fingerprint is consistent with the “digital fingerprint” of the document you sent, it means that the document has not been tampered with in the transmission process.
4.2.4 defects of MD5 algorithm
Hash collision means that different inputs produce the same output. A good hash algorithm, no one should be able to find the “collision” or extremely difficult to find, although the “collision” is sure to exist.
In 2005, Professor Wang Xiaoyun of Shandong University released the algorithm, which can easily construct MD5 collision instances. Since then, in 2007, some foreign scholars proposed a further MD5 prefix collision construction algorithm “chosen prefix collision” on the basis of Professor Wang Xiaoyun’s algorithm. Since then, some experts have successively provided open source libraries for MD5 collision construction.
In 2009, Xie Tao and Feng Dengguo of the Chinese Academy of Sciences cracked MD5’s collision resistance with only 220.96 collision algorithm complexity. The attack only takes a few seconds to run on ordinary computers.
MD5 collision is easy to construct, and it is not reliable to verify data integrity based on MD5. Considering that Google has successfully constructed SHA-1 (English: secure hash algorithm 1, Chinese Name: secure hash algorithm 1), for data integrity, sha256 or stronger algorithm should be used instead.
In fact, there is a lot of MD5 related knowledge, such as MD5 ciphertext reverse query, password salt adding and content resource anti-theft chain. Here, brother Bao will not continue to expand, and interested partners can read what he wrote before”Read MD5 algorithm“This article.
5、 Reference resources