Home>

Since javascript is a weakly typed scripting language,So when it interacts with strongly typed back-end languages, it creates various problems,Especially the operation of encryption and decryption.I encountered the problem of encrypting and decrypting with js and java in my work.Checked a lot of information and code snippets online.Cannot be resolved.After summing up the contents of multiple documents, I finally found a solution.Recorded with this:

The following introduces the two AES encryption methods of JavaScript.The details are as follows:

The first type:when encryption and decryption require a key (key) and a key offset (iv), verify the address online:

//This method can perform mutual encryption and decryption with java<! Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AES encryption and decryption requiring a key (key) and key offset (iv)</title>
</head>
<body>
<script src="aes_1.js"></script>//The js file introduced is in this link:https://github.com/hellobajie/aes-of-javascript
<script>
var key=cryptojs.enc.utf8.parse ("Hexadecimal number as secret key");
var iv=cryptojs.enc.utf8.parse ("hexadecimal hexadecimal number as key offset");
function encrypt (word) {
srcs=cryptojs.enc.utf8.parse (word);
var encrypted=cryptojs.aes.encrypt (srcs, key, {iv:iv, mode:cryptojs.mode.cbc, padding:cryptojs.pad.pkcs7});
return encrypted.ciphertext.tostring (). touppercase ();
}
function decrypt (word) {
var encryptedhexstr=cryptojs.enc.hex.parse (word);
var srcs=cryptojs.enc.base64.stringify (encryptedhexstr);
var decrypt=cryptojs.aes.decrypt (srcs, key, {iv:iv, mode:cryptojs.mode.cbc, padding:cryptojs.pad.pkcs7});
var decryptedstr=decrypt.tostring (cryptojs.enc.utf8);
return decryptedstr.tostring ();
}
var mm=encrypt ("nihao")
console.log (mm);
var jm=decrypt (mm);
console.log (jm)
</script>
</body>
<p>
<strong>
The second type:only the secret key is needed for encryption and decryption,Online verification address:
</strong>
</p>
<pre>
<code>
<! Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Only the secret key is required for encryption and decryption</title>
</head>
<body>
<script src="aes_2.js"></script>//The js file introduced is in the link:https://github.com/hellobajie/aes-of-javascript
<script type="text/javascript">
var pwd="secret key";
function encrypt (word) {
return cryptojs.aes.encrypt (word, pwd) .tostring ();
}
function decrypt (word) {
return cryptojs.aes.decrypt (word, pwd) .tostring (cryptojs.enc.utf8);
}
var mm=encrypt ("nihao");
console.log (mm)
var jm=decrypt (mm);
console.log (jm)
</script>
</body>
</html>
  • Previous AngularJS basic ng-model instruction detailed and sample code
  • Next JS method to get the absolute path of the input file (recommended)