J
J
jenya77712019-05-08 12:15:33
JavaScript
jenya7771, 2019-05-08 12:15:33

How to encrypt (decrypt) data correctly using the AES algorithm through the CryptoJs library?

Hello, please tell me how to encrypt and decrypt data using the CryptoJs library?
Now I've come up with this:

const key = CryptoJS.lib.WordArray.random(256).toString()

// Шифрование сообщения
function encryptMessage(message) {

    var iv = CryptoJS.lib.WordArray.random(256)
    var encrypted = CryptoJS.AES.encrypt(message, key, { iv: iv });

    return encrypted.toString()
}

// Дешифрование сообщения
function decryptMessage(encrypted) {

    const decrypted = CryptoJS.AES.decrypt(encrypted, key)

    return decrypted.toString(CryptoJS.enc.Utf8)
}

And the question arose for me, what if I use a key that is more than 256 bits, for example 1024, will the algorithm accept it, or will it take only the first 254 bits?
And iv is always random to create, they are not needed for decryption?
And is it worth using additional PBKDF2:
const key = CryptoJS.lib.WordArray.random(256).toString()

function encryptMessage(message) {

    var salt = CryptoJS.lib.WordArray.random(32)
    var iv = CryptoJS.lib.WordArray.random(256)
    var newKey = CryptoJS.PBKDF2(key, salt, { keySize: 256, iterations: 10 })

    var encrypted = CryptoJS.AES.encrypt(message, newKey, { iv: iv });

    return encrypted.toString()
}

As I understand it, this will help a small password (10 bits) be converted into a 256 bit key.
And when using a random salt, it is not possible to decrypt the data, why is that?
Thank you!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question