Giter Site home page Giter Site logo

feat(app): encrypt data about memoir HOT 2 OPEN

huilensolis avatar huilensolis commented on September 9, 2024
feat(app): encrypt data

from memoir.

Comments (2)

guiprav2 avatar guiprav2 commented on September 9, 2024 1

encrypt/decrypt utilities example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AES Encryption/Decryption</title>
    <script>
        async function getKeyMaterial(password) {
            const encoder = new TextEncoder();
            return window.crypto.subtle.importKey(
                "raw",
                encoder.encode(password),
                { name: "PBKDF2" },
                false,
                ["deriveKey"]
            );
        }

        async function getKey(keyMaterial, salt) {
            return window.crypto.subtle.deriveKey(
                {
                    name: "PBKDF2",
                    salt: salt,
                    iterations: 100000,
                    hash: "SHA-256"
                },
                keyMaterial,
                { name: "AES-GCM", length: 256 },
                false,
                ["encrypt", "decrypt"]
            );
        }

        function arrayBufferToBase64(buffer) {
            let binary = '';
            const bytes = new Uint8Array(buffer);
            const len = bytes.byteLength;
            for (let i = 0; i < len; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            return window.btoa(binary);
        }

        function base64ToArrayBuffer(base64) {
            const binary = window.atob(base64);
            const len = binary.length;
            const bytes = new Uint8Array(len);
            for (let i = 0; i < len; i++) {
                bytes[i] = binary.charCodeAt(i);
            }
            return bytes.buffer;
        }

        async function encrypt(payload, password) {
            const keyMaterial = await getKeyMaterial(password);
            const salt = window.crypto.getRandomValues(new Uint8Array(16));
            const key = await getKey(keyMaterial, salt);
            const iv = window.crypto.getRandomValues(new Uint8Array(12));
            const encoder = new TextEncoder();
            const data = encoder.encode(payload);
            const encryptedData = await window.crypto.subtle.encrypt(
                {
                    name: "AES-GCM",
                    iv: iv
                },
                key,
                data
            );
            const encryptedContent = new Uint8Array(encryptedData);
            const result = new Uint8Array(salt.length + iv.length + encryptedContent.length);
            result.set(salt, 0);
            result.set(iv, salt.length);
            result.set(encryptedContent, salt.length + iv.length);
            return arrayBufferToBase64(result.buffer);
        }

        async function decrypt(payload, password) {
            const keyMaterial = await getKeyMaterial(password);
            const data = base64ToArrayBuffer(payload);
            const salt = data.slice(0, 16);
            const iv = data.slice(16, 28);
            const encryptedData = data.slice(28);
            const key = await getKey(keyMaterial, salt);
            const decryptedData = await window.crypto.subtle.decrypt(
                {
                    name: "AES-GCM",
                    iv: iv
                },
                key,
                encryptedData
            );
            const decoder = new TextDecoder();
            return decoder.decode(decryptedData);
        }

        // Example usage:
        async function exampleUsage() {
            const text = "Hello, world!";
            const password = "securepassword";
            const encrypted = await encrypt(text, password);
            console.log("Encrypted:", encrypted);
            const decrypted = await decrypt(encrypted, password);
            console.log("Decrypted:", decrypted);
        }

        window.onload = exampleUsage;
    </script>
</head>
<body>
    <h1>AES Encryption/Decryption Example</h1>
    <p>Check the console for results.</p>
</body>
</html>

from memoir.

huilensolis avatar huilensolis commented on September 9, 2024
  • Use AES to encrypt user data before sending to the server.
  • Use plaintext user passwords as encryption key, ask them for long passwords.
  • Only send hashed passwords to your server (don't forget to salt them too; ideally use bcrypt, it does that for you).
  • Hash passwords on the server again so database dumps aren't enough to log into user accounts (again use bcrypt).
  • Use base64 to encode encrypted payloads so you can treat them as simple strings in your database.

from memoir.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.