How to use the AES function from crypto-js

Find comprehensive JavaScript crypto-js.AES code examples handpicked from public code repositorys.

crypto-js.AES is a function that provides encryption and decryption functionality using the AES algorithm.

10
11
12
13
14
15
16
17
18
19
  base64: str => CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(str)),
  hex: str => CryptoJS.enc.Hex.stringify(CryptoJS.enc.Utf8.parse(str)),
  aes: (str, aeskey, aesiv) => {
    const key = CryptoJS.enc.Utf8.parse(aeskey);
    const iv = CryptoJS.enc.Utf8.parse(aesiv);
    return CryptoJS.AES.encrypt(str, key, { iv }).ciphertext.toString();
  },
};
function enc(name, { method, key, iv }) {
  if (!methods[method]) {
fork icon15
star icon86
watch icon2

+ 7 other calls in file

116
117
118
119
120
121
122
123
124
125

var salt = CryptoJS.lib.WordArray.random(16);
var stretched_password = stretchPassword(password, salt, pbkdf2_iterations);
var iv = salt;
var payload = CryptoJS.enc.Utf8.parse(data);
var encrypted = CryptoJS.AES.encrypt(payload, stretched_password, {
  mode: CryptoJS.mode.CBC,
  padding: CryptoJS.pad.Iso10126,
  iv: iv
});
fork icon16
star icon17
watch icon6

+ 3 other calls in file

How does crypto-js.AES work?

crypto-js.AES is a function that provides encryption and decryption functionality using the AES algorithm. When called with a plaintext message and a secret key, the function returns a ciphertext that has been encrypted using the AES algorithm. Similarly, when called with a ciphertext and the same secret key, the function returns the original plaintext message. By default, crypto-js.AES uses a 128-bit key length, but it can be configured to use other key lengths as well, such as 192-bit and 256-bit keys. The function can also accept an optional third argument, which is an object containing configuration options for the encryption or decryption process. These options include things like the encryption mode to use, the initialization vector (IV) to use, and padding options. For example, to encrypt a message using AES-128 encryption with a secret key, you can call crypto-js.AES.encrypt like this: javascript Copy code {{{{{{{ const CryptoJS = require('crypto-js'); const plaintext = 'secret message'; const key = 'my secret key'; const ciphertext = CryptoJS.AES.encrypt(plaintext, key).toString(); console.log(ciphertext); In this example, we first import the crypto-js library using require. We define a plaintext message and a secret key. We call CryptoJS.AES.encrypt with plaintext and key, which returns an Object containing the encrypted ciphertext. We call the toString method on the resulting Object to convert it to a string. We log the resulting ciphertext to the console using console.log. When you run this example in a JavaScript environment like a web browser or Node.js, you should see the encrypted ciphertext logged to the console. Overall, crypto-js.AES is a powerful tool for encrypting and decrypting data using the AES algorithm, and it provides a wide range of configuration options for fine-tuning the encryption process.

80
81
82
83
84
85
86
87
88
89

/**
 * Crypto-JS AES decrypt to UTF-8 format
 */
function aesDecrypt(data,key) {
    return CryptoJS.AES.decrypt(data,key).toString(CryptoJS.enc.Utf8)
}

function isCanonicalSignature(signature) {
    return (
fork icon9
star icon23
watch icon5

+ 3 other calls in file

3
4
5
6
7
8
9
10
11
12
exports.md5 = (content) => {
  return crypto.HmacMD5(content, secret);
}

exports.aesDecrypt = (content) => {
  const bytes = crypto.AES.decrypt(content, secret);
  return bytes.toString(crypto.enc.Utf8);
}

exports.toBase64 = (content) => {
fork icon3
star icon9
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const CryptoJS = require("crypto-js");

const plaintext = "secret message";
const key = "my secret key";

// Encrypt the plaintext message using AES-128 encryption
const ciphertext = CryptoJS.AES.encrypt(plaintext, key).toString();

// Decrypt the ciphertext back to plaintext using the same key
const decryptedText = CryptoJS.AES.decrypt(ciphertext, key).toString(
  CryptoJS.enc.Utf8
);

console.log(decryptedText); // prints 'secret message'

In this example, we first import the crypto-js library using require. We define a plaintext message and a secret key. We call CryptoJS.AES.encrypt with plaintext and key, which returns an Object containing the encrypted ciphertext. We call the toString method on the resulting Object to convert it to a string. We store the resulting ciphertext in the ciphertext variable. We then call CryptoJS.AES.decrypt with ciphertext and key, which returns an Object containing the decrypted plaintext. We call the toString method on the resulting Object, passing CryptoJS.enc.Utf8 as an argument to convert it to a human-readable string. We store the resulting plaintext in the decryptedText variable, and log it to the console using console.log. When you run this example in a JavaScript environment like a web browser or Node.js, you should see the original plaintext message logged to the console after it has been decrypted from the ciphertext. Note that crypto-js provides a range of other functions for working with encryption and decryption, such as HMAC for generating message authentication codes and PBKDF2 for deriving keys from passwords. You can find more information on using crypto-js in the library's documentation page.

39
40
41
42
43
44
45
46
47
48
},
ECBDecrypt(data) {
  var key = CryptoJS.enc.Utf8.parse(aseKey);
  var ivs = CryptoJS.enc.Utf8.parse(iv);

  var decrypt = CryptoJS.AES.decrypt(data, key, {
    iv: ivs,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
fork icon2
star icon8
watch icon2

+ 11 other calls in file

18
19
20
21
22
23
24
25
26
27

initializeKeyringController() {
    const keyringController = new KeyringController({
    encryptor: {
        encrypt(pass, object) {
            const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(object), pass).toString();

            return ciphertext;
        },
        decrypt(pass, encryptedString) {
fork icon4
star icon4
watch icon4

17
18
19
20
21
22
23
24
25
26
27
28
29
30
}


async function generatePrivData(mnemonic, pin) {
  var priv = {};


  const encryptedMnemonic = cryptojs.AES.encrypt(mnemonic, pin.toString()).toString();


  priv.encryptedMnemonic = encryptedMnemonic;


  return priv;
fork icon4
star icon4
watch icon4

+ 3 other calls in file

17
18
19
20
21
22
23
24
25
26
  return encrypted
}

static decryptPrivateKey(encrypted) {
  const secret = process.env.SECRET_PASSPHRASE
  const decrypted = CryptoJS.AES.decrypt(encrypted, secret).toString(CryptoJS.enc.Utf8)
  return decrypted
}

static async getAdminAccountWithKeyIndex(keyIndex) {
fork icon2
star icon5
watch icon0

138
139
140
141
142
143
144
145
146
147
 */
aesEcbEncrypt(message, key = ';Z#^$;8+yhO!AhGo') {
    // utf8字符串—>WordArray对象,WordArray是一个保存32位整数的数组,相当于转成了二进制
    const keyHex = cryptoJS.enc.Utf8.parse(key);
    const messageHex = cryptoJS.enc.Utf8.parse(message);
    const encrypted = cryptoJS.AES.encrypt(messageHex, keyHex, {
        mode: cryptoJS.mode.ECB,
        padding: cryptoJS.pad.Pkcs7,
    });
    return encrypted.toString(); // base64结果
fork icon2
star icon2
watch icon2

99
100
101
102
103
104
105
106
107
  }).toString()
  return {key, salt: salt.toString()}
}

export function encrypt(text, code){
  return CryptoJS.AES.encrypt(text, code, {
    format: KatuCryptoFormatter
  });
}
fork icon0
star icon2
watch icon1

+ 17 other calls in file

540
541
542
543
544
545
546
547
548
549
550
var key = CryptoJS.enc.Utf8.parse("60532EB847CFB989");
var iv = CryptoJS.enc.Utf8.parse("0FF5A43FDAFCEF98");


function AES_Encrypt(word) {
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
fork icon0
star icon1
watch icon1

+ 15 other calls in file

101
102
103
104
105
106
107
108
109
110
},
hmacripemd160() {
  return CryptoJS.HmacRIPEMD160(this.text, this.serect).toString();
},
aes() {
  return CryptoJS.AES.encrypt(this.text, this.serect).toString();
},
tripledes() {
  return CryptoJS.TripleDES.encrypt(this.text, this.serect).toString();
},
fork icon0
star icon1
watch icon1

+ 17 other calls in file

9
10
11
12
13
14
15
16
17
  }).toString();
}

function legacyDecryptString(encryptedStr, password) {
  const { encStr, iv, salt } = encryptedStr;
  const decryptedStr = CryptoJS.AES.decrypt(encStr, password, { iv, salt });

  return decryptedStr.toString(CryptoJS.enc.Latin1);
}
fork icon486
star icon0
watch icon0

549
550
551
552
553
554
555
556
557
558
559
    return encrypted.toString();
}


function AES_Decrypt(word) {
    var srcs = word;
    var decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
fork icon2
star icon0
watch icon0

+ 9 other calls in file

100
101
102
103
104
105
106
107
108
109
if (users.length != 0) {
    for (var i = 0; i < users.length; i++) {
        if (CryptoJS.AES.decrypt(users[i].info.login, secret).toString(CryptoJS.enc.Utf8) ===
            CryptoJS.AES.decrypt(req.body.login, secret).toString(CryptoJS.enc.Utf8) &&
            CryptoJS.AES.decrypt(users[i].info.email, secret).toString(CryptoJS.enc.Utf8) ===
            CryptoJS.AES.decrypt(req.body.email, secret).toString(CryptoJS.enc.Utf8)) {
            console.log('Пользователь с такими данными уже существует');
            return res.send({ status: 'alreadyIs', token: false });
            return;
        }
fork icon2
star icon0
watch icon0

+ 7 other calls in file

23
24
25
26
27
28
29
30
31
32
};

/* AES coding */
exports.encodeAES = function(normalString, key) {
        try {
        return CryptoJS.AES.encrypt(
            normalString, 
            typeof key !== undefined ? key : this.key,
            this.cfg
        );
fork icon1
star icon0
watch icon2

+ 3 other calls in file

19
20
21
22
23
24
25
26
27
await Moralis?.start({ serverUrl: env.APP_SERVER_URL, appId: env.APP_ID, masterKey: env.APP_MASTER_KEY })
if (status != "success" || timestamp.length < 100)
  res.status(500).json({ msg: "Internal Server Error!!!" });

const passphrase = process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY;
const bytes = CryptoJS.AES.decrypt(timestamp, passphrase);
const decode = bytes.toString(CryptoJS.enc.Utf8);

let token = decode.substr(32, 64);
fork icon0
star icon1
watch icon1

71
72
73
74
75
76
77
78
79
80
        return res.status(500).json({ msg: "server error! " });
    }
    return res.status(400).json({ msg: "user not found" });
}
if (process.env.PASS_SECRET && process.env.JWT_SECRET && user.password) {
    const decryptPass = CryptoJS.AES.decrypt(user.password, process.env.PASS_SECRET).toString(CryptoJS.enc.Utf8);
    if (decryptPass !== req.body.password)
        return res.status(400).json({ msg: "invalid password" });
    const token = jsonwebtoken_1.default.sign({ _id: user._id }, process.env.JWT_SECRET, {
        expiresIn: "7d",
fork icon0
star icon1
watch icon1

+ 3 other calls in file

8
9
10
11
12
13
14
15
16
17
18
 * AES_256 암호화. 
 * @param {String} msg 암후화 하고싶은 문자열
 * @author hmju
 */
exports.enc = function (msg) {
    return '' + CryptoJS.AES.encrypt(JSON.stringify(msg), process.env.AES_KEY);
}


/**
 * getter 
fork icon0
star icon1
watch icon1

+ 9 other calls in file

106
107
108
109
110
111
112
113
114
115
116
117




const clienttoken = (req, res) => {
    const cookies_token = new Cookies(req, res, {"keys":[process.env.COOKIES_KEY]})
        .get('sessionisdd', {signed:true});
    let bytes  = CryptoJS.AES.decrypt((cookies_token === undefined) ? 'token' : cookies_token, process.env.COOKIES_KEY);
    let original_token = bytes.toString(CryptoJS.enc.Utf8);
    return original_token;
};

fork icon0
star icon1
watch icon1

+ 9 other calls in file