js encrypt/decrypt data

by slawe

HTML

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

JavaScript

let secretKey = '12345';

const cryptoData = {

    value:
    {
        data: null,

        get() {
            try {
                this.check();
            } catch (e) {
                return e;
            }
            return this.value;
        },

        set(data) {
            this.data = JSON.stringify(data);
            return this;
        },

        check() {
            if (!this.data) {
                throw new Error('You must first call "value.set" method!');
            }
        },

        encrypt(value = null) {
            if (value)
                this.set(value);

            try {
                // check passed value existing
                this.check();
                // encrypt data
                this.data = CryptoJS.AES.encrypt(this.data, secretKey).toString();
            } catch (error) {
                return error;
            }
            return value ? this.data : this;
        },

        decrypt(value = null) {
            if (value)
                this.set(value);

            try {
                // check passed value existing
                this.check();
                // decrypt data
                let decryptValue = CryptoJS.AES.decrypt(this.data, secretKey);
                this.data = JSON.parse(decryptValue.toString(CryptoJS.enc.Utf8));
            } catch (error) {
                return error;
            }
            return value ? this.data : this;
        },
    },

    storage:
    {
        getItem: (storageKey) => {
            // Get the store from local storage.
            let data = localStorage.getItem(storageKey);

            if (data) {
                try {
                    // Decrypt the store retrieved from local storage
                    // using our encryption token.
                    return cryptoData.value.decrypt(data);
                } catch (e) {
                    console.log(e);
                    // The store will be reset if decryption fails.
                   ...