<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ encryption - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ encryption - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:35:49 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/encryption/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Browser-Based PDF Password Protector Using JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Contracts, invoices, medical reports, and scanned ID cards are often converted to PDF files. And if one of them ends up in the wrong inbox or on a shared drive, anyone can open it. Adding a password f ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-pdf-password-protector-javascript/</link>
                <guid isPermaLink="false">6aff2ffbede28e00513a0715</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pdf ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bhavin Sheth ]]>
                </dc:creator>
                <pubDate>Thu, 19 Nov 2026 17:20:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/3ad5640f-31b1-412d-a20c-d1180ae363f2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Contracts, invoices, medical reports, and scanned ID cards are often converted to PDF files. And if one of them ends up in the wrong inbox or on a shared drive, anyone can open it.</p>
<p>Adding a password fixes that. A protected PDF is encrypted, so the file is unreadable until someone types the right password.</p>
<p>Most online tools that do this ask you to upload the document first. But that's an odd thing to do with a file you're trying to keep private.</p>
<p>In this tutorial, you'll build a browser-based PDF password protector with JavaScript. You'll open a PDF, choose a password, decide whether people can print, copy or edit it, encrypt the file with AES-256, check the result, and download it. The file never leaves the browser.</p>
<p>The interesting part is that the most popular JavaScript PDF library, PDF-lib, can't encrypt PDFs. So you'll write the encryption yourself with the Web Crypto API, following the PDF 2.0 specification. It's less code than you might expect: about 150 lines.</p>
<p>I built this tool for <a href="https://allinonetools.net/">All In One Tools</a>, where it runs as the Protect PDF tool. This article walks through a simplified version that you can build in three files.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/25eafe88-cf76-45b8-8411-949d202f2ac6.png" alt="Protect PDF tool on All In One Tools, showing the drop area for adding a PDF" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a href="#heading-what-this-pdf-protector-does">What This PDF Protector Does</a></li>
<li><a href="#heading-how-pdf-encryption-works">How PDF Encryption Works</a></li>
<li><a href="#heading-project-setup">Project Setup</a></li>
<li><a href="#heading-libraries-and-browser-apis-used">Libraries and Browser APIs Used</a></li>
<li><a href="#heading-creating-the-html-layout">Creating the HTML Layout</a></li>
<li><a href="#heading-opening-the-pdf">Opening the PDF</a></li>
<li><a href="#heading-handling-the-password-fields">Handling the Password Fields</a></li>
<li><a href="#heading-helpers-for-bytes-and-web-crypto">Helpers for Bytes and Web Crypto</a></li>
<li><a href="#heading-hashing-the-password-the-pdf-20-way">Hashing the Password the PDF 2.0 Way</a></li>
<li><a href="#heading-turning-permissions-into-a-number">Turning Permissions into a Number</a></li>
<li><a href="#heading-building-the-encryption-keys">Building the Encryption Keys</a></li>
<li><a href="#heading-encrypting-every-string-and-stream">Encrypting Every String and Stream</a></li>
<li><a href="#heading-writing-the-protected-pdf">Writing the Protected PDF</a></li>
<li><a href="#heading-checking-the-result-with-pdfjs">Checking the Result with PDF.js</a></li>
<li><a href="#heading-connecting-the-button">Connecting the Button</a></li>
<li><a href="#heading-renaming-and-downloading">Renaming and Downloading</a></li>
<li><a href="#heading-testing-the-file-outside-the-browser">Testing the File Outside the Browser</a></li>
<li><a href="#heading-demo-how-the-protect-pdf-tool-works">Demo: How the Protect PDF Tool Works</a></li>
<li><a href="#heading-performance-tips">Performance Tips</a></li>
<li><a href="#heading-common-mistakes">Common Mistakes</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-this-pdf-protector-does">What This PDF Protector Does</h2>
<p>The finished tool lets you open a PDF by clicking a button or dropping the file on the page. You can type a password that will be needed to open the file (and optionally type a second password for the permissions). You can also choose whether people can print, copy text and images, or edit the file.</p>
<p>The tool also encrypts the PDF with AES-256, checks that the new file really asks for a password and opens it with yours, and lets you rename and download the protected copy.</p>
<p>Through all this, the original file is never changed, and nothing is sent to a server.</p>
<h2 id="heading-how-pdf-encryption-works">How PDF Encryption Works</h2>
<p>Before writing our code, it helps to know what a protected PDF looks like inside. You don't need to read the specification, but these five ideas will make the rest of the article easier to follow.</p>
<h3 id="heading-1-the-content-is-encrypted-the-structure-isnt">1. The Content is Encrypted, the Structure Isn't</h3>
<p>A PDF is a list of numbered objects: dictionaries, arrays, numbers, names, strings and streams (a stream is a block of data, such as the drawing instructions of a page or an image). When a PDF is protected, every <strong>string</strong> and every <strong>stream</strong> is encrypted. Numbers, names and the way objects point to each other stay readable, so a PDF reader can still find its way around the file.</p>
<h3 id="heading-2-one-random-key-encrypts-everything">2. One Random Key Encrypts Everything</h3>
<p>The tool creates a random 256-bit file key and encrypts all strings and streams with it using AES. The password isn't the key.</p>
<h3 id="heading-3-the-password-unlocks-the-key">3. The Password Unlocks the Key</h3>
<p>The file stores the file key twice, encrypted with a hash of each password, plus a value that lets a reader check whether a typed password is right. These values live in an encryption dictionary, and the file's trailer points to it with <code>/Encrypt</code>.</p>
<h3 id="heading-4-there-are-two-passwords">4. There Are Two Passwords</h3>
<ul>
<li>The <strong>user password</strong> (the open password) is needed to open the file.</li>
<li>The <strong>owner password</strong> (the permissions password) unlocks the file <em>and</em> lets the owner change what's allowed.</li>
</ul>
<h3 id="heading-5-permissions-arent-a-lock"><strong>5. Permissions Aren't a Lock</strong></h3>
<p>The allowed actions (print, copy, edit) are stored as bits in a number called <code>/P</code>. Good PDF readers obey them, but a program that ignores them can still print or copy once the file is open. The open password is what really protects the content.</p>
<p>PDF has used several encryption methods over the years:</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Revision</th>
<th>Status</th>
</tr>
</thead>
<tbody><tr>
<td>RC4 40-bit and 128-bit</td>
<td>R2 to R4</td>
<td>Old and weak, don't use them for new files</td>
</tr>
<tr>
<td>AES-128</td>
<td>R4</td>
<td>Opens in Acrobat 7 and newer</td>
</tr>
<tr>
<td>AES-256</td>
<td>R6</td>
<td>PDF 2.0 standard, opens in Acrobat X and newer and in all current PDF apps</td>
</tr>
</tbody></table>
<p>This tool uses <strong>AES-256 (revision 6)</strong>. It's the strongest option, and it's also the simplest to build, because every object uses the same key.</p>
<p>Let's go through the flow.</p>
<p>From the PDF file:</p>
<ul>
<li>PDF-lib loads the objects</li>
<li>random file key (32 bytes)</li>
<li>U, UE, O, OE, Perms from the passwords (SHA-2 + AES)</li>
<li>every string and stream is encrypted with AES-256</li>
<li>/Encrypt dictionary + /ID are added to the trailer</li>
<li>the saved PDF is checked with PDF.js and then downloaded</li>
</ul>
<h2 id="heading-project-setup">Project Setup</h2>
<p>The project is three files and has no build step:</p>
<pre><code class="language-text">pdf-protector/
├── index.html
├── style.css
└── script.js
</code></pre>
<p>Because the Web Crypto API only works in a secure context, open the page from <code>https://</code> or from <code>http://localhost</code>. If you open <code>index.html</code> with a <code>file://</code> path or a plain <code>http://</code> address, <code>crypto.subtle</code> is <code>undefined</code>.</p>
<p>The easiest way to get a local server is:</p>
<pre><code class="language-bash">npx serve .
</code></pre>
<p>Then open the address it prints, such as <code>http://localhost:3000</code>.</p>
<h2 id="heading-libraries-and-browser-apis-used">Libraries and Browser APIs Used</h2>
<p><a href="https://pdf-lib.js.org/"><strong>PDF-lib</strong></a> <strong>1.17.1</strong> reads the PDF into objects you can change and writes it back out. It doesn't support encryption, which is why you'll build that part.</p>
<p><a href="https://mozilla.github.io/pdf.js/"><strong>PDF.js</strong></a> <strong>3.11.174</strong> is Mozilla's PDF reader. You'll use it to open the protected file, the same way a real reader would, and confirm that it works.</p>
<p><strong>The</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API"><strong>Web Crypto API</strong></a> is built into every modern browser. It gives you AES encryption, SHA-256/384/512 hashes, and secure random numbers. Never use <code>Math.random()</code> for keys.</p>
<p>Both libraries load from a CDN at the end of <code>index.html</code>:</p>
<pre><code class="language-html">&lt;script src="https://unpkg.com/pdf-lib@1.17.1/dist/pdf-lib.min.js"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"&gt;&lt;/script&gt;
&lt;script src="script.js"&gt;&lt;/script&gt;
</code></pre>
<h2 id="heading-creating-the-html-layout">Creating the HTML Layout</h2>
<p>The page has three parts: an upload area, a settings panel with the passwords and permissions, and a result panel. The settings and result panels start hidden.</p>
<pre><code class="language-html">&lt;!-- 1. Upload --&gt;
&lt;section id="uploadArea" class="upload-area"&gt;
  &lt;p&gt;Drop a PDF here or&lt;/p&gt;
  &lt;button type="button" id="selectBtn"&gt;Select PDF&lt;/button&gt;
  &lt;input type="file" id="fileInput" accept="application/pdf,.pdf" hidden&gt;
  &lt;p id="fileInfo" class="file-info" aria-live="polite"&gt;&lt;/p&gt;
&lt;/section&gt;

&lt;!-- 2. Passwords --&gt;
&lt;section id="settings" class="panel" hidden&gt;
  &lt;h2&gt;Passwords&lt;/h2&gt;

  &lt;label for="openPw"&gt;Password to open the PDF&lt;/label&gt;
  &lt;div class="pw-row"&gt;
    &lt;input type="password" id="openPw" autocomplete="new-password"&gt;
    &lt;button type="button" class="show-btn" data-target="openPw"&gt;Show&lt;/button&gt;
  &lt;/div&gt;
  &lt;p id="strength" class="hint"&gt;Use at least 8 characters.&lt;/p&gt;

  &lt;label for="openPw2"&gt;Type the password again&lt;/label&gt;
  &lt;input type="password" id="openPw2" autocomplete="new-password"&gt;

  &lt;label for="ownerPw"&gt;Permissions password (optional)&lt;/label&gt;
  &lt;div class="pw-row"&gt;
    &lt;input type="password" id="ownerPw" autocomplete="new-password"&gt;
    &lt;button type="button" class="show-btn" data-target="ownerPw"&gt;Show&lt;/button&gt;
  &lt;/div&gt;
  &lt;p class="hint"&gt;Lets you change the restrictions below later. Leave it empty to use a random one.&lt;/p&gt;

  &lt;h2&gt;What can people do after opening it?&lt;/h2&gt;
  &lt;label class="check"&gt;&lt;input type="checkbox" id="allowPrint" checked&gt; Print&lt;/label&gt;
  &lt;label class="check"&gt;&lt;input type="checkbox" id="allowCopy" checked&gt; Copy text and images&lt;/label&gt;
  &lt;label class="check"&gt;&lt;input type="checkbox" id="allowEdit"&gt; Edit, comment and fill forms&lt;/label&gt;

  &lt;button type="button" id="protectBtn" class="primary"&gt;Protect PDF&lt;/button&gt;
  &lt;p id="status" class="status" aria-live="polite"&gt;&lt;/p&gt;
&lt;/section&gt;

&lt;!-- 3. Result --&gt;
&lt;section id="result" class="panel" hidden&gt;
  &lt;h2&gt;Your protected PDF is ready&lt;/h2&gt;
  &lt;ul id="checks" class="checks"&gt;&lt;/ul&gt;
  &lt;label for="fileName"&gt;File name&lt;/label&gt;
  &lt;input type="text" id="fileName"&gt;
  &lt;button type="button" id="downloadBtn" class="primary"&gt;Download PDF&lt;/button&gt;
&lt;/section&gt;
</code></pre>
<p>There are a few details worth pointing out here:</p>
<ul>
<li>The password inputs use <code>autocomplete="new-password"</code>, so the browser doesn't fill in a saved login password.</li>
<li>The status lines use <code>aria-live="polite"</code>, so screen readers announce messages such as "The two passwords are different."</li>
<li>The file input is hidden. A regular button opens it, which is easier to style.</li>
</ul>
<p>The CSS is ordinary layout and colors, so it isn't covered here. You can copy it from the demo files.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/6fb5ea62-ebe4-4ab0-8ec6-6b7e87897f23.png" alt="Upload area of the PDF password protector with a Select PDF button" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-opening-the-pdf">Opening the PDF</h2>
<p>First, <code>script.js</code> takes the classes it needs from the two libraries, points PDF.js to its worker, and keeps the app's state in one object:</p>
<pre><code class="language-js">// ---------- Setup ----------
const { PDFDocument, PDFName, PDFNumber, PDFBool, PDFHexString, PDFString,
  PDFDict, PDFArray, PDFRawStream } = PDFLib;

pdfjsLib.GlobalWorkerOptions.workerSrc =
  'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

const state = {
  file: null,     // the File the user picked
  bytes: null,    // its contents as a Uint8Array
  pages: 0,
  result: null    // the protected PDF as a Uint8Array
};

const $ = (id) =&gt; document.getElementById(id);
const uploadArea = $('uploadArea');
const fileInput = $('fileInput');
const fileInfo = $('fileInfo');
const settings = $('settings');
const openPw = $('openPw');
const openPw2 = $('openPw2');
const ownerPw = $('ownerPw');
const strength = $('strength');
const protectBtn = $('protectBtn');
const statusText = $('status');
const result = $('result');
const checks = $('checks');
const fileName = $('fileName');
const downloadBtn = $('downloadBtn');
</code></pre>
<p>The user can pick a file with the button or drop it on the upload area:</p>
<pre><code class="language-js">// ---------- Opening the PDF ----------
$('selectBtn').addEventListener('click', () =&gt; fileInput.click());
fileInput.addEventListener('change', () =&gt; {
  if (fileInput.files[0]) loadFile(fileInput.files[0]);
  fileInput.value = '';
});

uploadArea.addEventListener('dragover', (e) =&gt; {
  e.preventDefault();
  uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', () =&gt; uploadArea.classList.remove('dragover'));
uploadArea.addEventListener('drop', (e) =&gt; {
  e.preventDefault();
  uploadArea.classList.remove('dragover');
  if (e.dataTransfer.files[0]) loadFile(e.dataTransfer.files[0]);
});
</code></pre>
<p>Setting <code>fileInput.value = ''</code> after reading the file lets the user pick the same file again.</p>
<p><code>loadFile</code> checks that the file is a PDF, reads it into a <code>Uint8Array</code>, and tries to load it with PDF-lib:</p>
<pre><code class="language-js">async function loadFile(file) {
  const isPdf = file.type === 'application/pdf' || /\.pdf$/i.test(file.name);
  if (!isPdf) {
    fileInfo.textContent = `${file.name} is not a PDF.`;
    return;
  }

  const bytes = new Uint8Array(await file.arrayBuffer());
  try {
    const doc = await PDFDocument.load(bytes, { updateMetadata: false });
    state.file = file;
    state.bytes = bytes;
    state.pages = doc.getPageCount();
  } catch (err) {
    fileInfo.textContent = /encrypted/i.test(err.message)
      ? `${file.name} already has a password. Unlock it first.`
      : `${file.name} could not be read. The file may be damaged.`;
    return;
  }

  fileInfo.textContent = `${file.name}: ${state.pages} page(s), ${formatSize(file.size)}`;
  settings.hidden = false;
  result.hidden = true;
  openPw.focus();
}

function formatSize(n) {
  if (n &lt; 1024) return n + ' B';
  if (n &lt; 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
  return (n / 1024 / 1024).toFixed(1) + ' MB';
}
</code></pre>
<p>Loading the file here does two jobs. It counts the pages, which you'll use later to check the result, and it catches files that already have a password: PDF-lib throws an error whose message contains "encrypted" when it sees one, so the tool can tell the user to unlock the file first.</p>
<p>The <code>updateMetadata: false</code> option is important here. By default, PDF-lib changes the file's Producer and modification date when it loads a document. You only want to add a password, not rewrite the document's details.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/30adb2ac-f245-4a7b-a32e-2416dcd7158c.png" alt="Message saying the selected PDF already has a password and must be unlocked first" style="display: block;" width="600" height="400" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/aa182706-202a-4dc5-841a-823dcd77efbb.png" alt="PDF loaded with its page count and size, and the password and permission settings shown" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-handling-the-password-fields">Handling the Password Fields</h2>
<p>Each Show button switches its input between <code>password</code> and <code>text</code>, so the user can check what they typed:</p>
<pre><code class="language-js">// ---------- Password fields ----------
document.querySelectorAll('.show-btn').forEach((btn) =&gt; {
  btn.addEventListener('click', () =&gt; {
    const input = $(btn.dataset.target);
    const show = input.type === 'password';
    input.type = show ? 'text' : 'password';
    btn.textContent = show ? 'Hide' : 'Show';
  });
});
</code></pre>
<p>While the user types, a short hint rates the password. It counts how many kinds of characters it contains (lowercase, uppercase, digits, and symbols):</p>
<pre><code class="language-js">openPw.addEventListener('input', () =&gt; {
  const pw = openPw.value;
  const kinds = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/]
    .filter((re) =&gt; re.test(pw)).length;

  if (pw.length &lt; 8) {
    strength.textContent = 'Use at least 8 characters.';
    strength.className = 'hint weak';
  } else if (pw.length &gt;= 12 &amp;&amp; kinds &gt;= 3) {
    strength.textContent = 'Strong password.';
    strength.className = 'hint good';
  } else {
    strength.textContent = 'OK. A longer password with numbers and symbols is stronger.';
    strength.className = 'hint';
  }
});
</code></pre>
<p>This isn't a real strength meter, and it doesn't need to be one. Its job is to push people away from passwords like <code>1234</code>.</p>
<p>Before encrypting, <code>passwordProblem</code> returns a message if something is wrong, or an empty string if everything is fine:</p>
<pre><code class="language-js">function passwordProblem() {
  if (openPw.value.length &lt; 8) return 'The password must have at least 8 characters.';
  if (openPw.value !== openPw2.value) return 'The two passwords are different.';
  if (ownerPw.value &amp;&amp; ownerPw.value === openPw.value) {
    return 'Use a different permissions password, or leave it empty.';
  }
  return '';
}
</code></pre>
<p>The last rule is there because if both passwords are the same, the permissions are pointless: anyone who can open the file can also change them.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/46301cdb-393f-4238-b237-88d96a359bac.png" alt="Password fields with a red border and the message that the two passwords are different" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-helpers-for-bytes-and-web-crypto">Helpers for Bytes and Web Crypto</h2>
<p>Encryption works on bytes, so you need a few small helpers. <code>concat</code> joins byte arrays, <code>randomBytes</code> gets secure random bytes, and <code>toHex</code> turns bytes into a hex string for PDF-lib:</p>
<pre><code class="language-js">// ---------- Byte helpers ----------
function concat(...parts) {
  const out = new Uint8Array(parts.reduce((n, p) =&gt; n + p.length, 0));
  let offset = 0;
  for (const p of parts) {
    out.set(p, offset);
    offset += p.length;
  }
  return out;
}

const randomBytes = (n) =&gt; crypto.getRandomValues(new Uint8Array(n));

function toHex(bytes) {
  return Array.from(bytes, (b) =&gt; b.toString(16).padStart(2, '0')).join('');
}

// PDF 2.0 passwords are UTF-8, normalized, and at most 127 bytes long
function passwordBytes(text) {
  return new TextEncoder().encode(text.normalize('NFKC')).slice(0, 127);
}
</code></pre>
<p><code>passwordBytes</code> prepares a password the way PDF 2.0 expects: as UTF-8, at most 127 bytes long. The <code>normalize('NFKC')</code> call makes sure that characters which look the same are stored the same way, so for example <code>é</code> typed on two different keyboards gives the same bytes. The specification uses a slightly stricter process called SASLprep, but NFKC covers the cases people actually come across.</p>
<p>Next come the Web Crypto helpers:</p>
<pre><code class="language-js">// ---------- Web Crypto helpers ----------
async function digest(algorithm, data) {
  return new Uint8Array(await crypto.subtle.digest(algorithm, data));
}

// AES-CBC with PKCS#7 padding (what PDF uses for strings and streams)
async function aesEncrypt(keyBytes, iv, data) {
  const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-CBC', false, ['encrypt']);
  return new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-CBC', iv }, key, data));
}

// AES-CBC without padding: the input is already a multiple of 16 bytes,
// so we keep the first data.length bytes and drop the extra padding block
async function aesEncryptNoPad(keyBytes, iv, data) {
  return (await aesEncrypt(keyBytes, iv, data)).slice(0, data.length);
}
</code></pre>
<p>Web Crypto's AES-CBC always adds PKCS#7 padding. PDF needs padding for strings and streams, so <code>aesEncrypt</code> is perfect for them. But a few values in the encryption dictionary must be encrypted <em>without</em> padding. Their input is always a multiple of 16 bytes, so the first <code>data.length</code> bytes of the output are exactly what you need, and <code>aesEncryptNoPad</code> simply drops the extra padding block.</p>
<h2 id="heading-hashing-the-password-the-pdf-20-way">Hashing the Password the PDF 2.0 Way</h2>
<p>AES-256 PDFs don't use a plain SHA-256 of the password. They use a slower hash (Algorithm 2.B in ISO 32000-2) that makes guessing passwords expensive:</p>
<pre><code class="language-js">// ---------- The PDF 2.0 password hash ----------
// ISO 32000-2, Algorithm 2.B: SHA-256, then at least 64 rounds of
// AES-128 + SHA-256/384/512 to make guessing passwords slow
async function hashPassword(password, salt, userKey) {
  let k = await digest('SHA-256', concat(password, salt, userKey));
  let e = new Uint8Array([0]);
  let round = 0;

  while (round &lt; 64 || e[e.length - 1] &gt; round - 32) {
    const block = concat(password, k, userKey);
    const k1 = new Uint8Array(block.length * 64);
    for (let i = 0; i &lt; 64; i++) k1.set(block, i * block.length);

    e = await aesEncryptNoPad(k.slice(0, 16), k.slice(16, 32), k1);

    let sum = 0;
    for (let i = 0; i &lt; 16; i++) sum += e[i];
    const hash = ['SHA-256', 'SHA-384', 'SHA-512'][sum % 3];
    k = await digest(hash, e);
    round++;
  }
  return k.slice(0, 32);
}
</code></pre>
<p>Here's what happens:</p>
<ol>
<li>Start with a SHA-256 hash of the password, a salt, and (for the owner password) the 48-byte <code>U</code> value.</li>
<li>Repeat the password, the current hash, and the extra data 64 times, and encrypt that block with AES-128. The key and IV come from the current hash.</li>
<li>Add up the first 16 bytes of the result. The remainder after dividing by 3 decides whether the next hash is SHA-256, SHA-384, or SHA-512.</li>
<li>Do this at least 64 times, then keep going until the last byte of the encrypted block is no bigger than the round number minus 32.</li>
<li>The first 32 bytes of the final hash are the result.</li>
</ol>
<p>Because the number of rounds and the hash function depend on the data, an attacker can't easily speed this up with special hardware. A browser still finishes it in a few milliseconds.</p>
<h2 id="heading-turning-permissions-into-a-number">Turning Permissions into a Number</h2>
<p>The permissions are stored in <code>/P</code> as a 32-bit number, where each bit allows one action:</p>
<pre><code class="language-js">// ---------- Permissions ----------
// Bit positions from the PDF specification (bit 1 is the lowest bit)
const PERM = {
  print: 1 &lt;&lt; 2,          // bit 3
  modify: 1 &lt;&lt; 3,         // bit 4
  copy: 1 &lt;&lt; 4,           // bit 5
  annotate: 1 &lt;&lt; 5,       // bit 6
  fillForms: 1 &lt;&lt; 8,      // bit 9
  accessibility: 1 &lt;&lt; 9,  // bit 10
  assemble: 1 &lt;&lt; 10,      // bit 11
  printHigh: 1 &lt;&lt; 11      // bit 12
};

function permissionFlags({ print, copy, edit }) {
  let p = 0xFFFFF0C0;                    // reserved bits that must be 1
  p |= PERM.accessibility;               // always allow screen readers
  if (print) p |= PERM.print | PERM.printHigh;
  if (copy) p |= PERM.copy;
  if (edit) p |= PERM.modify | PERM.annotate | PERM.fillForms | PERM.assemble;
  return p | 0;                          // as a signed 32-bit number
}
</code></pre>
<p>The starting value <code>0xFFFFF0C0</code> sets the bits that the specification says must always be 1. The function then turns on bit 10 (text extraction for accessibility) so screen readers keep working, and adds the bits for each option the user ticked:</p>
<table>
<thead>
<tr>
<th>Option in the tool</th>
<th>Bits turned on</th>
</tr>
</thead>
<tbody><tr>
<td>Print</td>
<td>3 (print) and 12 (high-quality print)</td>
</tr>
<tr>
<td>Copy text and images</td>
<td>5</td>
</tr>
<tr>
<td>Edit, comment, and fill forms</td>
<td>4, 6, 9 and 11</td>
</tr>
</tbody></table>
<p>The final <code>p | 0</code> converts the number to a signed 32-bit integer. With high bits set, it's negative, and that's normal: most PDFs show something like <code>/P -1324</code>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/d82f0a23-bfde-43f2-9457-bad333438ac0.png" alt="Open password marked as strong, with Print allowed and copying and editing turned off" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-building-the-encryption-keys">Building the Encryption Keys</h2>
<p>Now you can build the values that go into the encryption dictionary:</p>
<pre><code class="language-js">// ---------- Building the encryption dictionary values ----------
async function makeKeys(userText, ownerText, p) {
  const fileKey = randomBytes(32);       // the key that encrypts the document
  const user = passwordBytes(userText);
  const owner = passwordBytes(ownerText);
  const none = new Uint8Array(0);
  const zeroIv = new Uint8Array(16);

  // U and UE: check the open password and unlock the file key with it
  const uValidation = randomBytes(8);
  const uKeySalt = randomBytes(8);
  const U = concat(await hashPassword(user, uValidation, none), uValidation, uKeySalt);
  const UE = await aesEncryptNoPad(await hashPassword(user, uKeySalt, none), zeroIv, fileKey);

  // O and OE: the same for the permissions password (they also depend on U)
  const oValidation = randomBytes(8);
  const oKeySalt = randomBytes(8);
  const O = concat(await hashPassword(owner, oValidation, U), oValidation, oKeySalt);
  const OE = await aesEncryptNoPad(await hashPassword(owner, oKeySalt, U), zeroIv, fileKey);

  // Perms: the permissions, encrypted with the file key so they can't be edited
  const perms = new Uint8Array(16);
  new DataView(perms.buffer).setInt32(0, p, true);   // little-endian
  perms.set([0xFF, 0xFF, 0xFF, 0xFF], 4);
  perms.set([0x54, 0x61, 0x64, 0x62], 8);            // 'T' (encrypt metadata), 'a', 'd', 'b'
  perms.set(randomBytes(4), 12);
  const Perms = await aesEncryptNoPad(fileKey, zeroIv, perms);

  return { fileKey, U, UE, O, OE, Perms };
}
</code></pre>
<p>Let's go through them:</p>
<ul>
<li><code>fileKey</code> is 32 random bytes. It encrypts the whole document.</li>
<li><code>U</code> (48 bytes) lets a reader check the user password. It's the password hash plus two 8-byte random salts: a <em>validation salt</em> used to check the password, and a <em>key salt</em> used to unlock the key.</li>
<li><code>UE</code> is the file key, encrypted with a hash of the user password and the key salt. When someone types the right password, the reader rebuilds this hash and decrypts the file key.</li>
<li><code>O</code> and <code>OE</code> do the same for the owner password. Their hashes also include <code>U</code>, which ties the two passwords to the same file.</li>
<li><code>Perms</code> is the permission number plus a few check bytes, encrypted with the file key. A reader decrypts it and compares it with <code>/P</code>, so someone who edits <code>/P</code> in a text editor gets caught.</li>
</ul>
<p>Two rules from the specification show up here:</p>
<ul>
<li><code>UE</code>, <code>OE</code> and <code>Perms</code> are encrypted without padding and with an IV of zeros. (<code>Perms</code> is a single 16-byte block, so AES-CBC with a zero IV gives the same result as the AES-ECB mode the specification describes.)</li>
<li>The byte <code>T</code> in <code>Perms</code> means "the metadata is encrypted too", which must match <code>/EncryptMetadata true</code> in the dictionary.</li>
</ul>
<h2 id="heading-encrypting-every-string-and-stream">Encrypting Every String and Stream</h2>
<p>With the file key ready, you can encrypt the document. For AES-256, each string or stream is encrypted with the file key and a new random 16-byte IV, and the IV is stored in front of the encrypted bytes:</p>
<pre><code class="language-js">// ---------- Encrypting the objects ----------
// With AES-256 every string and stream is encrypted with the file key
// and a fresh random IV, which is stored in front of the encrypted data
async function encryptData(fileKey, data) {
  const iv = randomBytes(16);
  return concat(iv, await aesEncrypt(fileKey, iv, data));
}

async function encryptStrings(value, fileKey) {
  if (value instanceof PDFDict) {
    for (const [key, item] of value.entries()) {
      const replacement = await encryptValue(item, fileKey);
      if (replacement) value.set(key, replacement);
    }
  } else if (value instanceof PDFArray) {
    for (let i = 0; i &lt; value.size(); i++) {
      const replacement = await encryptValue(value.get(i), fileKey);
      if (replacement) value.set(i, replacement);
    }
  }
}

async function encryptValue(item, fileKey) {
  if (item instanceof PDFString || item instanceof PDFHexString) {
    return PDFHexString.of(toHex(await encryptData(fileKey, item.asBytes())));
  }
  await encryptStrings(item, fileKey);   // nested dictionaries and arrays
  return null;
}

async function encryptObjects(context, fileKey) {
  const objects = context.enumerateIndirectObjects();
  for (const [ref, object] of objects) {
    if (object instanceof PDFRawStream) {
      const type = object.dict.get(PDFName.of('Type'));
      if (type === PDFName.of('XRef')) {     // old cross-reference streams
        context.delete(ref);
        continue;
      }
      await encryptStrings(object.dict, fileKey);
      const data = await encryptData(fileKey, object.contents);
      context.assign(ref, PDFRawStream.of(object.dict, data));
    } else {
      await encryptStrings(object, fileKey);
    }
  }
}
</code></pre>
<p><code>encryptObjects</code> goes through every object in the file:</p>
<ul>
<li><strong>Streams</strong> (<code>PDFRawStream</code>): their data is replaced with the encrypted version. PDF-lib updates the <code>/Length</code> entry for you when it saves.</li>
<li><strong>Dictionaries and arrays</strong>: <code>encryptStrings</code> walks through them and replaces every string with an encrypted hex string. Nested dictionaries and arrays are handled by calling the function again.</li>
<li><strong>Cross-reference streams</strong> (<code>/Type /XRef</code>) are deleted. They describe where objects sit in the old file, PDF-lib writes a new cross-reference table anyway, and they must never be encrypted.</li>
</ul>
<p>PDF-lib has two string types: <code>PDFString</code> for literal strings like <code>(Hello)</code> and <code>PDFHexString</code> for hex strings like <code>&lt;48656C6C6F&gt;</code>. Both have an <code>asBytes()</code> method that returns the real bytes, which is what you encrypt.</p>
<p>The stream data is encrypted <em>as it is in the file</em>, which is usually already compressed. That's the correct order: a reader decrypts first, then decompresses.</p>
<h2 id="heading-writing-the-protected-pdf">Writing the Protected PDF</h2>
<p><code>protectPdf</code> puts it all together:</p>
<pre><code class="language-js">// ---------- Protecting the PDF ----------
async function protectPdf(bytes, options) {
  const doc = await PDFDocument.load(bytes, { updateMetadata: false });
  const context = doc.context;

  const p = permissionFlags(options);
  const ownerText = options.ownerPw || toHex(randomBytes(16));
  const keys = await makeKeys(options.openPw, ownerText, p);

  // 1. Encrypt every string and stream that is already in the file
  await encryptObjects(context, keys.fileKey);

  // 2. Add the encryption dictionary (it must NOT be encrypted itself)
  const hex = (b) =&gt; PDFHexString.of(toHex(b));
  const stdCF = context.obj({ AuthEvent: 'DocOpen', CFM: 'AESV3', Length: 32 });
  const encrypt = context.obj({
    Filter: 'Standard',
    V: 5,
    R: 6,
    Length: 256,
    CF: context.obj({ StdCF: stdCF }),
    StmF: 'StdCF',
    StrF: 'StdCF',
    P: PDFNumber.of(p),
    EncryptMetadata: PDFBool.True
  });
  encrypt.set(PDFName.of('U'), hex(keys.U));
  encrypt.set(PDFName.of('UE'), hex(keys.UE));
  encrypt.set(PDFName.of('O'), hex(keys.O));
  encrypt.set(PDFName.of('OE'), hex(keys.OE));
  encrypt.set(PDFName.of('Perms'), hex(keys.Perms));

  // 3. Point the trailer at it and give the file an ID
  context.trailerInfo.Encrypt = context.register(encrypt);
  const id = hex(randomBytes(16));
  context.trailerInfo.ID = context.obj([id, id]);

  // Object streams would hide objects from step 1, so write plain objects
  return doc.save({ useObjectStreams: false });
}
</code></pre>
<p>The steps are:</p>
<ol>
<li>Encrypt the existing objects: This must happen <em>before</em> you add the encryption dictionary, because the dictionary itself must stay readable.</li>
<li>Create the encryption dictionary: <code>context.obj()</code> turns plain strings into PDF names, so <code>Filter: 'Standard'</code> becomes <code>/Filter /Standard</code>. <code>V 5</code> and <code>R 6</code> mean AES-256 from PDF 2.0, and the crypt filter <code>StdCF</code> with <code>CFM AESV3</code> tells the reader to use AES-256 for both streams (<code>StmF</code>) and strings (<code>StrF</code>).</li>
<li>Update the trailer: The trailer gets an <code>/Encrypt</code> reference and a new <code>/ID</code>. PDF-lib writes <code>trailerInfo</code> into the trailer for you, and it doesn't encrypt the ID.</li>
</ol>
<p>If the user leaves the permissions password empty, the tool uses 16 random bytes as the owner password. Nobody knows it, so nobody can lift the restrictions. (If you used an empty owner password instead, any PDF program could remove them.)</p>
<p>Finally, the file is saved with <code>useObjectStreams: false</code>. An object stream packs many objects into one compressed stream. Strings inside an object stream must not be encrypted on their own, because the whole stream is encrypted. You already encrypted every string individually, so writing plain objects keeps the file correct.</p>
<p>Here's what the encryption dictionary looks like in the saved file:</p>
<pre><code class="language-text">&lt;&lt;
/Filter /Standard /V 5 /R 6 /Length 256
/CF &lt;&lt; /StdCF &lt;&lt; /AuthEvent /DocOpen /CFM /AESV3 /Length 32 &gt;&gt; &gt;&gt;
/StmF /StdCF /StrF /StdCF
/P -1324 /EncryptMetadata true
/U &lt;...48 bytes...&gt; /UE &lt;...32 bytes...&gt;
/O &lt;...48 bytes...&gt; /OE &lt;...32 bytes...&gt;
/Perms &lt;...16 bytes...&gt;
&gt;&gt;
</code></pre>
<h2 id="heading-checking-the-result-with-pdfjs">Checking the Result with PDF.js</h2>
<p>Encryption bugs are easy to make and hard to notice. A file might open in one reader and fail in another, or it might not be encrypted at all. So the tool opens its own output with PDF.js before offering the download:</p>
<pre><code class="language-js">// ---------- Checking the result with PDF.js ----------
async function verify(bytes, password) {
  const results = [];

  // 1. Without a password, PDF.js must ask for one
  try {
    const doc = await pdfjsLib.getDocument({ data: bytes.slice() }).promise;
    await doc.destroy();
    results.push([false, 'The file opened without a password']);
  } catch (err) {
    results.push([err.name === 'PasswordException', 'Asks for a password when opened']);
  }

  // 2. With the password, it must open and have every page
  try {
    const doc = await pdfjsLib.getDocument({ data: bytes.slice(), password }).promise;
    results.push([doc.numPages === state.pages, `Opens with your password (${doc.numPages} page(s))`]);
    await doc.destroy();
  } catch (err) {
    results.push([false, 'Could not open it with your password']);
  }
  return results;
}
</code></pre>
<p>There are two checks:</p>
<ol>
<li>Opening the file <strong>without</strong> a password must fail with a <code>PasswordException</code>. If it opens, the file isn't protected.</li>
<li>Opening it <strong>with</strong> the password must work, and it must have the same number of pages as the original.</li>
</ol>
<p><code>bytes.slice()</code> passes a copy, because PDF.js moves the buffer to its worker and the original array would become empty.</p>
<h2 id="heading-connecting-the-button">Connecting the Button</h2>
<p>The click handler checks the passwords, runs <code>protectPdf</code>, runs the checks, and shows the result:</p>
<pre><code class="language-js">// ---------- Running everything ----------
protectBtn.addEventListener('click', async () =&gt; {
  const problem = passwordProblem();
  openPw.setAttribute('aria-invalid', String(openPw.value.length &lt; 8));
  openPw2.setAttribute('aria-invalid', String(openPw.value !== openPw2.value));
  if (problem) {
    statusText.textContent = problem;
    statusText.className = 'status error';
    return;
  }

  protectBtn.disabled = true;
  statusText.className = 'status';
  statusText.textContent = 'Encrypting…';
  try {
    const options = {
      openPw: openPw.value,
      ownerPw: ownerPw.value,
      print: $('allowPrint').checked,
      copy: $('allowCopy').checked,
      edit: $('allowEdit').checked
    };
    state.result = await protectPdf(state.bytes, options);

    statusText.textContent = 'Checking the protected file…';
    const results = await verify(state.result, options.openPw);
    checks.innerHTML = '';
    for (const [ok, text] of results) {
      const li = document.createElement('li');
      li.textContent = (ok ? '✅ ' : '❌ ') + text;
      checks.appendChild(li);
    }
    const sizeLi = document.createElement('li');
    sizeLi.textContent = 'Size: ' + formatSize(state.result.length);
    checks.appendChild(sizeLi);

    fileName.value = state.file.name.replace(/\.pdf$/i, '') + '-protected.pdf';
    statusText.textContent = '';
    result.hidden = false;
    result.scrollIntoView({ behavior: 'smooth' });
  } catch (err) {
    console.error(err);
    statusText.textContent = 'Something went wrong: ' + err.message;
    statusText.className = 'status error';
  } finally {
    protectBtn.disabled = false;
  }
});
</code></pre>
<p>The button is disabled while the work runs, so a double click doesn't start two encryptions. The <code>finally</code> block turns it back on, even if something fails.</p>
<h2 id="heading-renaming-and-downloading">Renaming and Downloading</h2>
<p>The result panel suggests a name such as <code>report-protected.pdf</code>. When the user clicks Download PDF, the name is cleaned and the file is saved:</p>
<pre><code class="language-js">// ---------- Downloading ----------
downloadBtn.addEventListener('click', () =&gt; {
  let name = fileName.value.trim().replace(/[\\/:*?"&lt;&gt;|]+/g, '-') || 'protected.pdf';
  if (!/\.pdf$/i.test(name)) name += '.pdf';

  const blob = new Blob([state.result], { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = name;
  a.click();
  setTimeout(() =&gt; URL.revokeObjectURL(url), 60000);
});
</code></pre>
<p>The regular expression replaces characters that Windows doesn't allow in file names. The object URL is released after a minute, which gives the browser plenty of time to start the download.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/a0e84770-9203-4b41-a7b2-d981ca9a5110.png" alt="Result panel showing that the PDF asks for a password and opens with it, plus file name and Download button" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-testing-the-file-outside-the-browser">Testing the File Outside the Browser</h2>
<p>A PDF that only opens in your own tool isn't very useful. So you'll want to test the output in other software too.</p>
<p><a href="https://qpdf.readthedocs.io/">qpdf</a> is a free command-line tool that reads encrypted PDFs strictly. These commands check the file and show its encryption settings:</p>
<pre><code class="language-bash"># Should say: "invalid password"
qpdf --check report-protected.pdf

# Should say: "No syntax or stream encoding errors found"
qpdf --check --password='your password' report-protected.pdf

# Shows R = 6, AESv3 and each permission
qpdf --show-encryption --password='your password' report-protected.pdf
</code></pre>
<p>For the version in this article, <code>qpdf --show-encryption</code> prints:</p>
<pre><code class="language-text">R = 6
P = -1324
User password = Correct-Horse-42
Supplied password is user password
extract for accessibility: allowed
extract for any purpose: allowed
print low resolution: allowed
print high resolution: allowed
modify document assembly: not allowed
modify forms: not allowed
modify annotations: not allowed
modify other: not allowed
modify anything: not allowed
stream encryption method: AESv3
string encryption method: AESv3
file encryption method: AESv3
</code></pre>
<p>Also open the file in your browser's PDF viewer and in Adobe Acrobat Reader. Both should ask for the password, and Acrobat's Document Properties &gt; Security tab should show the restrictions you chose.</p>
<h2 id="heading-demo-how-the-protect-pdf-tool-works">Demo: How the Protect PDF Tool Works</h2>
<p>Here's the workflow in the full tool on All In One Tools.</p>
<h3 id="heading-step-1-add-your-pdf">Step 1: Add Your PDF</h3>
<p>Drop a PDF on the page or click Select PDF. The pages appear as previews, so you can check that it's the right file before you protect it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/584913da-37cf-4a9e-ba97-aeed28b65e09.png" alt="Uploaded PDF with its file name, size and a large preview of the page" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-step-2-choose-the-passwords-and-limits">Step 2: Choose the Passwords and Limits</h3>
<p>Type the open password twice. If you want to limit printing, copying or editing, turn on the limits and set a separate permissions password. AES-256 is selected by default.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/ebb38969-3a0b-40ca-a380-d2959e0827fd.png" alt="Password settings with AES-256 selected, open password, permissions password and printing and copying limits" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-step-3-check-and-download">Step 3: Check and Download</h3>
<p>The tool opens the protected file in the browser, checks that it asks for a password, accepts yours and refuses a wrong one, and then shows a preview. Rename the file if you like and click Download PDF.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/dc2a1ce7-bbdc-45cd-9c30-865adcecd01e.png" alt="Protected PDF preview with the in-browser checks passed and a Download PDF button" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-performance-tips">Performance Tips</h2>
<p>There are a few things you can do to make sure the tool performs well.</p>
<p>First, process objects one at a time. The code <code>await</code>s each encryption in turn. That keeps memory use low, because only one stream is copied at a time. For files with thousands of small objects you can encrypt in batches of, say, 50 with <code>Promise.all</code> to go faster.</p>
<p>Second, expect the file to grow a little. Each string and stream gains a 16-byte IV and up to 16 bytes of padding, and saving without object streams makes the cross-reference table bigger. A 4 KB file might become 8 KB, while a 5 MB file grows by only a few kilobytes.</p>
<p>Next, don't encrypt twice for the check. The tool verifies the exact bytes it's going to download. Don't run <code>protectPdf</code> again for the download, or the file will get a new random key and the check will no longer apply to it.</p>
<p>Finally, release memory after big files. Call <code>doc.destroy()</code> on PDF.js documents when you're done, as <code>verify</code> does. Otherwise the worker keeps the parsed file in memory.</p>
<h2 id="heading-common-mistakes">Common Mistakes</h2>
<p>There are also a few things to avoid when you're building this tool.</p>
<p>First, don't open the page over plain <code>http://</code>. <code>crypto.subtle</code> only exists in secure contexts. On <code>http://example.com</code> or a <code>file://</code> path, the code fails with "Cannot read properties of undefined (reading 'digest')". Use <code>https://</code> or <code>localhost</code>.</p>
<p>Don't use <code>Math.random()</code> for keys or salts. It isn't designed for security, and its output can be predicted. Always use <code>crypto.getRandomValues()</code>.</p>
<p>You also shouldn't encrypt the encryption dictionary. If the <code>/U</code>, <code>/O</code> or <code>/Perms</code> strings get encrypted, no reader can check a password. Encrypt the document first, then add the dictionary.</p>
<p>Avoid saving with object streams. PDF-lib saves with object streams by default. With encryption, strings inside them would be encrypted twice. Pass <code>useObjectStreams: false</code>.</p>
<p>Also, don't forget <code>slice()</code> when passing bytes to PDF.js. PDF.js transfers the buffer to its worker. Afterwards your original <code>Uint8Array</code> is empty, and the download is a 0-byte file.</p>
<p>Don't treat permissions as security. Restricting printing and copying is useful for honest readers, but it isn't protection. If the content must stay private, the open password is what matters.</p>
<p>Don't protect a digitally signed PDF. Encrypting changes every byte that the signature covers, so the signature becomes invalid. Add the password first, then sign the protected file.</p>
<p>And finally, make sure you and your users don't lose the password. With AES-256 there's no back door and no "forgot password" button. Tell your users to store the password somewhere safe.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you built a browser-based tool that adds a password to a PDF with AES-256 encryption.</p>
<p>You learned how PDF encryption is organized, how to hash a password with the PDF 2.0 algorithm, how to build the <code>U</code>, <code>UE</code>, <code>O</code>, <code>OE</code> and <code>Perms</code> values with the Web Crypto API, how to encrypt every string and stream with PDF-lib, and how to check the result with PDF.js and qpdf.</p>
<p>All of it runs in the browser, so the document stays on the user's device.</p>
<p>You can try the full version of this tool, with page previews, AES-128 and RC4 options for very old readers, low-resolution-only printing, and more detailed permission choices at <a href="https://allinonetools.net/protect-pdf/">Protect PDF</a>.</p>
<p>If you want to extend your version, here are some ideas:</p>
<ul>
<li>Add an Unlock tool that removes the password when the user knows it</li>
<li>Let users choose "print in low resolution only" (bit 3 without bit 12)</li>
<li>Protect several PDFs with the same password in one go</li>
<li>Show a warning when the PDF has a digital signature</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Encrypt PII in Data Pipelines While Keeping It Searchable ]]>
                </title>
                <description>
                    <![CDATA[ At Intuit, my team built a data pipeline that processed TurboTax e-filing data. This data needed to be made available for dashboards, analytics, and other downstream use cases. One of the biggest chal ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-encrypt-pii-in-data-pipelines-while-keeping-it-searchable/</link>
                <guid isPermaLink="false">6ac4810141f9b6b6ff5bf1cd</guid>
                
                    <category>
                        <![CDATA[ dataengineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ datasecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #DataPipelines ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PII ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hmac ]]>
                    </category>
                
                    <category>
                        <![CDATA[ KMS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lakshmi Mahabaleshwara ]]>
                </dc:creator>
                <pubDate>Tue, 06 Oct 2026 05:02:57 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/b9b99f84-c0c8-46a0-b217-0b2e598c8ac1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>At Intuit, my team built a data pipeline that processed TurboTax e-filing data. This data needed to be made available for dashboards, analytics, and other downstream use cases.</p>
<p>One of the biggest challenges was protecting <strong>Personally Identifiable Information (PII)</strong> such as Social Security Numbers (SSNs).</p>
<p>SSNs are highly sensitive and must be protected at every stage of the data pipeline. At the same time, analytics teams sometimes need to perform legitimate business operations such as identifying records associated with a particular customer or performing exact-match lookups.</p>
<p>So how do you protect sensitive data while still allowing controlled equality searches without exposing the plaintext?</p>
<p>In this article, I'll explain the encryption concepts behind this problem, including:</p>
<ul>
<li><p>Probabilistic vs. deterministic encryption</p>
</li>
<li><p>Equality searches on encrypted data</p>
</li>
<li><p>Base keys and derived keys</p>
</li>
<li><p>Key separation</p>
</li>
<li><p>Local vs. remote cryptographic operations</p>
</li>
<li><p>Tokenization</p>
</li>
<li><p>The security trade-offs involved in making encrypted data searchable</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-why-encrypt-pii">Why Encrypt PII?</a></p>
</li>
<li><p><a href="#heading-aes-advanced-encryption-standard">AES: Advanced Encryption Standard</a></p>
</li>
<li><p><a href="#heading-probabilistic-encryption">Probabilistic Encryption</a></p>
</li>
<li><p><a href="#heading-deterministic-encryption">Deterministic Encryption</a></p>
<ul>
<li><a href="#heading-the-security-trade-off">The Security Trade-off</a></li>
</ul>
</li>
<li><p><a href="#heading-base-keys-and-derived-keys">Base Keys and Derived Keys</a></p>
<ul>
<li><p><a href="#heading-key-derivation-with-hkdf">Key Derivation with HKDF</a></p>
</li>
<li><p><a href="#heading-where-does-the-master-key-live">Where Does the Master Key Live?</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-local-cryptographic-operations">Local Cryptographic Operations</a></p>
</li>
<li><p><a href="#heading-remote-cryptographic-operations">Remote Cryptographic Operations</a></p>
</li>
<li><p><a href="#heading-deterministic-encryption-vs-hmac">Deterministic Encryption vs HMAC</a></p>
</li>
<li><p><a href="#heading-tokenization">Tokenization</a></p>
</li>
<li><p><a href="#heading-comparing-the-approaches">Comparing the Approaches</a></p>
</li>
<li><p><a href="#heading-access-control-still-matters">Access Control Still Matters</a></p>
</li>
<li><p><a href="#heading-what-we-learned-from-the-data-pipeline">What We Learned from the Data Pipeline</a></p>
</li>
<li><p><a href="#heading-key-takeaways">Key Takeaways</a></p>
</li>
</ul>
<h2 id="heading-why-encrypt-pii">Why Encrypt PII?</h2>
<p>PII such as SSNs, email addresses, phone numbers, and financial information is highly sensitive.</p>
<p>If you store plaintext PII directly in a data lake or database, a storage-layer compromise could expose large amounts of sensitive information.</p>
<p>Encryption provides protection by transforming plaintext into ciphertext:</p>
<pre><code class="language-plaintext">Plaintext
   │
   ▼
Encryption + Key
   │
   ▼
Ciphertext
</code></pre>
<pre><code class="language-plaintext">SSN:        111-22-3333

Encrypted:  8f92a7c1...
</code></pre>
<p>Without the appropriate cryptographic key, the ciphertext shouldn't reveal the original value.</p>
<p>For a data platform, though, encryption introduces another requirement.</p>
<p>Suppose an analytics application needs to find records for:</p>
<pre><code class="language-plaintext">SSN = 111-22-3333
</code></pre>
<p>If the SSN is encrypted, we don't want the application to decrypt the entire dataset just to perform an equality lookup.</p>
<p>This is where <strong>deterministic encryption</strong> becomes useful.</p>
<h2 id="heading-aes-advanced-encryption-standard">AES: Advanced Encryption Standard</h2>
<p>Before looking at probabilistic and deterministic encryption, let's briefly understand <strong>AES (Advanced Encryption Standard)</strong>.</p>
<p>AES (Advanced Encryption Standard) is a widely used symmetric encryption algorithm for protecting sensitive data. It uses a secret key to transform plaintext into ciphertext, and the same key is used to decrypt the ciphertext back into the original plaintext.</p>
<p>The diagram below illustrates this basic process: the plaintext is encrypted using AES and a secret key to produce ciphertext. The ciphertext can then be decrypted using the same secret key to recover the original plaintext.</p>
<p>In real-world systems, AES is used with different encryption modes and constructions depending on the security and application requirements. The way randomness, initialization vectors, or nonces are handled affects properties such as whether repeated encryption of the same plaintext produces the same or different ciphertext.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/6d5b1313-1f73-460c-ac13-5e47f9661c6a.png" alt="Diagram showing symmetric AES encryption: plaintext is encrypted with a secret key to produce ciphertext, which can then be decrypted using the same key to recover the original plaintext." style="display: block;" width="1774" height="887" loading="lazy">

<p>For example:</p>
<pre><code class="language-plaintext">Plaintext:   111-22-3333
Key:         key1


        ↓ AES encryption


Ciphertext:  8f92a7c1...
</code></pre>
<p>AES is widely used to protect sensitive data such as PII. But how encryption behaves depends on how the encryption is constructed and used. One important distinction is whether randomness is used during encryption.</p>
<p>This brings us to <strong>probabilistic encryption</strong>.</p>
<h2 id="heading-probabilistic-encryption">Probabilistic Encryption</h2>
<p>Probabilistic encryption introduces randomness during encryption.</p>
<p>This means that even when we encrypt the <strong>same plaintext with the same key</strong>, the resulting ciphertext can differ each time.</p>
<pre><code class="language-plaintext">Encrypt("ABC", key1) → qwoeoewowe
Encrypt("ABC", key1) → cXcslslsd
Encrypt("ABC", key1) → fjkdfdfd
</code></pre>
<p>Although the input is the same:</p>
<pre><code class="language-plaintext">ABC
</code></pre>
<p>the encrypted values are different.</p>
<p>This randomness is intentional. It prevents someone looking at encrypted data from easily determining that two ciphertexts represent the same underlying value.</p>
<p>For example:</p>
<pre><code class="language-plaintext">Record 1 → qwoeoewowe
Record 2 → cXcslslsd
Record 3 → fjkdfdfd
</code></pre>
<p>An observer can't simply compare the ciphertexts and conclude that the records contain the same plaintext.</p>
<p>This makes probabilistic encryption a strong choice when <strong>confidentiality is the primary requirement</strong>.</p>
<h3 id="heading-advantages">Advantages</h3>
<ul>
<li><p>Provides strong protection against equality-pattern analysis</p>
</li>
<li><p>Makes repeated plaintext values look different after encryption</p>
</li>
<li><p>Suitable when encrypted values don't need to be directly compared</p>
</li>
</ul>
<h3 id="heading-limitation">Limitation</h3>
<p>The randomness that improves security also creates a challenge for analytics.</p>
<p>Suppose we want to find all records containing:</p>
<pre><code class="language-plaintext">SSN = 111-22-3333
</code></pre>
<p>If the same SSN was encrypted multiple times, we could have:</p>
<pre><code class="language-plaintext">111-22-3333 → X8a91...
111-22-3333 → P72k4...
111-22-3333 → M91q2...
</code></pre>
<p>The encrypted values are different, even though the underlying SSN is the same.</p>
<p>Therefore, a simple equality query such as:</p>
<pre><code class="language-plaintext">WHERE encrypted_ssn = encrypted_search_value
</code></pre>
<p>wouldn't work reliably.</p>
<p>This creates an important trade-off for data platforms: randomness provides stronger protection against pattern leakage, but it makes equality-based searching more difficult.</p>
<p>When analytics requires exact-match searches on sensitive fields, we need a different approach: <strong>deterministic encryption</strong>.</p>
<h2 id="heading-deterministic-encryption">Deterministic Encryption</h2>
<p><strong>Deterministic encryption</strong> is designed so that the same plaintext, encrypted under the same key and encryption context, produces the same ciphertext.</p>
<p>For Example:</p>
<pre><code class="language-plaintext">Encrypt("ABC", key)
    → adsfffdfd

Encrypt("ABC", key)
    → adsfffdfd

Encrypt("ABC", key)
    → adsfffdfd
</code></pre>
<p>The important property is:</p>
<pre><code class="language-plaintext">Same plaintext
      ↓
Same key + context
      ↓
Same ciphertext
</code></pre>
<p>This allows equality matching.</p>
<p>For example:</p>
<pre><code class="language-plaintext">SELECT *
FROM customer_data
WHERE encrypted_ssn = EncryptDeterministically(
    '111-22-3333',
    encryption_key
);
</code></pre>
<p>The application can generate the same ciphertext for the search value and compare it against the stored ciphertext.</p>
<h3 id="heading-the-security-trade-off">The Security Trade-off</h3>
<p>Deterministic encryption provides searchability, but that searchability comes at a cost.</p>
<p>Consider this dataset:</p>
<pre><code class="language-plaintext">Ciphertext
-----------
A9F82...
A9F82...
B72AC...
A9F82...
C81DE...
</code></pre>
<p>An attacker may not know that:</p>
<pre><code class="language-plaintext">A9F82... = 111-22-3333
</code></pre>
<p>But they can determine that the same plaintext occurs three times.</p>
<p>In other words, deterministic encryption leaks <strong>equality patterns</strong>.</p>
<p>If an attacker has additional information about the underlying dataset, they may be able to use those patterns to infer plaintext values.</p>
<p>This is particularly important for fields with a small number of possible values, such as:</p>
<ul>
<li><p>State codes</p>
</li>
<li><p>Boolean values</p>
</li>
<li><p>Gender categories</p>
</li>
<li><p>Small categorical fields</p>
</li>
<li><p>Other low-entropy attributes</p>
</li>
</ul>
<p>So you should use deterministic encryption deliberately and only when the equality-search requirement justifies the additional leakage.</p>
<h2 id="heading-base-keys-and-derived-keys">Base Keys and Derived Keys</h2>
<p>Another important part of a secure encryption architecture is <strong>key management</strong>.</p>
<p>A common design uses a highly protected root or master key and derives separate keys for specific purposes. Instead of using one key everywhere.</p>
<p>The diagram below illustrates <strong>key separation</strong>. Instead of using the same key for every type of data, a highly protected master key can serve as the root of a key hierarchy. Separate keys can then be created for different datasets, cryptographic purposes, or environments.</p>
<p>For example, a dataset key could be used for a particular data domain, while a purpose-specific key could be dedicated to encrypting SSNs. This limits each key's scope and reduces the impact if one key is compromised.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/c7c36e66-2c1d-4d43-8218-17f35ab52af6.png" alt="Diagram showing a master key securely stored in KMS or HSM and used to derive separate keys for different datasets, purposes, or environments, illustrating key separation." style="display: block;" width="1536" height="1024" loading="lazy">

<p>The idea with key separation is that different cryptographic purposes should use different keys or cryptographic contexts.</p>
<p>An organization might derive a key for:</p>
<pre><code class="language-text">Production + PII + SSN encryption
</code></pre>
<p>and another for:</p>
<pre><code class="language-plaintext">Production + PII + Email encryption
</code></pre>
<p>The exact hierarchy depends on the application's security requirements.</p>
<h3 id="heading-key-derivation-with-hkdf">Key Derivation with HKDF</h3>
<p>A common standard for deriving cryptographic keys is <strong>HKDF</strong>, or HMAC-based Key Derivation Function.</p>
<blockquote>
<p><strong>HKDF (HMAC-based Key Derivation Function):</strong> A standard method to derive multiple keys from a single master key.</p>
</blockquote>
<p>The diagram below shows how <strong>HKDF derives separate keys from a common master secret</strong>. HKDF takes the master secret as input, along with context information that identifies the intended purpose. For example, the context <code>"SSN encryption"</code> produces one derived key, while <code>"Email encryption"</code> produces another.</p>
<p>Because the context is different, the resulting keys are cryptographically separated even though they originate from the same master secret. You can use the same approach for other purposes, such as token generation.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/1063ad45-f8b1-46ef-91fb-496d73e73551.png" alt="Diagram showing a master secret passed through HKDF to derive separate cryptographic keys using different contexts, including SSN encryption, email encryption, and token generation." style="display: block;" width="1536" height="1024" loading="lazy">

<p>The important point is that the application doesn't need to maintain a completely independent master secret for every purpose. Instead, you can use a securely managed root secret as the starting point for deriving purpose-specific keys.</p>
<p>So context is a key part of the key-derivation design.</p>
<p>For example:</p>
<pre><code class="language-python">DerivedKey =
    HKDF(
        master_secret,
        context = "production:ssn"
    )
</code></pre>
<p>Another context produces a different derived key:</p>
<pre><code class="language-python">DerivedKey =
    HKDF(
        master_secret,
        context = "production:email"
    )
</code></pre>
<p>This provides <strong>key separation</strong>.</p>
<p>A compromise of one derived key should not automatically expose data protected using independently derived keys.</p>
<p>But key derivation does not magically make compromised ciphertext safe. If a derived key is compromised, all data protected with that particular key may still be at risk.</p>
<h3 id="heading-where-does-the-master-key-live">Where Does the Master Key Live?</h3>
<p>The root key should not be stored inside application source code or configuration files.</p>
<p>Instead, organizations typically use a managed key-management system or a Hardware Security Module (HSM).</p>
<blockquote>
<p><strong>HSM (Hardware Security Module):</strong> A physical or cloud-based device that safely stores digital keys and performs encryption.</p>
</blockquote>
<p>Examples include:</p>
<ul>
<li><p>AWS Key Management Service (KMS)</p>
</li>
<li><p>Google Cloud KMS</p>
</li>
<li><p>Azure Key Vault</p>
</li>
<li><p>Dedicated HSM infrastructure</p>
</li>
</ul>
<p>The key-management system provides controlled access, auditing, rotation capabilities, and integration with identity and access-management systems.</p>
<p>The application should receive only the cryptographic material or cryptographic operation that it actually needs.</p>
<h2 id="heading-local-cryptographic-operations">Local Cryptographic Operations</h2>
<p>In a local encryption workflow, the application performs the actual data encryption.</p>
<p>In this workflow, the <strong>KMS protects the root or key-encryption key</strong>, while the application performs the actual encryption locally. The application first requests a data-encryption key from the KMS. The KMS returns the data key along with a protected copy of that key. The application can then use the data key to encrypt data without making a KMS request for every individual value.</p>
<p>For a high-volume data pipeline, this approach scales better because the application can encrypt large amounts of data locally while the KMS protects the higher-level key. The data key should be treated as sensitive and kept in application memory only for as long as necessary.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/ed7c7f1a-f306-49c3-a5a7-dfb3e6496ccc.png" alt="Application requests a data key from KMS. KMS provides a data key along with a protected copy of the key. The application uses the data key to encrypt data locally and stores the encrypted data together with the encrypted data key." style="display: block;" width="936" height="924" loading="lazy">

<p>The application uses the appropriate data-encryption key or derived cryptographic key to perform encryption.</p>
<h3 id="heading-advantages">Advantages</h3>
<ul>
<li><p>High throughput</p>
</li>
<li><p>Fewer network calls for large datasets</p>
</li>
<li><p>Suitable for batch processing and data pipelines</p>
</li>
<li><p>Lower latency for individual encryption operations</p>
</li>
</ul>
<h3 id="heading-consideration">Consideration</h3>
<p>Cryptographic material used by the application exists temporarily in application memory.</p>
<p>Therefore, application security becomes an important part of the overall key-protection strategy.</p>
<h2 id="heading-remote-cryptographic-operations">Remote Cryptographic Operations</h2>
<p>In a remote encryption workflow, the application sends an encryption request to the KMS rather than performing the cryptographic operation itself. The KMS performs the operation using a protected key and returns the resulting ciphertext to the application. The underlying key material remains within the KMS boundary.</p>
<p>This provides centralized control and auditing of cryptographic operations, but every encryption request introduces a network interaction. For high-volume data processing, this can increase latency and may make the approach less suitable for encrypting individual values at very large scale.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/7689eeda-27bb-4238-b364-a03f5834403d.png" alt="Application sends an encryption request to KMS. KMS performs the encryption using its protected key and returns the ciphertext to the application, which stores the encrypted data. The encryption key remains within KMS." style="display: block;" width="924" height="919" loading="lazy">

<p>The application doesn't receive the underlying key material. This can reduce direct key exposure and centralize cryptographic operations and auditing.</p>
<h3 id="heading-advantages">Advantages</h3>
<ul>
<li><p>Stronger centralization of key access</p>
</li>
<li><p>Keys can remain within the managed cryptographic boundary</p>
</li>
<li><p>Centralized authorization and auditing</p>
</li>
<li><p>Useful for operations where remote cryptographic APIs are appropriate</p>
</li>
</ul>
<h3 id="heading-trade-offs">Trade-offs</h3>
<ul>
<li><p>Network latency</p>
</li>
<li><p>API throughput limits</p>
</li>
<li><p>Additional operational dependencies</p>
</li>
<li><p>Potential cost for large numbers of cryptographic operations</p>
</li>
</ul>
<p>For high-volume data pipelines, calling a remote KMS for every field or row may not be practical.</p>
<h2 id="heading-deterministic-encryption-vs-hmac">Deterministic Encryption vs HMAC</h2>
<p>Another option is worth considering when the only requirement is equality matching.</p>
<p>Suppose the analytics team doesn't need to recover the original SSN from the stored value.</p>
<p>They only need to answer:</p>
<blockquote>
<p>"Does this record have the same SSN as the search value?"</p>
</blockquote>
<p>In that case, reversible encryption may not be necessary.</p>
<p>A <strong>keyed cryptographic hash</strong>, such as HMAC, can sometimes be a better design.</p>
<pre><code class="language-text">HMAC(secret_key, normalized_SSN)
</code></pre>
<p>For example:</p>
<pre><code class="language-plaintext">111-22-3333
      │
      ▼
HMAC(secret_key, SSN)
      │
      ▼
X7a91f...
</code></pre>
<p>The same SSN produces the same HMAC:</p>
<pre><code class="language-plaintext">111-22-3333 → X7a91f...
111-22-3333 → X7a91f...
222-33-4444 → P3k21...
</code></pre>
<p>This allows equality comparisons:</p>
<pre><code class="language-plaintext">WHERE ssn_hmac = HMAC(secret_key, '111-22-3333')
</code></pre>
<p>But unlike encryption, an HMAC isn't intended to be reversible.</p>
<p>This can be a useful security property when the original value doesn't need to be recovered from the analytics dataset.</p>
<p>The choice between deterministic encryption and HMAC depends on the requirements, threat model, key-management architecture, and whether reversibility is required.</p>
<h2 id="heading-tokenization">Tokenization</h2>
<p>Another common approach is <strong>tokenization</strong>.</p>
<p>Instead of storing:</p>
<pre><code class="language-plaintext">111-22-3333
</code></pre>
<p>the system stores something like:</p>
<pre><code class="language-plaintext">TOKEN-8F72A1
</code></pre>
<p>The mapping between the original value and the token is maintained by a secure tokenization service or vault.</p>
<p>The data pipeline and analytics systems can work with the token instead of the original PII.</p>
<p>The diagram below shows how <strong>tokenization separates the sensitive value from the systems that consume the data</strong>. The original SSN is sent to a secure token vault, which creates or retrieves a token representing that value. The vault securely maintains the relationship between the original SSN and its token.</p>
<p>The data lake receives only the token, rather than the original SSN. Downstream systems can use the token as an identifier for matching or joining records without directly storing the underlying PII. If an authorized system ever needs the original SSN, it can interact with the token vault to resolve the token, subject to appropriate access controls.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69fd77e89f93a850a46d376f/dd76572a-7c40-411b-b51e-b6c3fa92acb3.png" alt="Diagram showing an SSN sent to a secure token vault, which maps the original SSN to a token. The token is returned to the application and stored in the data lake instead of the original PII." style="display: block;" width="1774" height="887" loading="lazy">

<p>Tokenization can be particularly useful when many downstream systems need to work with an identifier without having access to the underlying sensitive value.</p>
<h2 id="heading-comparing-the-approaches">Comparing the Approaches</h2>
<p>The right choice depends on what the application actually needs.</p>
<table>
<thead>
<tr>
<th>Approach</th>
<th>Equality Search</th>
<th>Reversible</th>
<th>Equality Leakage</th>
<th>Typical Use</th>
</tr>
</thead>
<tbody><tr>
<td>Randomized encryption</td>
<td>❌</td>
<td>✅</td>
<td>Low</td>
<td>General encrypted data</td>
</tr>
<tr>
<td>Deterministic encryption</td>
<td>✅</td>
<td>✅</td>
<td>Yes</td>
<td>Equality lookups</td>
</tr>
<tr>
<td>HMAC</td>
<td>✅</td>
<td>❌</td>
<td>Yes</td>
<td>Equality matching without recovery</td>
</tr>
<tr>
<td>Tokenization</td>
<td>✅</td>
<td>Usually through a vault</td>
<td>Depends on design</td>
<td>Shared identifiers across systems</td>
</tr>
</tbody></table>
<p>There is no universally "best" approach.</p>
<p>The important question is <strong>what operations do downstream systems actually need to perform on the sensitive data?</strong></p>
<h2 id="heading-access-control-still-matters">Access Control Still Matters</h2>
<p>Encryption is only one part of protecting PII. Even when data is encrypted, you still need:</p>
<ul>
<li><p>Strong IAM policies</p>
</li>
<li><p>Least-privilege access</p>
</li>
<li><p>Key-access controls</p>
</li>
<li><p>Encryption-key rotation policies</p>
</li>
<li><p>Audit logging</p>
</li>
<li><p>Data classification</p>
</li>
<li><p>Network controls</p>
</li>
<li><p>Secure secret management</p>
</li>
<li><p>Data retention and deletion policies</p>
</li>
<li><p>Monitoring and alerting</p>
</li>
</ul>
<p>For example, an analytics user might be allowed to perform an equality lookup without being allowed to decrypt the entire SSN column.</p>
<p>This is an important distinction: <strong>the ability to query an encrypted identifier doesn't have to imply the ability to decrypt it.</strong></p>
<h2 id="heading-what-we-learned-from-the-data-pipeline">What We Learned from the Data Pipeline</h2>
<p>For our data pipeline, the key challenge wasn't simply:</p>
<blockquote>
<p>"How do we encrypt the SSN?"</p>
</blockquote>
<p>The more important question was:</p>
<blockquote>
<p>"How do we protect the SSN while still supporting legitimate analytics requirements?"</p>
</blockquote>
<p>That distinction changes the architecture.</p>
<p>A practical design needs to consider:</p>
<ol>
<li><p>What data is sensitive?</p>
</li>
<li><p>Who needs access to it?</p>
</li>
<li><p>Does the data need to be reversible?</p>
</li>
<li><p>Does the application need equality matching?</p>
</li>
<li><p>Does it need range or other query types?</p>
</li>
<li><p>What information can be safely exposed to downstream systems?</p>
</li>
<li><p>Where should cryptographic keys live?</p>
</li>
<li><p>How should keys be separated and rotated?</p>
</li>
<li><p>How much cryptographic processing can the pipeline perform locally?</p>
</li>
<li><p>What needs to happen inside a managed KMS or HSM?</p>
</li>
</ol>
<p>Once these questions are answered, the encryption mechanism becomes an architectural decision rather than simply a library choice.</p>
<h2 id="heading-key-takeaways">Key Takeaways</h2>
<p>When designing a data pipeline containing sensitive PII, there are some key takeaways to keep in mind.</p>
<p>First, AES is a cryptographic primitive. The encryption mode determines important properties such as nonce/randomness behavior.</p>
<p>Second, randomized encryption protects against equality-pattern leakage but doesn't directly support deterministic equality searches.</p>
<p>Deterministic encryption enables equality matching but leaks information about repeated values. And deterministic encryption doesn't automatically support range, prefix, or arbitrary searches.</p>
<p>Next, you can use HKDF to derive cryptographically separated keys from a root secret. Key separation limits the impact of compromising one cryptographic context.</p>
<p>KMS and HSMs provide secure key management and cryptographic boundaries.</p>
<p>HMAC can be a better choice than reversible encryption when you only need equality matching.</p>
<p>Tokenization can isolate sensitive identifiers from downstream systems.</p>
<p>And don't forget that encryption must be combined with IAM, auditing, monitoring, and least-privilege access.</p>
<p>Most importantly: the goal isn't simply to encrypt sensitive data. The goal is to design a system where sensitive data remains protected while legitimate business operations can still be performed safely.</p>
<p>That's the real challenge when building secure, large-scale data pipelines.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build an Endpoint Data Loss Prevention Strategy for Your Development Team ]]>
                </title>
                <description>
                    <![CDATA[ A developer's laptop holds more sensitive data than most people realize: API keys, database credentials, staging environment secrets, and sometimes entire copies of production data pulled down "just f ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-an-endpoint-data-loss-prevention-strategy-for-your-dev-team/</link>
                <guid isPermaLink="false">6aa9b28d96b8eb1b8b1475f0</guid>
                
                    <category>
                        <![CDATA[ data loss prevention ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Protection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cybersecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CybersecurityAwareness ]]>
                    </category>
                
                    <category>
                        <![CDATA[ sensitive data ]]>
                    </category>
                
                    <category>
                        <![CDATA[ endpoint security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ remote access ]]>
                    </category>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ IT_Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Alex Tray ]]>
                </dc:creator>
                <pubDate>Tue, 15 Sep 2026 21:03:09 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/4a1cf15f-7d3a-48d2-8fdd-b53ceb1dd0e7.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A developer's laptop holds more sensitive data than most people realize: API keys, database credentials, staging environment secrets, and sometimes entire copies of production data pulled down "just for testing."</p>
<p>End-users are responsible for <a href="https://www.mimecast.com/content/endpoint-dlp-data-loss-prevention/">75%</a> of internal data-loss incidents, most of them accidental rather than malicious. For a dev team, that risk concentrates on the endpoint, the machine where code gets written, tested, and pushed.</p>
<p>Here's how to build a strategy that protects that machine without slowing your team down.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-how-to-build-an-endpoint-data-loss-prevention-strategy">How to Build an Endpoint Data Loss Prevention Strategy</a></p>
<ul>
<li><p><a href="#heading-step-1-map-where-sensitive-data-lives-in-the-endpoint">Step 1: Map Where Sensitive Data Lives in the Endpoint</a></p>
</li>
<li><p><a href="#heading-step-2-set-access-control-as-the-foundation">Step 2: Set Access Control as the Foundation</a></p>
</li>
<li><p><a href="#heading-step-3-harden-the-endpoint-os-layer">Step 3: Harden the Endpoint OS Layer</a></p>
</li>
<li><p><a href="#heading-step-4-lock-down-containers-and-local-environments">Step 4: Lock Down Containers and Local Environments</a></p>
</li>
<li><p><a href="#heading-step-5-catch-leaks-before-they-ship">Step 5: Catch Leaks Before They Ship</a></p>
</li>
<li><p><a href="#heading-step-6-extend-coverage-to-public-facing-surfaces">Step 6: Extend Coverage to Public-Facing Surfaces</a></p>
</li>
<li><p><a href="#heading-step-7-monitor-measure-and-keep-policies-honest">Step 7: Monitor, Measure, and Keep Policies Honest</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-build-security-into-how-your-team-already-works">Build Security Into How Your Team Already Works</a></p>
</li>
</ul>
<h2 id="heading-how-to-build-an-endpoint-data-loss-prevention-strategy">How to Build an Endpoint Data Loss Prevention Strategy</h2>
<img src="https://cdn.hashnode.com/uploads/covers/65e715387099ff28d36bf4ac/f3675a55-3f39-4c4f-bb60-8c036791842e.png" alt="f3675a55-3f39-4c4f-bb60-8c036791842e" style="display: block;" width="746" height="415" loading="lazy">

<h3 id="heading-step-1-map-where-sensitive-data-lives-in-the-endpoint">Step 1: Map Where Sensitive Data Lives in the Endpoint</h3>
<p>Start by finding out where secrets and sensitive data sit across your team's machines. Likely candidates are things like config files with hardcoded credentials, .env files that never made it to <code>.gitignore</code>, and cached database dumps from a debugging session six months ago that nobody remembered to delete.</p>
<p>Anything that qualifies as a backup, even an ad hoc one, should be treated as sensitive data in its own right. So if the <a href="https://www.nakivo.com/blog/how-to-enable-backup-encryption/">backup encryption</a> isn't in place, that copy is just as vulnerable as the original source of data.</p>
<p>Most teams are surprised by what turns up once they start looking. A short audit across a handful of laptops usually reveals the same handful of habits repeating across a whole team, since one developer's shortcut tends to spread once it works one time.</p>
<p>A simple spreadsheet tracking what kind of sensitive data lives where and on which machines gives the rest of this strategy something concrete to build on. Skip this step and every control that follows ends up guessing at what it's supposed to be protecting.</p>
<p>Try this first:</p>
<ol>
<li><p>Choose three to five developer machines to begin your initial audit.</p>
</li>
<li><p>Search typical locations for environment files, credentials, database dumps, and private keys.</p>
</li>
<li><p>Record the finding, file location, data type, owner, and note if the data is still needed.</p>
</li>
<li><p>Remove unnecessary copies and update credentials that might have been exposed.</p>
</li>
</ol>
<p>For a Linux machine, a basic first pass could look like:</p>
<pre><code class="language-shell">find ~ -type f \( -name ".env" -o -name "*.pem" -o -name "*.key" \) 2&gt;/dev/null
</code></pre>
<p>This approach won't uncover every secret, but it gives your team a solid starting inventory.</p>
<p>For example, if the audit finds ~/projects/client-api/.env containing a database password, you need to move the credential to a secret manager, delete the local file, and update the password.</p>
<h3 id="heading-step-2-set-access-control-as-the-foundation">Step 2: Set Access Control as the Foundation</h3>
<p>Every endpoint DLP strategy sits on top of a working access control system. If every developer can pull production credentials regardless of their role, no amount of monitoring downstream will fix that gap.</p>
<p><a href="https://www.freecodecamp.org/news/how-to-build-scalable-access-control-for-your-web-app/">Scalable access control</a> that's built around roles and attributes limits what a compromised laptop can expose in the first place. After all, a stolen set of credentials only matters as much as the permissions attached to them.</p>
<p>This is also the cheapest control on this whole list to get wrong, and one of the easiest to fix.</p>
<p>Reviewing who has access to what on a recurring schedule rather than once at onboarding will catch the slow creep of permissions that no one remembered to revoke after a project ended.</p>
<p><strong>A simple implementation process:</strong></p>
<ol>
<li><p>List production systems and sensitive resources.</p>
</li>
<li><p>Create roles such as developer, senior developer, DevOps, and administrator.</p>
</li>
<li><p>Document which resources each role actually needs.</p>
</li>
<li><p>Remove permissions that don't support someone's current work.</p>
</li>
<li><p>Review access whenever someone changes projects or leaves the team.</p>
</li>
</ol>
<p>The difference between too much access and appropriate access is easier to see side by side. Here's the same developer role, granted two different ways in Postgres.</p>
<p><strong>Too much access:</strong></p>
<pre><code class="language-markdown">-- One role, every database, every table, every operation 

GRANT ALL PRIVILEGES ON DATABASE prod_db TO dev_team; 

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO dev_team; 
</code></pre>
<p><strong>Appropriate access:</strong></p>
<pre><code class="language-markdown">-- Full access where the work actually happens 

GRANT CONNECT ON DATABASE staging_db TO dev_team; 

GRANT USAGE ON SCHEMA public TO dev_team; 

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO dev_team;
</code></pre>
<pre><code class="language-markdown">-- No standing connection to production at all 

REVOKE ALL ON DATABASE prod_db FROM dev_team; 
</code></pre>
<p>The same idea maps cleanly onto a role table, which is usually the easier version to hand to a team:</p>
<table style="width:629px"><colgroup><col style="width:78px"><col style="width:158px"><col style="width:141px"><col style="width:126px"><col style="width:126px"></colgroup><tbody><tr><th><p>Role</p></th><td><p>Dev / staging DB&nbsp;</p></td><td><p>Production DB</p></td><td><p>Secret Manager&nbsp;</p></td><td><p>Cloud Console</p></td></tr><tr><td><p>Developer</p></td><td><p>Read + write</p></td><td><p>None</p></td><td><p>Read, own project only</p></td><td><p>None</p></td></tr><tr><td><p>Senior Developer</p></td><td><p>Read + write</p></td><td><p>Read-only, time-limited</p></td><td><p>Read, own team's projects</p></td><td><p>Read-only&nbsp;</p></td></tr><tr><td><p>DevOps</p></td><td><p>Read + write</p></td><td><p>Write, scoped to deploys</p></td><td><p>Read + write&nbsp;</p></td><td><p>Admin, scoped&nbsp;</p></td></tr><tr><td><p>Administrator</p></td><td><p>Read + write</p></td><td><p>Full</p></td><td><p>Full</p></td><td><p>Full</p></td></tr></tbody></table>

<p>For example, a developer should have read and write access to the development and staging databases since those environments are part of their regular work. They shouldn't have direct access to the production database. A DevOps team member may need controlled production access for deployment and troubleshooting, with that access limited to the tasks they're responsible for.</p>
<h3 id="heading-step-3-harden-the-endpoint-os-layer">Step 3: Harden the Endpoint OS Layer</h3>
<p>Most development machines run some flavor of Linux, whether directly or through WSL, and the operating system layer is where a lot of DLP controls end up getting enforced day to day: file permissions, disk encryption, and keeping user privileges properly separated.</p>
<p>Getting comfortable with <a href="https://www.freecodecamp.org/news/the-linux-commands-handbook/">core Linux commands</a> makes it a lot easier to audit what's running on a machine, lock file permissions down the right way, and catch something out of place before it turns into a real problem.</p>
<p>Disk encryption also deserves a mention here. Steal a laptop with an unencrypted drive, and everything on it just hands itself over, no password needed, the moment someone pulls the disk and mounts it somewhere else.</p>
<p>Turn on full-disk encryption, and that same stolen laptop becomes a much smaller headache.</p>
<p>For Linux developers, here are a few commands you can run during an endpoint review:</p>
<pre><code class="language-markdown">whoami 
</code></pre>
<pre><code class="language-markdown">sudo -l 
</code></pre>
<pre><code class="language-markdown">ls -la ~/.ssh 
</code></pre>
<pre><code class="language-markdown">df -h 
</code></pre>
<p>These commands can help identify the current user, available sudo privileges, SSH files, and disk usage.</p>
<p>File permissions are where this gets specific. A secret sitting in a world-readable file is available to every process and every account on that machine, which quietly cancels out the access control work from the previous step.</p>
<p>Check what the permissions actually are before changing anything:</p>
<pre><code class="language-markdown">ls -la ~/.ssh
</code></pre>
<pre><code class="language-markdown">find ~/projects -name ".env" -exec ls -l {} \;
</code></pre>
<p>Output worth acting on looks like this:</p>
<pre><code class="language-markdown">-rw-r--r--  1 dev  staff  1704  Mar 12 09:14 /home/dev/.ssh/id_ed25519
</code></pre>
<pre><code class="language-markdown">-rw-rw-r--  1 dev  staff   612  Mar 12 09:14 /home/dev/projects/client-api/.env
</code></pre>
<p>Those trailing <strong>r--</strong> bits mean group members and every other user on the box can read a private key and a set of credentials. Tighten them so only the owner can access:</p>
<pre><code class="language-markdown">chmod 700 ~/.ssh              # directory: owner only
</code></pre>
<pre><code class="language-markdown">chmod 600 ~/.ssh/id_ed25519   # private key: owner read/write
</code></pre>
<pre><code class="language-markdown">chmod 644 ~/.ssh/id_ed25519.pub
</code></pre>
<pre><code class="language-markdown">chmod 600 ~/projects/client-api/.env
</code></pre>
<p>To sweep a whole projects directory at once:</p>
<pre><code class="language-markdown">find ~/projects -name ".env" -exec chmod 600 {} \;
</code></pre>
<p>Then give the actual hardening sequence:</p>
<ol>
<li><p>Enable full-disk encryption.</p>
</li>
<li><p>Keep the OS and security updates current.</p>
</li>
<li><p>Remove unnecessary administrator privileges.</p>
</li>
<li><p>Review SSH keys and remove unused ones.</p>
</li>
<li><p>Enable screen locking.</p>
</li>
<li><p>Configure endpoint monitoring where appropriate.</p>
<p>For example, if a developer's laptop has an old SSH key belonging to a previous project, remove it and revoke the corresponding access rather than leaving it available indefinitely.</p>
</li>
</ol>
<p>Some teams sidestep this risk at the source by moving development onto a <a href="https://v2cloud.com/glossary/virtual-desktop-infrastructure-vdi-definition">virtual desktop infrastructure</a>, where sensitive data lives centrally rather than on the physical machine. But this just relocates the DLP burden rather than removing it, since the virtual environment itself now needs the same access controls and monitoring to <a href="http://www.freecodecamp.org/news/vm-data-protection-best-practices/">protect VMs from data loss.</a></p>
<h3 id="heading-step-4-lock-down-containers-and-local-environments">Step 4: Lock Down Containers and Local Environments</h3>
<p>Local development increasingly happens inside containers, and each one is a small self-contained environment that can end up holding secrets if developers aren't careful about what gets stored in it.</p>
<p>A <code>.env</code> file might get baked into an image or credentials might sit in a container's environment variables long after a project wraps up.</p>
<p>Learning to work properly with <a href="https://www.freecodecamp.org/news/the-docker-handbook/">Docker</a> includes understanding how to keep secrets out of images entirely, using secret managers or runtime injection instead of hardcoding anything into a Dockerfile.</p>
<p>Here's a Dockerfile that looks perfectly straightforward and leaks in two different ways:</p>
<pre><code class="language-markdown">FROM node:20
WORKDIR /app
# Problem 1: copies everything, including .env, *.pem, and .git history
COPY . .
# Problem 2: the value is written into an image layer, permanently
ENV DB_PASSWORD="prod-9f2a-4c11-secret"
RUN npm install
CMD ["node", "server.js"]
</code></pre>
<p>Deleting the file in a later layer doesn't help, because the earlier layer still contains it. Anyone who pulls the image can read both:</p>
<pre><code class="language-markdown">docker history --no-trunc my-app:latest | grep -i password

docker run --rm -it --entrypoint sh my-app:latest -c "cat .env"
</code></pre>
<p>The corrected version starts with a .dockerignore, which keeps the sensitive files out of the build context entirely:</p>
<pre><code class="language-markdown"># .dockerignore

.env

.env.*

*.pem

*.key

.git

node_modules
</code></pre>
<p>Then copy only what the application needs and leave credentials out of the image:</p>
<pre><code class="language-markdown">FROM node:20

WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
# Copy application code only, not the whole directory
COPY src ./src
CMD ["node", "src/server.js"]
</code></pre>
<p>Supply the credential at runtime instead:</p>
<pre><code class="language-markdown">docker run -e DB_PASSWORD="$DB_PASSWORD" my-app:latest
</code></pre>
<p><strong>Practical check:</strong> Before pushing an image, scan it for .env files, private keys, credentials, and other sensitive data.</p>
<h3 id="heading-step-5-catch-leaks-before-they-ship">Step 5: Catch Leaks Before They Ship</h3>
<p>If you catch a leak early, it might cost you less loss.</p>
<p>Wire automated secret scanning into a <a href="https://www.freecodecamp.org/news/learn-continuous-integration-delivery-and-deployment/">CI/CD pipeline</a>, and a hardcoded API key gets flagged before it ever reaches a public repository.</p>
<p>Gitleaks and TruffleHog both handle this well by running right in the pipeline and failing the build as soon as a potential credential is detected in a commit.</p>
<p>Tuning the alerting properly takes some patience, but skipping that step tends to backfire. A scanner that keeps crying wolf with false positives encourages a team to click past every warning without even reading it. So, it's worth spending the setup time getting the rules to fit your codebase properly.</p>
<p>For example, a GitHub Actions workflow can run Gitleaks before code reaches production:</p>
<pre><code class="language-markdown">name: Secret Scan

on:

  pull_request:

  push:

jobs:

  gitleaks:

    runs-on: ubuntu-latest

    steps:

      - uses: actions/checkout@v4

        with:
          fetch-depth: 0

      - uses: gitleaks/gitleaks-action@v2
</code></pre>
<p>With this setup, the repository gets scanned whenever developers push code or open a pull request. If Gitleaks detects a potential credential, the workflow can stop before the change moves further through the deployment process.</p>
<p>A caught secret shows up in the workflow log looking roughly like this:</p>
<pre><code class="language-markdown">Finding:     AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI...
Secret:      wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
RuleID:      aws-access-token
Entropy:     4.31
File:        services/billing/.env.staging
Line:        12
Commit:      8f2a1c9dbe4477a1c0f9e2b3a5d7c8e1f0a2b3c4
Author:      dev@example.com
INF 14 commits scanned.
WRN leaks found: 1
Error: Process completed with exit code 1.
</code></pre>
<p>The non-zero exit code is what actually blocks the merge. The file name, line number, and commit hash tell whoever picks it up exactly where to look.</p>
<p>Tuning the alerting properly takes some patience, but skipping that step tends to backfire. Again, you don't want constant false positives causing your team to click past every warning without looking at it. So take the time to get the rules to fit your codebase.</p>
<p>That tuning happens in a <strong>.gitleaks.toml</strong> at the repository root, where you exempt the paths that legitimately contain fake credentials:</p>
<pre><code class="language-markdown">[extend]
useDefault = true

[[rules]]
id = "aws-access-token"
  [rules.allowlist]
  paths = [
    '''tests/fixtures/.*''',
    '''docs/examples/.*'''
  ]
  regexes = [
    '''AKIAIOSFODNN7EXAMPLE'''
  ]
</code></pre>
<p>Keep the allowlist narrow. Exempting a whole directory because one file in it kept tripping the scanner is how real credentials start slipping through.</p>
<p>For example, a developer accidentally commits an API key to a pull request. Gitleaks flags it during the workflow, the pull request can't proceed, and the team removes the key and rotates the credential before merging the code.</p>
<h3 id="heading-step-6-extend-coverage-to-public-facing-surfaces">Step 6: Extend Coverage to Public-Facing Surfaces</h3>
<p>Most endpoint DLP strategies focus on laptops and dev machines, but public websites need the same scrutiny, even when they're maintained outside the engineering team.</p>
<p>You might have a poorly configured contact form, a staging subdomain someone forgot was still live, and an admin panel nobody locked down properly. An ⁠API security testing platform can test exposed APIs for vulnerabilities and business logic flaws before they put sensitive data at risk. Any one of those can leak data just as easily as a careless commit ever could.</p>
<p>Part of the problem is that web design and security often get treated as separate jobs handled by separate people. Sites built with hosting, maintenance, and security combined into the process from the start hold up far better than ones where those pieces get tacked on after something goes wrong.</p>
<p>This kind of ongoing oversight matters for a public-facing site the same way endpoint monitoring matters for a developer's machine. Unattended surfaces are where problems tend to build up slowly, unnoticed, until something forces a closer look.</p>
<p>If your dev team owns the marketing site too, treat it as a part of the same DLP scope, handled with the same routine attention as everything else, rather than something someone gets to whenever there's some spare time.</p>
<p>A simple monthly check can catch these issues before they become forgotten infrastructure. Start by listing every active domain and subdomain, then check whether each one still needs to be publicly accessible.</p>
<p>Here's how that usually plays out in practice. A team ships a customer portal rewrite and spins up <strong>staging-v2.example.com</strong> to demo it to stakeholders. The launch goes fine. Nobody deletes the staging environment, and it keeps running on a copy of the production database that was loaded for the demo.</p>
<p>Eight months later, a routine subdomain sweep turns it up:</p>
<pre><code class="language-markdown"># Every subdomain still resolving
dig +short staging-v2.example.com
203.0.113.47
</code></pre>
<pre><code class="language-markdown"># Is it publicly reachable, and does it need auth?
curl -s -o /dev/null -w "%{http_code}\n" https://staging-v2.example.com/api/v1/customers
200
</code></pre>
<p>A 200 with no credentials attached is the problem. Pulling the first record confirms it:</p>
<pre><code class="language-markdown">curl -s https://staging-v2.example.com/api/v1/customers | head -c 200
[{"id":4471,"email":"real.customer@example.com","phone":"+1-555-0142",
"plan":"enterprise","last_invoice":"2025-11-03"}]
</code></pre>
<p>That's production customer data sitting on an unauthenticated endpoint, indexed by anyone scanning certificate transparency logs for subdomains. The fix has an order to it:</p>
<ol>
<li><p>Take the environment offline immediately, before anything else.</p>
</li>
<li><p>Check access logs to see if anyone else found it first.</p>
</li>
<li><p>Decide whether the environment is still needed. If not, delete it and remove the DNS record.</p>
</li>
<li><p>If it's needed, put it behind authentication or an IP allowlist and replace the database with generated test data.</p>
</li>
<li><p>Add every subdomain to the monthly inventory so the next one doesn't sit unnoticed for eight months.</p>
</li>
</ol>
<p>Keep the same review for public forms, admin panels, cloud storage, and unused API endpoints. The goal is to make every internet-facing surface something the team knows about and actively maintains.</p>
<h3 id="heading-step-7-monitor-measure-and-keep-policies-honest">Step 7: Monitor, Measure, and Keep Policies Honest</h3>
<p>A DLP strategy without measurement isn't a good strategy. Teams need visibility into where data exposure is showing up in practice, the same way marketing teams have started tracking brand visibility across AI platforms.</p>
<p>For insurance, Similarweb’s <a href="https://aisearch.similarweb.com/aeo/">AEO platform</a> built for that purpose tracks where and how a brand gets mentioned across AI-generated answers, catching patterns nobody would ever spot by checking one prompt at a time by hand.</p>
<p>Security monitoring for endpoints runs on that same idea. Without a dashboard showing where secrets are exposed or which machines have drifted out of compliance, a team spends its energy cleaning up after incidents instead of catching them early.</p>
<p>The same principle applies to backups: an untested backup is merely an assumption. Regularly <a href="https://www.freecodecamp.org/news/disaster-recovery-testing/">testing your disaster recovery plan</a> ensures that your data backup strategy works properly when issues arise.</p>
<p>That principle doesn't stop at the laptop, either. Most companies store sensitive data across Microsoft 365 (mailboxes, SharePoint sites, OneDrive folders, or Teams channels) and it's usually the dev or IT team's job to make sure that data is actually protected, not just retained.</p>
<p>Microsoft's native retention covers accidental deletion within a short window. It isn't built to recover from ransomware or a compromised account that goes unnoticed for weeks. Teams relying on that retention alone, without an <a href="https://www.nakivo.com/microsoft-office-365-backup">independent backup for Microsoft 365</a> data, are making the same unverified assumption this article already warns against with local backups.</p>
<p>Policy matters here just as much as any of the tooling does.</p>
<p>A policy only works if the people bound by it actually believe in it, and that part is harder to measure than tooling compliance. This is where an <a href="https://confiscore.com/">anonymous employee confidence tool</a> earns its place, showing whether a team genuinely trusts a security rule or is just quietly routing around it.</p>
<p>Security policies have a similar challenge. Vague one-size-fits-all rules dropped on a team without context can be difficult for developers to follow in practice. Give a team a policy nobody understands and eventually they'll build a workaround for it, regardless of how well-meaning it was when someone wrote it.</p>
<p>Rules that are specific and come with a clear explanation tend to hold up better than a generic PDF buried three folders deep in onboarding.</p>
<p>A security dashboard simplifies the review process. Track the number of secrets detected, endpoints outside required controls, permission changes, and resolution times for each issue.</p>
<p>For a team of twenty developers, that dashboard doesn't need to be more complicated than this:</p>
<table style="min-width:207px"><colgroup><col style="min-width:25px"><col style="min-width:25px"><col style="width:107px"><col style="min-width:25px"><col style="min-width:25px"></colgroup><tbody><tr><th><p>Metric</p></th><td><p>Last month&nbsp;</p></td><td><p>This month&nbsp;</p></td><th><p>Target</p></th><th><p>Direction</p></th></tr><tr><td><p>Secrets caught in CI</p></td><td><p>6</p></td><td><p>2</p></td><td><p>0</p></td><td><p>Improving</p></td></tr><tr><td><p>Secrets found in merged code</p></td><td><p>1</p></td><td><p>0</p></td><td><p>0</p></td><td><p>Improving</p></td></tr><tr><td><p>Endpoints with full-disk encryption</p></td><td><p>17 / 20</p></td><td><p>20 / 20&nbsp;</p></td><td><p>100%</p></td><td><p>Met</p></td></tr><tr><td><p>Machines missing security updates (30+ days)</p></td><td><p>4</p></td><td><p>5</p></td><td><p>0</p></td><td><p>Worsening</p></td></tr><tr><td><p>Standing production DB access</p></td><td><p>9 users&nbsp;</p></td><td><p>3 users&nbsp;</p></td><td><p>0</p></td><td><p>Met</p></td></tr><tr><td><p>Unreviewed subdomains</p></td><td><p>11</p></td><td><p>0</p></td><td><p>0</p></td><td><p>Met</p></td></tr><tr><td><p>Median time to rotate an exposed credential</p></td><td><p>3 days&nbsp;</p></td><td><p>6 hours</p></td><td><p>Under 24 hours&nbsp;</p></td><td><p>Improving&nbsp;</p></td></tr></tbody></table>

<p>Two things stand out immediately in a table like that, and neither would be obvious from an incident report.</p>
<ol>
<li><p>Secrets are getting caught in CI instead of after merge, which means step 5 is doing its job.</p>
</li>
<li><p>Patching is going backwards, which means something in the update process isn't working and another reminder email is unlikely to fix it.</p>
</li>
</ol>
<p>For example, if you see that a secret scanner detected an AWS credential in a pull request, stop the merge, revoke or rotate the credential, remove it from the repository, and check for its presence elsewhere. Investigate why the credential was accessible to the developer and update the workflow to prevent recurrence.</p>
<p>Make sure to monitor these metrics regularly instead of waiting for an incident. If the same violations continue, consider implementing clearer policies, improved tools, or a streamlined development process rather than issuing additional warnings.</p>
<img src="https://cdn.hashnode.com/uploads/covers/65e715387099ff28d36bf4ac/6164df73-1f9b-440d-af32-606538d1c389.png" alt="Data loss prevention diagram showing five steps (discover and classify, monitor and inspect, enforce policy, report and log, and refine and tune)" style="display: block;" width="1006" height="591" loading="lazy">

<h2 id="heading-build-security-into-how-your-team-already-works">Build Security Into How Your Team Already Works</h2>
<p>A strong DLP strategy doesn't mean slowing engineers down with endless approval steps or locking every laptop into a rigid corporate image, and it shouldn't come at the cost of customer experience either, since the whole point of shipping fast is to serve users well without exposing their data in the process.</p>
<p>The strongest endpoint DLP strategies just run in the background, mostly invisible day to day: access control keeping blast radius small, CI/CD checks catching mistakes before they ship, and monitoring pointing a team toward its real gaps instead of leaving everyone to guess.</p>
<p>Start with access control and CI/CD, since those two catch common mistakes with minimal <a href="https://codedesign.ai/glossary/frictionless-ux">friction</a>, and build outward once that foundation is solid.</p>
<p>Picking up suitable tools, including the best <a href="https://infomsp.com/top-10-backup-software/">backup software</a>, behind each of these steps makes the whole thing far easier to build and keep running over time.</p>
<p>Anyone looking to strengthen those foundations, whether that's Linux fundamentals, containerization, or CI/CD pipelines, will find free and practical guides covering precisely this kind of work over at <a href="https://www.freecodecamp.org">freeCodeCamp</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Developer's Guide to Protecting Personal Data: Best Practices and Tools ]]>
                </title>
                <description>
                    <![CDATA[ Think about it: you're sitting there enjoying your morning coffee, reading the headlines when again another data breach is making headlines. Millions of users' personal information – gone. You can't help but cringe as a developer at the prospect. Cou... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/developers-guide-to-protecting-personal-data/</link>
                <guid isPermaLink="false">680102ccf67e471495d5a624</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Personal data protection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ authentication ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Databases ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Alex Tray ]]>
                </dc:creator>
                <pubDate>Thu, 17 Apr 2025 13:31:56 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744839185611/b3e49efc-6eee-4a0b-9522-20407b1782e3.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Think about it: you're sitting there enjoying your morning coffee, reading the headlines when again another data breach is making headlines. Millions of users' personal information – gone. You can't help but cringe as a developer at the prospect. Could it happen on your watch?</p>
<p>The reality is, keeping personal data safe isn't something you should be doing because it's good practice – it's something you have to do. Users are trusting developers to care for their data day in and day out, and power must be wielded wisely. If you're writing code that involves getting, processing, or storing someone's personal data, then you should be being proactive about keeping it safe.</p>
<p>So the question is: how do you safely keep personal data?</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<p></p><dl><p></p>
<p></p><ul><p></p>
<p></p><li><a href="heading-know-what-youre-protecting">Know What You</a></li><p></p>
<h2 id="heading-know-what-youre-protecting">Know What You're Protecting</h2>
<p>If you must protect information, first determine what information must be protected. It is crucial to <a target="_blank" href="https://blog.incogni.com/opt-out-guides/">protect sensitive information</a> from unauthorized access to ensure data security. Below is a list of some common types of sensitive data:</p>
<ul>
<li><p>Personally Identifiable Information (PII): name, address, phone number, email, Social Security number.</p>
</li>
<li><p>Financial Data: bank details, payment history, credit card number.</p>
</li>
<li><p>Authentication Data: password, auth tokens, API keys, security question responses.</p>
</li>
<li><p>Health Info: any kind of <a target="_blank" href="https://www.jotform.com/what-is-hipaa-compliance/">HIPAA</a>-protected information about the health and medical history of the user.</p>
</li>
</ul>
<p>Once you know what information has to be rendered secure, then you can go ahead and render it secure.</p>
<h2 id="heading-best-practices-in-data-security">Best Practices in Data Security</h2>
<h3 id="heading-1-encrypt-everything">1. Encrypt Everything</h3>
<p>Your best protection against hacking is encryption. When data is encrypted, even if hackers have access to it, they cannot do anything with it in the absence of the decryption key.</p>
<p>For stored sensitive information, use <strong>hashing with a salt</strong>, a process that turns a password into an irreversible value. This way, even if someone gains access to the stored data, the actual password isn't exposed.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> hashlib
<span class="hljs-keyword">import</span> os

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hash_password</span>(<span class="hljs-params">password</span>):</span>
    salt = os.urandom(<span class="hljs-number">32</span>)  <span class="hljs-comment"># Generate a new salt</span>
    hashed_password = hashlib.pbkdf2_hmac(<span class="hljs-string">'sha256'</span>, password.encode(<span class="hljs-string">'utf-8'</span>), salt, <span class="hljs-number">100000</span>)
    <span class="hljs-keyword">return</span> salt + hashed_password
</code></pre>
<p>For data in transit, always use HTTPS:</p>
<pre><code class="lang-bash">sudo certbot --nginx -d yourdomain.com
</code></pre>
<p>This ensures data is encrypted between your server and the user. You can also reduce how often data is in transit by using <a target="_blank" href="https://www.suse.com/c/what-is-edge-computing/">edge computing</a>. Rather than sending sensitive data to external servers, increasing risk, it allows data to be stored and processed locally.</p>
<h3 id="heading-2-perform-secure-authentication">2. Perform Secure Authentication</h3>
<p>Weak authentication is an extremely critical security vulnerability.</p>
<p><strong>Authentication</strong> is the process of verifying who a user is (for example, logging in), while <strong>authorization</strong> is verifying what they're allowed to do (for example, access admin features).</p>
<p>Make sure that you:</p>
<ul>
<li><p>Perform strong password habits.</p>
</li>
<li><p>Perform multi-factor authentication (MFA). MFA requires users to present two or more verification factors (for example password and one-time code from a mobile device), making it much harder for attackers to gain access.</p>
</li>
<li><p>Perform OAuth 2.0 or OpenID Connect third-party authentication. These are secure industry-standard protocols that allow users to authenticate via trusted platforms like Google or Facebook, reducing the need to store credentials yourself.</p>
</li>
</ul>
<p>Example: Here’s an authentication setup using JWT (JSON Web Tokens) in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> jwt
<span class="hljs-keyword">import</span> datetime

SECRET_KEY = <span class="hljs-string">"your_secret_key"</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_token</span>(<span class="hljs-params">user_id</span>):</span>
    payload = {
        <span class="hljs-string">"user_id"</span>: user_id,
        <span class="hljs-string">"exp"</span>: datetime.datetime.utcnow() + datetime.timedelta(hours=<span class="hljs-number">1</span>)
    }
    <span class="hljs-keyword">return</span> jwt.encode(payload, SECRET_KEY, algorithm=<span class="hljs-string">'HS256'</span>)
</code></pre>
<p>This function generates a secure token for a user. The token contains the user ID and an expiration time, and it's signed using a secret key. Clients send this token with each request, and servers verify it to ensure the request comes from an authenticated user.</p>
<h3 id="heading-3-minimize-the-data-you-need-to-store">3. Minimize the Data You Need to Store</h3>
<p>One of the simplest things you can do to protect personal data? Store less than you have to. Consider the following questions:</p>
<ul>
<li><p>Do I really need to store this data?</p>
</li>
<li><p>How long do I really need to keep it for?</p>
</li>
<li><p>Can I anonymise it?</p>
</li>
</ul>
<p>For example, if you are going to need analytics, consider deleting personal identifiers prior to storing the data:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> anonymizeData = <span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">sessionId</span>: generateRandomId(),
        <span class="hljs-attr">event</span>: user.event,
        <span class="hljs-attr">timestamp</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toISOString()
    };
};
</code></pre>
<p>This JavaScript function removes identifying information (like name or email) and replaces it with a random session ID, keeping only the data necessary for analytics.</p>
<p>For instance, if you manage email lists, avoid storing unnecessary subscriber data beyond what is required for communication.</p>
<p>Regularly clean and scrub email lists to remove outdated or inactive addresses. Sending emails to outdated/inactive addresses can damage your domain reputation, leading to blacklisting and email deliverability issues. If you only need email addresses for temporary campaigns, consider <a target="_blank" href="https://support.google.com/a/answer/151128?hl=en">automated deletion policies</a> to remove old data.</p>
<h3 id="heading-4-secure-your-apis">4. Secure Your APIs</h3>
<p>If your application is consuming other services, protect your API endpoints. You can do this by:</p>
<ul>
<li><p><strong>Require tokens or API keys</strong>: These act as credentials to access the API and prevent unauthorized use.</p>
</li>
<li><p><strong>Implement rate limiting to deter abuse</strong>: This prevents attackers from flooding your server with too many requests.</p>
</li>
<li><p><strong>Validate and sanitize all input data</strong>: This protects against injection attacks and malformed inputs.</p>
</li>
</ul>
<p>Here's how you can validate API input in Node.js:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();

app.post(<span class="hljs-string">'/api/data'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> { name, email } = req.body;
    <span class="hljs-keyword">if</span> (!name || !email.includes(<span class="hljs-string">'@'</span>)) {
        <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">'Invalid input'</span>);
    }
    res.send(<span class="hljs-string">'Data received'</span>);
});
</code></pre>
<p>This ensures the API receives valid data and returns an error for incorrect input, which is a basic form of input sanitization.</p>
<h3 id="heading-5-lock-down-your-database">5. Lock Down Your Database</h3>
<p>Your database is an attack treasure trove, so lock it down:</p>
<ul>
<li><p><strong>Use parameterized queries</strong> to prevent SQL injection. These queries separate data from code.</p>
</li>
<li><p><strong>Limit database access using role-based permissions</strong>: Only give each user or service the access it needs—no more.</p>
</li>
<li><p><strong>Back up and test restoration procedures</strong>: Regular backups ensure you can recover data in the event of a breach or corruption.</p>
</li>
</ul>
<p>Here's a safe way to query a database in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_user</span>(<span class="hljs-params">email</span>):</span>
    conn = sqlite3.connect(<span class="hljs-string">'database.db'</span>)
    cursor = conn.cursor()
    cursor.execute(<span class="hljs-string">"SELECT * FROM users WHERE email = ?"</span>, (email,))
    <span class="hljs-keyword">return</span> cursor.fetchone()
</code></pre>
<p>This example uses a parameterized query (the ? placeholder) to safely insert the email into the SQL command, protecting against injection.</p>
<p>Also, never overlook how databases and internal systems might be accessed remotely. Remote access, whether for IT admins, support teams, or mobile workers, often involves logging in from unfamiliar devices—which introduces new security challenges. Tools that allow for secure, contactless logins without typing passwords or installing software on the remote machine reduce the risk of credential theft.</p>
<p>You can also ensure that remote database connections, SSH access, and admin panels are protected with strong authentication, IP restrictions, and, ideally, VPN access to avoid exposing sensitive entry points to the internet.</p>
<p>And remember, you don’t have to reinvent the wheel—there are <a target="_blank" href="http://blog.scalefusion.com/best-data-protection-software/">powerful data protection tools</a> available to keep your data safe from breaches and downtime. Want to know which ones stand out? Check out this guide for a breakdown of some of the best solutions.</p>
<h3 id="heading-6-periodically-audit-and-update-your-code">6. Periodically Audit and Update Your Code</h3>
<p>Unpatched software and outdated dependencies are essentially an open invitation to the attackers. Update your software and conduct security audits regularly.</p>
<p>Perform security scans for your project:</p>
<pre><code class="lang-javascript">npm audit fix --force  # For Node.js projects
</code></pre>
<pre><code class="lang-python">pip install --upgrade package_name  <span class="hljs-comment"># For Python projects</span>
</code></pre>
<p>These commands help find and fix known vulnerabilities in your project dependencies.</p>
<h3 id="heading-7-train-your-employees">7. Train Your Employees</h3>
<p>Your security is just as strong as your weakest link. If one employee handles sensitive data irresponsibly, everything else may have been for naught.</p>
<ul>
<li><p><strong>Standard security training</strong>: Regular sessions on topics like phishing, password security, and data handling.</p>
</li>
<li><p><strong>Implement solid policies on user data handling</strong>: For instance, never download sensitive data to personal devices.</p>
</li>
<li><p><strong>Establish a security-oriented culture</strong>: Encourage reporting of suspicious activity, regular internal audits, and open communication about threats.</p>
</li>
</ul>
<h3 id="heading-8-give-users-control-over-their-data">8. Give Users Control Over Their Data</h3>
<p>Transparency breeds trust. Give users control to:</p>
<ul>
<li><p>View and download their data.</p>
</li>
<li><p>Terminate their account easily.</p>
</li>
<li><p>Make adjustments in privacy settings.</p>
</li>
</ul>
<p>If you are collecting data, provide an opt-out. Users must be able to protect sensitive data and be in control of what becomes of their information. This is why it is important to have a privacy policy: users need to know what data you are collecting and for what purpose. Check out this <a target="_blank" href="https://www.iubenda.com/en/help/36387-privacy-policy-template">privacy policy template</a> if you need to create one for your site.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Data protection isn't just about coding well—it's about attitude. Get in the head of an attacker for a day, minimize vulnerabilities, and put user privacy at the top of your mind.</p>
<p>So the next time you're scanning the headlines for news of the latest ginormous data breach, you can be confident that your apps are bulletproof. Be smart, continue to learn, and let's make the internet safe—one line of secure code at a time.</p>
</ul></dl> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How SSH Authentication with GitHub Works Under the Hood ]]>
                </title>
                <description>
                    <![CDATA[ SSH (Secure Shell) is a client-server protocol for connecting and authenticating to a remote server. Authentication means that the remote server can verify that it’s actually you and not somebody else talking on your behalf. You may already be using ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/ssh-authentication-with-github-under-the-hood/</link>
                <guid isPermaLink="false">67ace33e18a2c0de81d7ffc3</guid>
                
                    <category>
                        <![CDATA[ ssh ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ public-key cryptgraphy ]]>
                    </category>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vivek Agrawal ]]>
                </dc:creator>
                <pubDate>Wed, 12 Feb 2025 18:06:54 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739082652213/aba38efa-117c-4ef7-a844-91599c0a4d62.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>SSH (Secure Shell) is a client-server protocol for connecting and authenticating to a remote server.</p>
<p>Authentication means that the remote server can verify that it’s actually you and not somebody else talking on your behalf.</p>
<p>You may already be using GitHub’s SSH authentication, but do you know how it actually works? In this article, you’ll learn what happens under the hood and how SSH authentication actually works.</p>
<p>Along the way, you’ll understand the fundamental concepts of cryptography that every developer should know about: symmetric key encryption, asymmetric key encryption, cryptographic hash functions, and digital signatures.</p>
<p>Some developers usually don’t get the chance to learn and understand these cryptography fundamentals, but these concepts will help you in the long run. Also, they’ll help you be in a much better position to take informed security decisions for your production web applications.</p>
<p>So come on, fasten your seat belts, and let’s start!</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-first-why-is-authentication-so-important">First, Why is Authentication So Important?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-symmetric-key-encryption">Symmetric Key Encryption</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-asymmetric-key-encryption">Asymmetric Key Encryption</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cryptographic-hash-functions">Cryptographic Hash Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-digital-signatures">Digital Signatures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-ssh-authentication-works">How SSH Authentication Works</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-it-all-up">Wrapping it All Up</a></p>
</li>
</ol>
<h2 id="heading-first-why-is-authentication-so-important">First, Why is Authentication So Important?</h2>
<p>When we run <code>git push</code>, GitHub needs to verify that the right person is interacting with GitHub. Imagine if an attacker could manage to do <code>git push</code> on your behalf.</p>
<p>Then all your repositories would be under that attacker's control. They could delete all your code along with all the commit history.</p>
<p>This sounds quite dangerous, doesn’t it? So to verify that it’s actually you who’s talking to GitHub, and not an attacker, GitHub has several ways to authenticate you.</p>
<p>The most widely used method to authenticate with GitHub is SSH authentication.</p>
<p>Before we understand how SSH authentication works under the hood, we will need to understand the fundamental cryptography concepts, namely — symmetric key encryption, asymmetric key encryption, cryptographic hash functions, and digital signatures.</p>
<p>Let’s begin!</p>
<h2 id="heading-symmetric-key-encryption">Symmetric Key Encryption</h2>
<p>In the ancient days, rulers devised various methods of communicating secret military messages to their army commanders.</p>
<p>One of the earliest methods, likely used by ancient Greek rulers and possibly later the Romans, involved using a cylindrical wooden rod called a <a target="_blank" href="https://en.wikipedia.org/wiki/Scytale"><strong>Scytale</strong></a>.</p>
<p>Before a military invasion, the ruler would have two exact same cylindrical wooden rods made called scytales. Then he would give one scytale to the army commander and keep one for himself.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734514827027/b4945c3a-64d4-458b-a410-f23b1a08d9ef.png" alt="A scytale with leather strip wounded and a message written on it." class="image--center mx-auto" width="2012" height="1176" loading="lazy"></p>
<p>The device worked by winding a strip of leather around the scytale. After doing this, the ruler would write the message on top of the wound-up leather strip so that it could only be read when properly wound again.</p>
<p>Suppose the scytale allowed him to write three letters around in a circle and five letters straight across/along its length. The wound leather strip with the message <code>attackfromright</code> written on it would look like this:</p>
<pre><code class="lang-plaintext">       |   |   |   |   |   |
       | a | t | t | a | c |  |
     __| k | f | r | o | m |__|
    |  | r | i | g | h | t |
    |  |   |   |   |   |   |
</code></pre>
<p>After writing the message on the scytale, the ruler would unwind the leather strip and send it to the army commander. When it was unwound, the leather strip would have the following jumbled message:</p>
<pre><code class="lang-plaintext">----------------
akrtfitrgaohcmt
----------------
</code></pre>
<p>So now you see, even if the leather strip got intercepted by an enemy spy, the message would not make sense. Isn't this fascinating? The smart use of a wooden rod and a leather strip might have helped some ancient rulers win battles!</p>
<p>When the leather strip reached the army commander, he would wind it around his own scytale (which would be exactly the same as ruler’s), and then the commander would be able to understand the message properly.</p>
<p>This scytale technique is actually an example of symmetric key encryption in practice.</p>
<p>Encryption is a process in which the original message is modified (or encoded) in such a way that only the intended recipient can decode and see the actual message.</p>
<p>The original message is called plaintext, while the encoded message is called ciphertext. Encryption converts <code>plaintext to ciphertext</code> with the help of a key.</p>
<p>To decrypt the message, that is to convert <code>ciphertext to plaintext</code>, a person must have access to that same key.</p>
<p>If we compare it to the scytale technique, the scytale is the key. The ruler only shares the key (scytale) with the army commander who needs to know what the message says.</p>
<p>Here's what the encryption process looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734519516607/75c926a3-faec-402a-8bcd-122039f47a01.png" alt="Encryption with scytale as key." class="image--center mx-auto" width="2023" height="526" loading="lazy"></p>
<p>The decryption process will look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734519525487/de096889-332c-4482-b2df-b28ce609a8a6.png" alt="Decryption with scytale as key." class="image--center mx-auto" width="1979" height="526" loading="lazy"></p>
<p>We call this symmetric key encryption because the same key is used to both encrypt and decrypt the message.</p>
<p>This key (the scytale) must be kept protected from enemy access. If the enemy get’s access to this key, then they’ll be able to decrypt the messages.</p>
<p>But there’s another type of encryption called asymmetric key encryption. Now that you understand symmetric key encryption, let’s move on to asymmetric key encryption.</p>
<h2 id="heading-asymmetric-key-encryption">Asymmetric Key Encryption</h2>
<p>In symmetric key encryption, like we saw above, the same key was used by both the ruler and the army commander to encrypt and decrypt the message.</p>
<p>But in an asymmetric key encryption, there are two keys (called a key pair). Out of the two keys, one is a private key and the other is a public key.</p>
<p>The public key can be shared with everyone (which is why it’s called public). But the private key is meant to be kept secret! It must never ever be revealed to anybody.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735200860039/7aca8ffa-c33a-44e5-ab1a-181492ebefd8.png" alt="Public key can be shared with everyone. But the private key must be kept secret." class="image--center mx-auto" width="2714" height="1428" loading="lazy"></p>
<p>The interesting thing about asymmetric key encryption is that, if a message is encrypted with the public key, then it can only be decrypted with the corresponding private key. No other key can decrypt it.</p>
<p>And it works the other way too. If a message is encrypted with the private key then it can only be decrypted using the corresponding public key.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735120077350/b90901c8-b55c-428a-8eb4-1b8ffa65fa06.png" alt="Illustration of public and private key mathematically linked with each other." class="image--center mx-auto" width="948" height="835" loading="lazy"></p>
<p>The two keys – public and private – are mathematically linked with each other. While one encrypts, the other decrypts.</p>
<p>Just a small note that asymmetric key encryption is also called public key encryption. These two terms are used interchangeably but they mean the same thing.</p>
<h2 id="heading-cryptographic-hash-functions">Cryptographic Hash Functions</h2>
<p>A cryptographic hash function is designed to take in an input of any length and produce a fixed-length output. The fixed-length output is called as hash value.</p>
<p>A popular example of a cryptographic hash function is SHA-256.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735030835833/201640c6-13b4-4b2b-9be3-88e245269bd1.png" alt="SHA-256 calculation of &quot;freeCodeCamp.org&quot;" class="image--center mx-auto" width="2283" height="285" loading="lazy"></p>
<p>The above image shows the SHA-256 hash value of the input “freeCodeCamp.org“. Cryptographic hash function has three properties that make it very useful (we’ll see how in the coming sections).</p>
<p>First<strong>,</strong> it’s practically impossible to take the hash value and figure out the input from the hash value.</p>
<p>For example, if we are given the hash value <code>c9c31315ef2257e4b7698</code>, there’s no way for us to figure out that the input to the hash function was “freeCodeCamp.org“.</p>
<p>Second<strong>,</strong> if we pass the same input to the hash function, we get the same hash value as output.</p>
<p>If we pass “freeCodeCamp.org“ again to the SHA-256 hash function, we will get the same hash output as our previous call.</p>
<p>Third<strong>,</strong> two different inputs never share the same hash value. Even the slightest change in input produces an entirely different output.</p>
<p>Suppose if we provide “freeCodeCamp“ as input instead of “freeCodeCamp.org“ – we would get a totally different output.</p>
<h2 id="heading-digital-signatures">Digital Signatures</h2>
<p>In your daily lives, you might have to sign various documents. These might be legal documents, or your kids’ school report card, or maybe something else.</p>
<p>When your signature is present on the document, it conveys to the other party that it is you who agrees with whatever is written on that document.</p>
<p>Later on, you cannot walk back from doing what’s written on the document. Correct?</p>
<p>Similarly, in the digital world, we have digital signatures – or we can simply call them signatures.</p>
<p>Let’s understand how signatures works using an example. We have two users named “Alice“ and “Bob“.</p>
<p>Bob wants to transfer some money to Alice’s bank account. So Bob asks Alice about her bank account information.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735042150046/034d26c5-b33d-4b82-aeb8-173e47cd8e8e.png" alt="An illustration showing alice and bob's computers far away from each other and alice's bank account number." class="image--center mx-auto" width="1972" height="1410" loading="lazy"></p>
<p>Alice knows about digital signatures and decided to use one. At the end, you will understand why Alice opted for a digital signature.</p>
<p>Before Alice can create a digital signature. Alice provides Bob with her public key (and keeps the private key to herself).</p>
<p>Then Alice creates a digital signature and places it at the end of the document.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735041977880/35313148-8820-42d7-b122-3ddf0cbaa723.png" alt="Process of digital signature generation." class="image--center mx-auto" width="1065" height="471" loading="lazy"></p>
<p>A digital signature is created by first passing the document contents to a cryptographic hash function like SHA-256. In Alice’s case, the document’s content is her bank account number.</p>
<p>Once we get the hash value, it gets encrypted with Alice’s <strong>private key</strong>. The output of this encryption is the signature which gets placed at the end of the document.</p>
<p>This is then sent to Bob over the Internet.</p>
<p>When Bob receives this document, he verifies whether the <strong>signature is valid or not</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735043216695/256f7707-3f40-433f-9b00-c11b27ef01e8.png" alt="Process of signature verification." class="image--center mx-auto" width="2905" height="1636" loading="lazy"></p>
<p>To verify the signature, Bob first decrypts the signature with Alice’s public key. If you remember, Alice generated the signature by encrypting the hash value.</p>
<pre><code class="lang-plaintext"> plaintext                         ciphertext  
     |                                 |
     |                                 |
     |                                 |
hash value --------encrypt--------&gt; signature
</code></pre>
<p>So, when Bob decrypts the signature, he will get the hash value that Alice calculated. Let’s call this Alice’s hash value.</p>
<pre><code class="lang-plaintext"> ciphertext                         plaintext  
     |                                 |
     |                                 |
     |                                 |
signature --------decrypt--------&gt; hash value
</code></pre>
<p>Then Bob takes the bank account number that’s present on the document and passes it to the hash function.</p>
<p>Finally, Bob matches the Alice’s hash value (the decrypted signature) and the hash value that he just calculated. If both the hash values match then that means the signature is valid.</p>
<p>OK — but why did we need to do all this? What does it mean if the signature is valid?</p>
<p>When the signature verification is successful, it proves two things.</p>
<p>First<strong>,</strong> it proves that the document has been sent by Alice only. Nobody else could have sent this document.</p>
<p>The assurance that only Alice has sent this document comes from the fact that we were able to decrypt the signature using Alice’s public key.</p>
<p>We have learned that if something is encrypted using a private key then it can only be decrypted using its linked public key.</p>
<p>So, if Bob was successfully able to decrypt the signature using Alice’s public key, it means that it was encrypted using Alice’s private key, correct?</p>
<p>And only Alice has access to her private key. This means that Alice is the only person who could have sent this document!</p>
<p>Second<strong>,</strong> it proves that the content of the message has not been modified by an attacker during network transmission.</p>
<p>We did two things to verify the signature. We decrypted the signature, and it gave us the hash value that Alice calculated. And we also hashed the received bank account number.</p>
<p>If the hash value that Alice calculated and the hash value that Bob calculated are the same, this means that Alice and Bob gave exactly the same input to the hash function.</p>
<p>And this means that the bank account number that Alice sent and that Bob received are exactly same.</p>
<p>If an attacker would have changed the bank account number before the document reached Bob, then Bob would’ve received a modified bank account number.</p>
<p>When Bob went to calculate the hash value of this modified bank account number, the hash value would’ve come out to be different than what Alice had calculated.</p>
<p>So while matching Alice’s hash value (decrypted signature) and the hash value that Bob calculated, the matching would fail. And it would prevent Bob from transferring money to the wrong bank account number.</p>
<p>To conclude, when the signature is successfully verified, it means that:</p>
<ol>
<li><p>The document is only from Alice.</p>
</li>
<li><p>The document’s contents were not modified by any third party.</p>
</li>
</ol>
<p>Now you’ve learned about symmetric key encryption, asymmetric key encryption, cryptographic hash functions, and digital signatures. That’s awesome!</p>
<p>We have built a really solid foundation. Now understanding SSH authentication is going to be much easier for you.</p>
<h2 id="heading-how-ssh-authentication-works">How SSH Authentication Works</h2>
<p>If you have not setup SSH authentication with GitHub, then after completing this article you can follow <a target="_blank" href="https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account">GitHub’s detailed documentation on how to do it</a>. For now, please stay here till the end.</p>
<p>The crux of the setup process is that you create a public and private key pair on your local computer. Then you upload your public key to your GitHub profile – and that’s it!</p>
<p>After we have created our public-private key pair, in Ubuntu, public-private key pair are stored inside the <code>~/.ssh</code> directory.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735035539565/1f837d9b-9717-44fa-a5e0-5801276113df.png" alt="Showing my public key from my terminal." class="image--center mx-auto" width="4380" height="243" loading="lazy"></p>
<p>The above image shows my public key. I have this public key uploaded to my GitHub profile:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735035898284/1ef9133a-895b-4847-a7ac-6157fdcc3143.png" alt="Showing my GitHub profile settings where my public key is uploaded for SSH authentication with GitHub." class="image--center mx-auto" width="4287" height="1398" loading="lazy"></p>
<p>Now, when I run <code>git push</code> or any other command that wants to communicate with GitHub, I will be authenticated using SSH authentication.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735053545173/6fb293f1-f90a-4b64-b026-082d8676afae.png" alt="The illustration of SSH authentication process between client and GitHub server." class="image--center mx-auto" width="4082" height="2574" loading="lazy"></p>
<p>SSH is a client-server protocol. Our computer that runs <code>git push</code> is the SSH client. GitHub is the SSH server.</p>
<p>The client starts off the authentication process by first fetching our public key that we have inside <code>~/.ssh</code>.</p>
<p>The client then prepares a message which has our public key. And then the client generates the signature using the corresponding private key.</p>
<p>The public key and signature are sent to GitHub. Upon receiving this message, GitHub does two things:</p>
<p>First, it verifies whether the public key mentioned in the message is connected to a GitHub profile or not. Since we upload our public key to GitHub, this step checks out successfully.</p>
<p>Second, GitHub verifies the signature using the public key that we have uploaded.</p>
<p>We have learned that if the signature verification turns out to be successful this means that only the person who is in the possession of the corresponding private key could have sent the message.</p>
<p>Since only we have the private key linked to the uploaded public key, this proves to GitHub that it is indeed us attempting to communicate with GitHub and not an attacker.</p>
<p>Now, GitHub is 100% sure that we are the correct person, we are successfully authenticated, and our <code>git push</code> is allowed to proceed further.</p>
<p>See, it became so easy to understand SSH authentication as you already learned the fundamentals.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735120630613/e9a8bbba-3cc4-43e7-8369-865ab377fb87.png" alt="A xkcd comic depicting Cueball thinking to share his private key. A dangerous move!" class="image--center mx-auto" width="733" height="282" loading="lazy"></p>
<p>The above image is from the popular <a target="_blank" href="https://xkcd.com/1553/">xkcd comic</a>. The character there (named Cueball) is thinking about revealing his private key. I hope now you know why it’s bad to reveal your private key.</p>
<p>If you reveal your private key then someone else can authenticate to GitHub on your behalf. You don’t want that to happen, right? ;)</p>
<p>So, always make sure to keep your private key just to yourself.</p>
<h2 id="heading-wrapping-it-all-up">Wrapping it All Up</h2>
<p>If you have read this far, then Congratulations 🥳.</p>
<p>You’ve learned how SSH authentication actually works — when the signature was successfully verified by GitHub, it confirms to GitHub that it is we who are talking to it not an attacker.</p>
<p>Along the way you built a foundational understanding of symmetric key encryption, asymmetric key encryption, cryptographic hash functions and digital signatures.</p>
<p>Thanks for being with me on this one, I hope you are going away with some new and valuable learnings.</p>
<p>I put useful ideas and resources on my Twitter. <a target="_blank" href="https://twitter.com/vkwebdev"><strong>You should follow me there.</strong></a> I will respect your time.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Homomorphic Encryption Works – Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ As the fields of cryptography and cybersecurity advance, homomorphic encryption stands out as a groundbreaking technology.  It has the potential to reshape everything in data privacy and security. What really is homomorphic encryption? Why is it gett... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/homomorphic-encryption-in-plain-english/</link>
                <guid isPermaLink="false">66ba5320ba2ef92905bfa81d</guid>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ information security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tiago Capelo Monteiro ]]>
                </dc:creator>
                <pubDate>Mon, 29 Jan 2024 18:33:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/vanna-phon-hRXIKdxoaPo-unsplash--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As the fields of cryptography and cybersecurity advance, <a target="_blank" href="https://www.freecodecamp.org/news/introduction-to-homomorphic-encryption/">homomorphic encryption</a> stands out as a groundbreaking technology. </p>
<p>It has the potential to reshape everything in data privacy and security.</p>
<p>What really is homomorphic encryption? Why is it getting so much attention? How can it increase data privacy?</p>
<p>Essentially, with homomorphic encryption, we can process encrypted data without ever needing to decrypt it for computation.</p>
<p>This results in complete privacy everywhere the data is processed and stored.</p>
<p>In this article, you'll learn why this type of encryption will revolutionize the field of security. We'll tackle questions such as:</p>
<ul>
<li>What is homomorphic encryption?</li>
<li>How does homomorphic encryption work?</li>
<li>Homomorphic encryption vs traditional encryption – what's the difference?</li>
<li>What are the applications of homomorphic encryption?</li>
</ul>
<h2 id="heading-what-is-homomorphic-encryption">What is Homomorphic Encryption?</h2>
<p>Let's use an analogy to understand homomorphic encryption.</p>
<p>Imagine a locked treasure chest that has many valuable items inside.</p>
<p>To add or remove items, you need to unlock the chest. This could make it easier for thieves to steal the items when you open it.</p>
<p>In this analogy, this is what traditional encryption is.</p>
<p>Homomorphic encryption is like having a magical glove that allows you to add or remove items from the chest without ever unlocking it.</p>
<p>This way, you remove the risk of thieves ever getting the items inside the treasure chest.</p>
<p>This is essentially what Homomorphic encryption does with data: it allows us to perform operations on encrypted data without ever needing to decrypt it.</p>
<p>This is not possible with traditional encryption. In that case, we must process the data we need to decrypt, do whatever computations are necessary, and then encrypt the data again.</p>
<p>With homomorphic encryption, security is never compromised.</p>
<h2 id="heading-how-does-homomorphic-encryption-work">How Does Homomorphic Encryption Work?</h2>
<p>Homomorphic encryption allows computations to act on encrypted data – also called ciphertext.</p>
<p>This means the data is processed while encrypted.</p>
<p>Homomorphic encryption does computations on encrypted data (ciphertext). But computations done in ciphertext give encrypted results.</p>
<p>When these results are decrypted, they are similar to those that would've been obtained if the operations had been performed on the original, unencrypted data.</p>
<p>So basically, homomorphic encryption allows operations on encrypted data to give the same results as if performed on the original, decrypted data.</p>
<h3 id="heading-how-is-this-done">How is this done?</h3>
<p>Homomorphic encryption uses complex mathematical algorithms that:</p>
<ul>
<li>transform the numbers to obscure the original data, and </li>
<li>perform the same operations whether on the original or on this obscured data.</li>
</ul>
<p>Essentially, you're always working on the same data in the same way, but from different points of view.</p>
<p>So you can work with the data and get exactly the same results as if it were not encrypted. But since it actually is encrypted, the data is always protected!</p>
<p>This way, no one can see it and maybe steal it, which allows data privacy even in environments where trust is minimal.</p>
<h3 id="heading-python-code-example">Python code example</h3>
<p>We are going to use the Pyfhel library for this example, which you can read more about <a target="_blank" href="https://pypi.org/project/Pyfhel/3.1.1/">here</a>.</p>
<p>In this code, we are going to add two numbers in their encrypted form and see the results.</p>
<p>Here is the full code so you can truly understand how homomorphic encryption works:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> Pyfhel <span class="hljs-keyword">import</span> Pyfhel

HE = Pyfhel()
HE.contextGen(scheme=<span class="hljs-string">'bfv'</span>, n=<span class="hljs-number">2</span>**<span class="hljs-number">14</span>, t_bits=<span class="hljs-number">20</span>)
HE.keyGen()

integer1 = np.array([<span class="hljs-number">127</span>], dtype=np.int64)
integer2 = np.array([<span class="hljs-number">-57</span>], dtype=np.int64)

ctxt1 = HE.encryptInt(integer1)
ctxt2 = HE.encryptInt(integer2)

ctxtSum = ctxt1 + ctxt2
ctxtSub = ctxt1 - ctxt2
ctxtMul = ctxt1 * ctxt2

resSum = HE.decryptInt(ctxtSum) 
resSub = HE.decryptInt(ctxtSub)
resMul = HE.decryptInt(ctxtMul)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/ray-so-export.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now we are going to break it down line by line:</p>
<p>First, we need to import the necessary modules:</p>
<pre><code><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> Pyfhel <span class="hljs-keyword">import</span> Pyfhel
</code></pre><p>Here, we are just importing the necessary modules to make our calculations.</p>
<p>Next, we need to create a Pyfhel object and generate keys:</p>
<pre><code>HE = Pyfhel()
HE.contextGen(scheme=<span class="hljs-string">'bfv'</span>, n=<span class="hljs-number">2</span>**<span class="hljs-number">14</span>, t_bits=<span class="hljs-number">20</span>)
HE.keyGen()
</code></pre><p>In the first line we initialize a <code>Pyfhel</code> python object. In the second line we set encryption with certain parameters:</p>
<ul>
<li><code>scheme='bfv'</code>: We use the <a target="_blank" href="https://link.springer.com/chapter/10.1007/978-3-030-92078-4_21">BFV (Brakerski/Fan-Vercauteren)</a> homomorphic encryption scheme.</li>
<li><code>n=2**14</code>: Defines the degree of the polynomial modulus degree. The polynomial modulus degree balances the encryption security level with the computational efficiency. A bigger number gives better encryption but at the cost of more computational resources</li>
<li><code>t_bits=20</code>: Sets the bit size of the plaintext modulus. Bigger bit size values let you use larger numbers but make the encryption less clean</li>
<li>In the third line, we <a target="_blank" href="https://www.freecodecamp.org/news/encryption-explained-in-plain-english/">generate a public and private key</a></li>
</ul>
<p>Then, we get two numbers and encrypt them:</p>
<pre><code>integer1 = np.array([<span class="hljs-number">127</span>], dtype=np.int64)
integer2 = np.array([<span class="hljs-number">-57</span>], dtype=np.int64)

ctxt1 = HE.encryptInt(integer1)
ctxt2 = HE.encryptInt(integer2)
</code></pre><p>We represent the numbers in a array with just one number and encrypt them.</p>
<p>We represent these numbers in an array and not as if we are declaring variables.</p>
<p>We do this because the function <code>encryptInt()</code> only takes an array of integers with 64 bits as an argument. From the <a target="_blank" href="https://pyfhel.readthedocs.io/en/latest/_autosummary/Pyfhel.Pyfhel.html">documentation</a>:</p>
<pre><code class="lang-python">encryptInt(self, int64_t[:] arr, PyCtxt ctxt=<span class="hljs-literal">None</span>)
</code></pre>
<p>Now we'll perform the operations on the two numbers while encrypted:</p>
<pre><code>ctxtSum = ctxt1 + ctxt2
ctxtSub = ctxt1 - ctxt2
ctxtMul = ctxt1 * ctxt2
</code></pre><p>And then decrypt the numbers after the operation when they where encrypted:</p>
<pre><code>resSum = HE.decryptInt(ctxtSum) 
resSub = HE.decryptInt(ctxtSub)
resMul = HE.decryptInt(ctxtMul)
</code></pre><p>Which will output the following:</p>
<pre><code>&gt;&gt;&gt; [<span class="hljs-number">70</span>  <span class="hljs-number">0</span>  <span class="hljs-number">0</span> ...  <span class="hljs-number">0</span>  <span class="hljs-number">0</span>  <span class="hljs-number">0</span>]
&gt;&gt;&gt; [<span class="hljs-number">184</span>   <span class="hljs-number">0</span>   <span class="hljs-number">0</span> ...   <span class="hljs-number">0</span>   <span class="hljs-number">0</span>   <span class="hljs-number">0</span>]
&gt;&gt;&gt; [<span class="hljs-number">-7239</span>     <span class="hljs-number">0</span>     <span class="hljs-number">0</span> ...     <span class="hljs-number">0</span>     <span class="hljs-number">0</span>     <span class="hljs-number">0</span>]
</code></pre><p>And if we do the normal calculations without being encrypted, we see that the values match:</p>
<pre><code>integer1 = <span class="hljs-number">127</span>
integer2 = <span class="hljs-number">-57</span>

print(integer1+integer2)

print(integer1-integer2)

print(integer1*integer2)
</code></pre><p>Which gives the following:</p>
<pre><code>&gt;&gt;&gt; <span class="hljs-number">70</span>

&gt;&gt;&gt; <span class="hljs-number">184</span>

&gt;&gt;&gt; <span class="hljs-number">-7239</span>
</code></pre><p>As you can see, we get the same results if we perform the operations on the data while it's encrypted as we do when it's not encrypted.</p>
<h2 id="heading-homomorphic-encryption-vs-traditional-encryption-whats-the-difference">Homomorphic Encryption vs Traditional Encryption – What's the Difference?</h2>
<p>In traditional encryption methods, data needs to be decrypted before any kind of processing. </p>
<p>In homomorphic encryption, data is always used in its encrypted state.</p>
<p>Traditional encryption is like a secure envelope: contents must be taken out to be read or modified. </p>
<p>Homomorphic encryption is like a special envelope that allows content manipulation without ever needing to open it to be read or modified.</p>
<h2 id="heading-applications-of-homomorphic-encryption">Applications of Homomorphic Encryption</h2>
<p>There are many practical applications of homomorphic encryption.</p>
<p>In cloud computing, it allows users to process data in the cloud without ever exposing it to cloud service providers. This way, sensitive information always remains confidential.</p>
<p>In healthcare, it allows the analysis of encrypted medical records without compromising patient privacy. Patient health data always remains protected.</p>
<p>Another promising application of homomorphic encryption is in secure voting systems. Using this type of encryption, votes are counted in such a way that no one can see for whom each person voted. This would make the voting process safer and more private.</p>
<p>These examples represent just the tip of the iceberg. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Homomorphic encryption is a paradigm shift in how we handle and process sensitive data. </p>
<p>This technology and its development are important as more and more data breaches are happening all the time.</p>
<p>Homomorphic encryption offers a path toward the simplification of data privacy regulations. </p>
<p>It also allows more innovation by making the protection of private data simpler, encouraging new security developments.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Photo Encryption App using Steganography ]]>
                </title>
                <description>
                    <![CDATA[ In this digital age, data flows freely across networks and devices. So protecting sensitive information from unauthorized access is crucial. That's where encryption comes in.  Encryption involves converting plain, readable data into an incomprehensib... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-a-photo-encryption-app/</link>
                <guid isPermaLink="false">66c5a25d3d77fae9eb82a46c</guid>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ information security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Houssein Badra ]]>
                </dc:creator>
                <pubDate>Wed, 23 Aug 2023 21:06:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot--122-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this digital age, data flows freely across networks and devices. So protecting sensitive information from unauthorized access is crucial. That's where encryption comes in. </p>
<p>Encryption involves converting plain, readable data into an incomprehensible form. It's also essential to have a way to convert the data back into a readable form – otherwise the whole process makes no sense and isn't useful.</p>
<p>There are various popular encryption algorithms, each with its strengths and weaknesses. Understanding how these algorithms work is essential for programmers, as they need to choose the most appropriate one for their applications. </p>
<p>In this article, we will be build an application where users can encrypt images, and also revert the process using HTML, CSS, and JavaScript. </p>
<p>You will learn about working with images and how to encrypt them. The approach we will be using involves hiding one image inside another one, which is called <strong>Steganography.</strong> You will also practice some basic web development skills. It will be fun for sure!</p>
<h3 id="heading-heres-what-well-cover">Here's what we'll cover:</h3>
<ul>
<li>How images are represented on your computer</li>
<li>How to create the encryption algorithm </li>
<li>How to create the decryption algorithm</li>
<li>Photo encryption app code</li>
</ul>
<h2 id="heading-how-images-are-represented-on-your-computer">How Images Are Represented on Your Computer</h2>
<p>Understanding the way images are stored is critical before diving into encrypting them. </p>
<p>Images are represented on computers using a combination of pixels. A pixel is the smallest unit of an image and serves as the building block for displaying visuals on digital screens. </p>
<p>In memory, an image is an array of pixels. But now you're probably wondering, what is a pixel?</p>
<p>A pixel is assigned a specific color value which determines its appearance. The color values are typically represented using a combination of three primary colors: red, green, and blue – commonly known as RGB. </p>
<p>Each color channel is represented by a number value, ranging from 0 to 255, which determines the intensity of that color in the pixel. </p>
<p>For example:</p>
<ul>
<li>(0, 0, 0) represents black (absence of all colors)</li>
<li>(255, 255, 255) represents white (maximum intensity of all colors)</li>
<li>(255, 0, 0) represents pure red (maximum intensity of red, absence of green and blue)</li>
<li>(0, 255, 0) represents pure green (maximum intensity of green, absence of red and blue)</li>
<li>(0, 0, 255) represents pure blue (maximum intensity of blue, absence of red and green)</li>
</ul>
<p>By combining different intensities of red, green, and blue, we can represent a wide range of colors. This color information for each pixel is stored in memory, forming a digital image. For example to get yellow, we can combine red and green – (255, 255, 0) represents a yellow pixel.</p>
<h2 id="heading-how-to-use-the-encryption-algorithm">How to Use the Encryption Algorithm</h2>
<p>The key idea behind the algorithm we're going to use is that it uses 2 images: the image we want to encrypt and an image that will play the role of mask used to hide the image we want to encrypt. So we're going to combine these two images in a way that hides our main image and allows its extraction.</p>
<p>Since an image is made of pixels, what works for a single pixel works for an entire image. We will discuss how we will be combining 2 pixels in a way that hides one and allows reverting the process.</p>
<p>Now for the interesting part: if we look at numbers from 0 to 255, they all can be written as follows: a <em> 16 + b. For example 241 can be written as 15 </em> 16 + 1. But why we are doing this? </p>
<p>We will be using this to divide each pixel into two parts: first the a * 16 part and second b. The first part holds way more information than the second, since when a color degree goes up its intensity goes up. For example a (245, 137, 200) pixel can be split into (240, 128, 192) and (5, 9, 8). </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot--114-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image splitting</em></p>
<p>Now by comparing the high value pixel and the original one, you can see clearly that using the higher value pixel instead of the original one isn't going to change much of the information the original pixel holds.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot--115-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Comparing a higher value pixel and an original pixel's values</em></p>
<p>Now we will be using two pixels – one we're going to encrypt (the target pixel), and one we're going to hide the target pixel within (the encryption pixel), which can be random as we will see later. </p>
<p>First we will get the high value pixel from our target and encryption pixels. Then for the pixel we're trying to encrypt, we'll divide each number degree by 16. </p>
<p>For example if the original target pixel was (245, 137, 200) then the high value pixel will be (240, 128, 192) which will become (15, 8, 12) after applying a division by 16. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot--121-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Getting initial values and applying division</em></p>
<p>Now we have two new pixels: the high value pixel of the encryption pixel, and our target pixel high value pixel that got divided by 16. </p>
<p>Finally, to get an encrypted pixel, we'll sum up the values of these two pixels to get what we're looking for. </p>
<p>Take, for example, (26, 98, 234) and (245, 137, 200) as our encryption and target pixels, respectively. Let's first get the high value pixels. We will have (16, 96, 224) and (240, 128, 192), respectively. </p>
<p>Now divide the target pixel high value pixel by 16 and you'll have (15, 8, 12). Now add these two up and you'll be left with (31, 104, 236). And that's our encrypted pixel. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot--118-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Encrypted image</em></p>
<p>Now you know how to encrypt a pixel. By applying this to all the pixels of an image we will get an encrypted image. </p>
<p>To make this clearer, we will be hiding an image of Quincy Larson playing guitar within the freeCodeCamp logo 😂.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot--126-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image showing how we were able to hide Quincy Larson image in the freeCodeCamp logo</em></p>
<p>So to make this work we need two images: the one we need to encrypt and a random image to use as the encryption image. Also the two images should have the same dimensions to get the same number of pixels. </p>
<p>The reason we're using a random image to hide our image is to make it look like a very random image that will make no one suspicious.</p>
<h2 id="heading-how-to-use-the-decryption-algorithm">How to Use the Decryption Algorithm</h2>
<p>Now we need a way to revert the process, so to extract the target pixel from an encrypted pixel. Then we will have accomplished our goal.</p>
<p>Like we did earlier by combining 2 pixels to get an encrypted pixel, we will split back the encrypted pixel to get our target.</p>
<p>Every pixel can be split into two parts – the high value part (a * 16) and the low value part (b). Now we care about the b part since it comes from our target pixel. So we need to extract the b part from an encrypted pixel.</p>
<p>We can do this easily by mapping each number with its corresponding remainder of division by 16. We can do this using the modulo operator <strong>%</strong> which is a mathematical operator to get the remainder of the division of a number by another. For example 241 % 16 is 1 since since 241 is equal to 15 * 16 + 1.</p>
<p>By taking (31, 104, 236) and applying the modulo, we will be left with (15, 8, 12). As discussed earlier an encrypted pixel is the sum of the high value pixel of our encryption pixel or the mask pixel and the high value pixel of our target divided by 16. After the modulo is applied, the left value is the high value pixel of our target divided by 16.</p>
<p>Now multiply each number by 16 and you'll get exactly (240, 128, 192) which is the high value pixel of our target pixel.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Screenshot--117-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Decryption</em></p>
<p>Now as you can see, <strong>Steganography</strong> involves a small loss of each target pixel's information – but it's ok as you can see that it doesn't matter much in how the final image looks.</p>
<h2 id="heading-photo-encryption-app-code">Photo Encryption App Code</h2>
<p>And now since our toolkit is ready, let's code this image encryption application. All the code is available in this <a target="_blank" href="https://github.com/HousseinBadra/image-Encryption.git">GitHub repo</a>. The code itself is very straightforward. </p>
<p>First, create three files: an HTML file, a CSS file, and a JavaScript file. </p>
<p>For the HTML file we just need a canvas where we can see the resulting image. We also need two inputs of type file so we can upload our target and encryption images. And finally we need a button to save our encrypted image. </p>
<p>Also we will be using a small library to manage images created by Duke University, so we will have to include a script tag in the end of the body for this.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Image encryption app<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"index.css"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">canvas</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">canvas</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"Target"</span>&gt;</span>Upload target image<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"target"</span> <span class="hljs-attr">mltiple</span>=<span class="hljs-string">'false'</span> <span class="hljs-attr">accept</span>=<span class="hljs-string">'image/*'</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"Encryption"</span>&gt;</span>Upload encryption image<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"encryption"</span> <span class="hljs-attr">multiple</span>=<span class="hljs-string">'false'</span> <span class="hljs-attr">accept</span>=<span class="hljs-string">'image/*'</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Save image<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">'https://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js'</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index.js"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>The CSS is simple too. We will give the div wrapping the canvas a width and height of 300px, the canvas a width and height of 100%, and it'll have a black border. Now the div tags wrapping our inputs will get a slight margin of 10px on the top, and that's it.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span>{
  <span class="hljs-attribute">width</span>:<span class="hljs-number">300px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}

<span class="hljs-selector-tag">canvas</span>{
  <span class="hljs-attribute">width</span>:<span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>:<span class="hljs-number">100%</span>;
  <span class="hljs-attribute">border</span>:<span class="hljs-number">1px</span> solid black;
}

<span class="hljs-selector-class">.input-container</span>{
    <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p>Now for the JavaScript file. We will first select the two inputs, the canvas and the save button, and store them in four different variables. Then we will set the canvas width and height to 300px with JavaScript to avoid any future problems. And finally we'll set two variables, target and encryption, to store our encryption and target images.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> canvas = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"canvas"</span>);
<span class="hljs-keyword">const</span> targetInput = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#target"</span>);
<span class="hljs-keyword">const</span> encryptionInput = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#encryption"</span>);
<span class="hljs-keyword">const</span> saveButton = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"button"</span>);
<span class="hljs-keyword">let</span> target;
<span class="hljs-keyword">let</span> encryption;

canvas.width = <span class="hljs-number">300</span>;
canvas.height = <span class="hljs-number">300</span>;
</code></pre>
<p>Now we need to store the encryption and target images on user upload in the two variables we created earlier. Also set the <strong>onClick</strong> event of our save button to a function called <strong>save</strong> that we will create next. Finally, we'll create a function that takes a number as an argument and returns its high value as discussed in the encryption algorithm section.  </p>
<pre><code class="lang-js">targetInput.onchange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> img = <span class="hljs-keyword">new</span> SimpleImage(targetInput);
  img.setSize(<span class="hljs-number">300</span>, <span class="hljs-number">300</span>);
  target = img;
};

encryptionInput.onchange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> img = <span class="hljs-keyword">new</span> SimpleImage(encryptionInput);
  img.setSize(<span class="hljs-number">300</span>, <span class="hljs-number">300</span>);
  encryption = img;
};

saveButton.onclick = save;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getValue</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> x - (x % <span class="hljs-number">16</span>);
}
</code></pre>
<p>All that's left is to create the save function. First we will create a new image object with dimensions of 300 * 300. An image with these dimensions will have 90000 pixels. All of them have x and y coordinates from 0-299, since indexing starts from 0 in arrays. Looping from 0 to 300 twice will allow us to get all possible coordinates which means all pixels.</p>
<p>Now for each coordinate we will use the corresponding pixel of our encryption, target, and newly created image. Now we can set each pixel of our newly created image to the sum of the high value pixel of the encryption pixel and the high value pixel of our target divided by 16.</p>
<p>Now we will draw the newly created pixel on the canvas. And we'll need to get the URL of the image drawn into the canvas. We will be applying a small modification to the URL otherwise it will not work because we will get blocked by the browser for security reasons.</p>
<p>Finally, navigate to this URL by setting the window location to that URL. Then the encrypted image will be downloaded.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> img = <span class="hljs-keyword">new</span> SimpleImage(<span class="hljs-number">300</span>, <span class="hljs-number">300</span>);
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">300</span>; i++) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">300</span>; j++) {
      <span class="hljs-keyword">const</span> targetPixel = target.getPixel(i, j);
      <span class="hljs-keyword">const</span> encryptionPixel = encryption.getPixel(i, j);
      <span class="hljs-keyword">const</span> pixel = img.getPixel(i, j);
      pixel.setRed(
        getValue(targetPixel.getRed()) / <span class="hljs-number">16</span> + getValue(encryptionPixel.getRed())
      );
      pixel.setGreen(
        getValue(targetPixel.getGreen()) / <span class="hljs-number">16</span> +
          getValue(encryptionPixel.getGreen())
      );
      pixel.setBlue(
        getValue(targetPixel.getBlue()) / <span class="hljs-number">16</span> +
          getValue(encryptionPixel.getBlue())
      );
    }
  }
  img.drawTo(canvas);
  <span class="hljs-keyword">let</span> url = canvas
    .toDataURL(<span class="hljs-string">"image/png"</span>)
    .replace(<span class="hljs-string">"image/png"</span>, <span class="hljs-string">"image/octet-stream"</span>);
  <span class="hljs-built_in">window</span>.location.href = url;
}
</code></pre>
<p>And that's it for the code 😇.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we've learned a simple algorithm for image encryption. Modern algorithms are way more robust, as they use techniques like matrix multiplication to get solid hashing algorithms but they are very complex and require way more time and math knowledge than this one. </p>
<p>If you find this content enjoyable, <a target="_blank" href="https://www.linkedin.com/in/houssein-badra-943879214/">follow me on LinkedIn</a> as I post great content there 😉.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Symmetric and Asymmetric Key Encryption – Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ Encryption is a way of scrambling data so that it can only be read by the intended recipient. Encryption is an integral part of our daily lives – whether you are sending messages to friends on WhatsApp, visiting a website and your browser is making s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/encryption-explained-in-plain-english/</link>
                <guid isPermaLink="false">66d45e0e3dce891ac3a967dc</guid>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ information security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Daniel Adetunji ]]>
                </dc:creator>
                <pubDate>Wed, 05 Apr 2023 20:09:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/cover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Encryption is a way of scrambling data so that it can only be read by the intended recipient.</p>
<p>Encryption is an integral part of our daily lives – whether you are sending messages to friends on WhatsApp, visiting a website and your browser is making sure it's legitimate, or entering your bank details when buying something online. Encryption protects your data from potentially malicious and prying eyes.</p>
<p>This article will cover:</p>
<ul>
<li><p>Encryption algorithms and keys</p>
</li>
<li><p>Symmetric and asymmetric key encryption</p>
</li>
<li><p>How TLS/SSL uses both symmetric and asymmetric encryption</p>
</li>
</ul>
<h2 id="heading-encryption-algorithms-and-keys">Encryption Algorithms and Keys</h2>
<p>At the start of this article, I described encryption as a way of scrambling data so that it can only be read by the intended recipient. Let’s break down what this means.</p>
<p>Let's say you want to write a letter to your friend and want to ensure that only the friend can read its contents. How would you prevent the prying eyes of all the intermediaries the letter could pass through before it gets to your friend? That is, how do you prevent the postman, the concierge in their building, or one of their friends from reading the letter?</p>
<p>You start with an unscrambled letter that anyone can read. This is called <strong>plaintext</strong>. To scramble the contents of the message, you need an <strong>encryption algorithm</strong> and a <strong>key</strong>. The encryption algorithm uses the key to scramble the contents of the message. This encrypted message is called <strong>ciphertext</strong>.</p>
<p>The process of encryption is shown in the image below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-9.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>When your friend gets the message, they will need to descramble it using the <strong>algorithm</strong> and the <strong>key</strong>. This is illustrated below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The two key ingredients needed to send a message to your friend that only they can read is an <strong>encryption algorithm</strong> and a <strong>key</strong>.</p>
<p>The encryption algorithm is simply a mathematical formula designed to scramble data, while the key is used as part of the formula. The encryption algorithm is generic, but the key, used as an input to the algorithm, is what ensures the uniqueness of the scrambled data.</p>
<p>Let’s look at one of the simplest encryption algorithms, called the Caesar Cipher. In its simplest form, this algorithm simply replaces each letter by the next letter in the alphabet. So A becomes B, and B becomes C and so on.</p>
<p>With this algorithm, the text ‘Birthday Surprise’ becomes ‘Cjsuiebz Tvsqsjtf’, indistinguishable from gibberish to the untrained eye.</p>
<p>With the Caesar Cipher example, the <strong>algorithm</strong> is the formula used to replace each letter of the alphabet with another. The <strong>key</strong> is the number of shifts made between each letter. With a key of 0, A is A, an obviously poor choice of key as the data is unscrambled. With a key of 1, A becomes B. With a key of 10, A becomes K.</p>
<p>The Caesar Cipher is a relatively poor encryption algorithm. Why? Since there are only 26 letters in the English language, you can only produce a maximum of 25 possible ciphertexts. If you don’t have the key, you only need to shift each letter up to 25 times until you see coherent words and sentences, at which point you know that you have successfully decrypted the message.</p>
<p>A bad encryption algorithm is one that is easily decrypted by using a small amount of brute force (that is, trying every possible permutation) – and 25 possible ciphertexts is an objectively small number of possible options to go through.</p>
<p>Modern encryption algorithms like AES-256 used by AWS, GCP, and Azure for encrypting data are considerably more complicated and secure than the Caesar Cipher. Based on current computing capability, it would take trillions and trillions of years for the most advanced supercomputer to use brute force to decrypt data encrypted using AES-256 [<a target="_blank" href="https://scrambox.com/article/brute-force-aes/">1</a>]. Even the universe is not that old.</p>
<h2 id="heading-symmetric-and-asymmetric-key-encryption">Symmetric and Asymmetric Key Encryption</h2>
<p>The core of any encryption process is the encryption algorithm and the key. There are many types of encryption algorithms. But there are, broadly speaking, two types of keys – symmetric and asymmetric keys.</p>
<p>In symmetric key encryption, the same key used to encrypt the data is used to decrypt the data. In asymmetric key encryption, one key is used to only encrypt the data (the public key) and another key is used to decrypt (the private key).</p>
<h3 id="heading-asymmetric-key-encryption">Asymmetric key encryption</h3>
<p>First, let’s look at asymmetric key encryption with a simple analogy.</p>
<p>Imagine you wanted to send something to your friend, but it was absolutely essential that nobody else, except your friend, could have access to that object. So, your friend buys an indestructible box, fabricated from the strongest metal on the planet, and sends it to you so that you can place the object in it. Your friend also sends you the key that can only be used to lock the box.</p>
<p>Now, this box has one more special property. It has two keyholes. One keyhole to open the box, another to lock the box.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Naturally, this box will also need two keys – one to open and another to lock it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-12.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Both keys are similar, but not identical. As you can see in the image above, for example, the key used to open the box has two prongs while the key used to lock the box has three prongs.</p>
<p>As the sender of the object, all you have is the box to place the object in and a key to lock the box. Only your friend has the key that can unlock the box.</p>
<p>The key used to lock the box is called the public key, and cannot be used to open it, as that requires the private key. If anyone intercepted the package and made a copy of the public key, it could not be used to open the box, only to lock it. Only the person who holds the private key can open the box.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-13.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Asymmetric key encryption is used when there are two or more parties involved in the transfer of data. This type of encryption is used for encrypting data in transit, that is encrypting data being sent between two or more systems. The most popular example of asymmetric key encryption is <a target="_blank" href="https://nordvpn.com/blog/rsa-encryption/">RSA</a>.</p>
<h3 id="heading-symmetric-key-encryption">Symmetric key encryption</h3>
<p>Symmetric key encryption uses the same key for encryption and decryption. This makes sharing the key difficult, as anyone who intercepts the message and sees the key can then decrypt your data.</p>
<p>This is why symmetric key encryption is generally used for encrypting data at rest. AES-256 is the most popular symmetric key encryption algorithm. It is used by AWS for encrypting data stored in hard disks (EBS volumes) and S3 buckets. GCP and Azure also use it for encrypting data at rest.</p>
<h2 id="heading-how-tlsssl-uses-both-symmetric-and-asymmetric-encryption">How TLS/SSL Uses Both Symmetric and Asymmetric Encryption</h2>
<p>The main strength of symmetric key encryption is that it is computationally easier and faster to encrypt and decrypt data using a single key, just as it is easier to build a box with a single lock and key.</p>
<p>The weakness of symmetric key encryption is that if the key is exposed, your data is no longer securely encrypted. So, if you needed to share the key with an external party, there is a risk that the key could be exposed, leaving your data at risk of being decrypted.</p>
<p>Symmetric key encryption is ideal for encrypting data at rest, where you do not need to share the key with another system.</p>
<p>With asymmetric encryption, this is not a problem since two separate keys are used – the public key to encrypt data and the private key to decrypt data.</p>
<p>The public key can be easily shared with anyone and poses no risk to your data being decrypted, since the private key is needed for decryption.</p>
<p>The drawback of asymmetric key encryption is that the encryption and decryption process is slower and more complicated. Asymmetric key encryption is ideal for encrypting data in transit, where you need to share the key with another system.</p>
<p>What if there was a way of getting the speed and computational simplicity of symmetric encryption without increasing the risk of exposing your keys?</p>
<p>TLS/SSL encryption use both symmetric and asymmetric keys to encrypt data in transit, and is used with the HTTP protocol for secure communications over a computer network.</p>
<h3 id="heading-tlsssl-encryption-explained">TLS/SSL Encryption Explained</h3>
<p>TSL (Transport Layer Security) and SSL (Secure Sockets Layer) are often used interchangeably to mean the same thing. But when people say SSL, they often mean TLS.</p>
<p>TLS is generally considered more secure than SSL due to several improvements made to the protocol, such as stronger cryptographic algorithms. Due to security concerns with SSL, most modern web browsers and applications have dropped support for SSL and only support TLS. As a result, TLS has become the standard for secure communication over the internet.</p>
<h3 id="heading-how-to-use-symmetric-and-asymmetric-encryption-at-the-same-time">How to Use Symmetric and Asymmetric Encryption at the Same Time</h3>
<p>Let's say you want to securely send a parcel to your friend. But you don’t want to keep using the special indestructible box that has two keyholes and two locks. It is expensive, heavy and impractical to use for frequent communications. You still want to use an indestructible box, but one that is simpler, with a single lock and key.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>However, if you are using a box with only a single lock and key, you now need to figure out how to securely share the key for that simpler box with your friend.</p>
<p>Since the same key is used to both open and lock it, you cant just send the key to your friend without somehow protecting it first. If the key is intercepted and a copy is taken by someone, they can now open your box and take what is inside.</p>
<p>How can you securely share this key with your friend so that you can use this simpler box for future communication?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-15.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ol>
<li><p>First, your friend sends the box with the two locks plus the public key used to lock it. But you don’t want to keep using this box. You will only use this box once – to transfer the key for another simpler box that you will use for future exchanges.</p>
</li>
<li><p>You place the master key that will be used in future exchanges inside this box and lock it with the public key sent by your friend.</p>
</li>
<li><p>You send the locked box which contains a copy of the master key inside back to your friend.</p>
</li>
<li><p>Your friend uses his private key to open the box. Now you both have the master key and can be sure no one else has it since it was sent in a secure box</p>
</li>
<li><p>All future items are then placed in this simpler box with a single lock and key which can be opened and locked using the master key you just sent to your friend.</p>
</li>
</ol>
<h3 id="heading-tlsssl-encryption-sequence">TLS/SSL Encryption Sequence</h3>
<p>The analogy in the previous section neatly maps to how TLS/SSL encryption actually works. But there are some prerequisite steps which I ignored in this analogy, like creating a TCP connection and the server sending its certificate (Steps 1 and 2 below).</p>
<p>Also, Step 6 is a simplification of the process. In reality, the master key is used to generate a further set of keys that the client and server will use to encrypt and decrypt messages and also to authenticate that the messages were indeed sent by the client and server.</p>
<p>To read more about the low level detail, I’d recommend Chapter 8 of "<a target="_blank" href="https://www.amazon.co.uk/Computer-Networking-Global-James-Kurose/dp/1292405465/ref=sr_1_1?keywords=computer+networking+a+top-down+approach&amp;qid=1680219419&amp;sprefix=computer+netw%2Caps%2C168&amp;sr=8-1">Computer Networking</a>" by Kurose &amp; Ross.</p>
<p>But, at a high level, the sequence is as follows:</p>
<ol>
<li><p>Client establishes TCP connection with the server</p>
</li>
<li><p>Client verifies that the server is who it says it is – server sends certificate which has the public key. The accompanying private key remains with the server.</p>
</li>
<li><p>Client creates a master secret key and uses the server's public key to encrypt it. This master secret key is a symmetric key so the same key is used for encryption and decryption.</p>
</li>
<li><p>Client sends the encrypted master secret key to the server.</p>
</li>
<li><p>Server decrypts the encrypted master key using its private key.</p>
</li>
<li><p>All future messages between client and server now use the symmetric master key to encrypt and decrypt messages.</p>
</li>
</ol>
<h2 id="heading-best-of-both-worlds">Best of Both Worlds</h2>
<p>Using both symmetric and asymmetric key encryption gives you the speed of symmetric key encryption without compromising on the extra security provided by asymmetric key encryption.</p>
<p>But nothing comes for free, of course. With TLS, there is an added layer of complexity since you need to first use asymmetric keys to establish a secure connection before exchanging the symmetric key for future communication.</p>
<p>So by using both symmetric and asymmetric encryption, TLS/SSL gets the best of both worlds with limited downsides.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Encryption at Rest? Explained for Security Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Encryption is a technique for secure communication that converts plain text into a coded form that can only be deciphered with a secret key. Let's explore some of encryption's fun bits. Encryption works by using an algorithm to convert plaintext into... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/encryption-at-rest/</link>
                <guid isPermaLink="false">66b995d8a3099de4654e61b0</guid>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ information security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ David Clinton ]]>
                </dc:creator>
                <pubDate>Tue, 04 Apr 2023 15:49:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/pexels-cottonbro-studio-7319078.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Encryption is a technique for secure communication that converts plain text into a coded form that can only be deciphered with a secret key. Let's explore some of encryption's fun bits.</p>
<p>Encryption works by using an algorithm to convert plaintext into ciphertext, which is unreadable without a corresponding decryption key. </p>
<p>This article comes from <a target="_blank" href="https://www.udemy.com/course/complete-lpi-security-essentials-exam-study-guide/?referralCode=C2B6802EDB99578238B5">The Complete LPI Security Essentials Exam Study Guide</a>. You can also follow along with this video:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/kWBLfhf8eto" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>The encryption process takes the original data, and transforms it in a way that only someone with the correct decryption key can reverse the process and read the original data. This helps ensure that sensitive information is protected from unauthorized access or interception during transmission or storage.</p>
<h2 id="heading-understanding-encryption-tools">Understanding Encryption Tools</h2>
<p>Encryption at rest refers to the practice of protecting data that is stored on a device, such as a hard drive or a smartphone, by encoding it using encryption algorithms. The encrypted data can only be decrypted with the appropriate key, and this helps ensure that sensitive information remains confidential even if the device is lost or stolen. </p>
<p>This is a common security measure used to protect sensitive information such as credit card numbers, personal data, and confidential business information.</p>
<p>Password hashing is a technique for storing passwords in a secure manner by converting them into a cryptographic representation called a hash. The hash is created using a one-way function that transforms the password into a fixed-length string of characters that cannot be easily reversed to reveal the original password.</p>
<pre><code>$ echo -n mySecretPassword | sha256sum
<span class="hljs-number">2250e74</span>c6f823de9d70c2222802cd059dc970f56ed8d41d5d22d1a6d4a2ab66f  -
</code></pre><p>Salting is a security measure added to password hashing to increase its resilience against attacks. A salt is a random value that is generated for each password and combined with the password before it is hashed. </p>
<pre><code>$ openssl passwd -salt <span class="hljs-number">29</span> mytext
$<span class="hljs-number">1</span>$<span class="hljs-number">29</span>$WKQPJOxDf2nJLoPwT6cnz1
</code></pre><p>This results in a unique hash for each password, even if multiple users have the same password, making it much more difficult for an attacker to use pre-computed tables of hashes (such as rainbow tables) to crack the passwords. </p>
<p>When verifying a password, the salt is used to regenerate the hash, which is then compared to the stored hash to determine if the password is correct.</p>
<h2 id="heading-password-attack-tools">Password Attack Tools</h2>
<p>A rainbow table is a pre-computed table of hashes used to crack passwords by searching for a matching hash value. It is an optimization of a brute force attack that reduces the number of hashes that need to be calculated by reusing hashes computed for previous password guesses.</p>
<p>A Directory attack is a method of cracking passwords by using a large dictionary of words, phrases, and commonly used passwords to generate hashes and compare them to the target hashes. This type of attack is effective against weak passwords that are easily guessable.</p>
<p>A brute force attack is a way of cracking passwords by trying all possible combinations of characters until a match is found. It is a slow and resource-intensive method of cracking passwords, but it is effective against strong passwords that cannot be easily guessed. </p>
<p>Brute force attacks can be mitigated by using strong passwords, rate-limiting login attempts, and using encryption and hashing to store passwords securely.</p>
<h2 id="heading-symmetric-and-asymmetric-encryption">Symmetric and Asymmetric Encryption</h2>
<p>Symmetric cryptography, also known as shared-secret cryptography, is a type of encryption where the same key is used for both encryption and decryption of data. This means that both the sender and receiver of the data must have the same key and must keep it confidential. </p>
<p>Symmetric cryptography is fast and efficient but can be vulnerable if the key is compromised.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/slide-09.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram showing how symmetric encryption works</em></p>
<p>Asymmetric cryptography, also known as public-key cryptography, uses a pair of keys, one for encryption and another for decryption. The encryption key, known as the public key, can be widely distributed, while the decryption key, known as the private key, is kept confidential. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/slide-10.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram showing how asymmetric encryption works</em></p>
<p>Asymmetric cryptography is used for tasks such as digital signatures, key exchange, and data encryption, and is considered more secure than symmetric cryptography because the private key never needs to be transmitted or shared.</p>
<p>Hybrid cryptography is a combination of both symmetric and asymmetric cryptography. </p>
<p>In a typical hybrid encryption scheme, the data is encrypted using a symmetric algorithm, and the symmetric key is then encrypted using an asymmetric algorithm and sent to the recipient along with the encrypted data. The recipient uses their private key to decrypt the symmetric key, and then uses the symmetric key to decrypt the data. </p>
<p>Hybrid cryptography provides the security benefits of both symmetric and asymmetric cryptography, making it a commonly used encryption method.</p>
<h2 id="heading-public-key-infrastructure-pki">Public Key Infrastructure (PKI)</h2>
<p>PKI is a system for secure communication that uses a combination of public key cryptography, digital certificates, and certificate authorities (CAs) to authenticate the identity of parties involved in a communication and secure their communications.</p>
<p>Certificate Authorities (CAs) are organizations or entities that issue digital certificates, which are used to validate the identity of parties involved in a communication. </p>
<p>CAs act as trusted third parties that verify the identity of parties and issue certificates attesting to that identity. The certificate includes information such as the identity of the owner, the public key of the owner, and the digital signature of the CA.</p>
<p>Trusted Root-CAs are the highest level CAs in the PKI hierarchy. They are responsible for issuing certificates for intermediate CAs, who in turn issue certificates for end entities, such as individuals or organizations. </p>
<p>The trustworthiness of the entire PKI system is based on the trust in the root CAs. A trusted root CA is one that is widely recognized and trusted by users, systems, and applications. </p>
<p>The trusted root CA's certificate is usually pre-installed in software and devices, such as web browsers, to facilitate secure communication and verify the authenticity of digital certificates issued by other CAs.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>With what you've learned here, you're now ready to use encryption tools like <a target="_blank" href="https://www.veracrypt.fr/en/Home.html">VeraCrypt</a> and <a target="_blank" href="https://gnupg.org/">GnuPG</a> to protect the data you store on your local machines. You'll be able to properly assess the safety and integrity of the online and cloud storage platforms where you store data remotely.</p>
<p>This article and the accompanying video are excerpted from <a target="_blank" href="https://www.udemy.com/course/complete-lpi-security-essentials-exam-study-guide/?referralCode=C2B6802EDB99578238B5">my Complete LPI Security Essentials Exam Study Guide course</a>. And there's much more technology goodness available at <a target="_blank" href="https://bootstrap-it.com/">bootstrap-it.com</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Website Encryption Works ]]>
                </title>
                <description>
                    <![CDATA[ It's one thing to protect your data when it's sitting quietly on your own local machine and not bothering anyone. But moving data between locations – as you do whenever you open a website on a remote server or send an email attachment across the inte... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understanding-website-encryption/</link>
                <guid isPermaLink="false">66b9965f94b336889c600442</guid>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ David Clinton ]]>
                </dc:creator>
                <pubDate>Tue, 28 Mar 2023 17:35:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/pexels-markus-spiske-225769.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>It's one thing to protect your data when it's sitting quietly on your own local machine and not bothering anyone. But moving data between locations – as you do whenever you open a website on a remote server or send an email attachment across the internet – introduces a whole new set of vulnerabilities.</p>
<p>Plain text protocols transmit data in its unencrypted form, which makes it vulnerable to eavesdropping and tampering by third-party actors. Data transmitted over plain text protocols can be easily intercepted and read by anyone with access to the network. </p>
<p>If you're thinking of transmitting, say, credit card information or entering online banking passwords this way, then I would beg you to stop right now. You definitely want to add some encryption to your mix.</p>
<p>This article comes from <a target="_blank" href="https://www.udemy.com/course/complete-lpi-security-essentials-exam-study-guide/?referralCode=C2B6802EDB99578238B5">The Complete LPI Security Essentials Exam Study Guide</a>. You can also follow along using this video:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/v3Z0IRzTEcY" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-some-key-encryption-protocols">Some Key Encryption Protocols</h2>
<p>Transport encryption protocols, as it turns out, use encryption techniques to protect the data during transit. The data is encrypted before it is transmitted and decrypted after it is received. This provides protection against eavesdropping and tampering by third-party actors. </p>
<p>The most common transport encryption protocols are Secure Sockets Layer (SSL) and its successor, Transport Layer Security (TLS).</p>
<p>Beyond transport encryption, end-to-end encryption refers to a method of encrypting data from the sender's device to the recipient's device, such that only the sender and the recipient have access to the data. </p>
<p>E2EE provides protection for the entire transmission, including protection from intermediaries such as network administrators, service providers, and hackers. E2EE is typically used in applications such as instant messaging, email, and file sharing.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/what-is-https-http-vs-https-meaning-and-how-it-works/">HTTPS (the Hypertext Transfer Protocol Secure)</a> is a protocol that is commonly used to secure web pages. It uses SSL or TLS encryption to secure the connection between a web browser and a server, ensuring that sensitive information, such as login credentials and credit card numbers, cannot be intercepted by third-party actors.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/what-is-tls-transport-layer-security-encryption-explained-in-plain-english/">TLS (Transport Layer Security)</a> is a security protocol that provides encryption and integrity for data transmission over the internet. It is the successor to SSL and is currently widely used to secure web connections, email, and other internet protocols. TLS uses public-key cryptography to negotiate a shared secret key, which is then used to encrypt the data.</p>
<h2 id="heading-how-to-identify-website-encryption">How to Identify Website Encryption</h2>
<p>You can identify if a website is encrypted by looking for the padlock icon and the "https" prefix in the URL of the website. The padlock icon is usually located in the address bar of your web browser and indicates that the connection between your browser and the website is secure. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-28-at-10.11.06-AM.png" alt="Image" width="600" height="400" loading="lazy">
<em>The padlock showing that freecodecamp.org/news is secure</em></p>
<p>The padlock icon can also show the level of security, such as the type of encryption used, the identity of the website, and the validity of the SSL/TLS certificate.</p>
<p>The "https" prefix in the URL of the website indicates that the connection is encrypted and secure. The "s" in "https" stands for "secure". In contrast, unencrypted websites use the "http" prefix in their URL.</p>
<p>It's important to note that while the padlock icon and the "https" prefix indicate that a website is encrypted, they don't guarantee the authenticity or security of the website. Always be cautious when entering sensitive information, such as login credentials or credit card numbers, into any website and make sure to verify the identity of the website before entering any sensitive information.</p>
<p>TLS-encrypted websites can acquire padlocks and "HTTPS" as a URL prefix by requesting a certificate from a certificate authority. Once upon a time, CAs would charge good money for issuing certificates, and they would take their time about it, too. However, that was before Let's Encrypt.</p>
<p><a target="_blank" href="https://letsencrypt.org/">Let's Encrypt</a> is a non-profit certificate authority that provides free, automated, and open-source SSL/TLS certificates. These certificates are used to encrypt and secure web communications, providing privacy and data integrity to internet users. </p>
<p>The main value of Let's Encrypt is its ability to make encryption more accessible and affordable. By offering free SSL/TLS certificates, Let's Encrypt makes it easier and more cost-effective for website owners to secure their websites and protect the privacy of their users.</p>
<p>In addition to being free, Let's Encrypt certificates are also easy to obtain and install. The certificates are issued through <a target="_blank" href="https://certbot.eff.org/">an automated process</a>, making it possible for website owners to obtain a certificate in minutes, rather than waiting for days or weeks for manual processing.</p>
<h2 id="heading-understanding-x509-certificates">Understanding X.509 Certificates</h2>
<p>Let's understand those certificates a bit better. X.509 is a standard for digital certificates that is widely used on the internet to establish trust between parties. </p>
<p>An X.509 certificate is a digital document that contains information about the identity of an entity and is signed by a trusted third-party known as a certificate authority (CA).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/slide-31-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram of how X.509 certificates work</em></p>
<p>The process of obtaining an X.509 certificate involves jumping through some hoops:</p>
<ul>
<li>The entity seeking the certificate (a website owner, for instance) generates a certificate signing request (CSR) which includes information about their identity and public key.</li>
<li>The CA verifies the identity of the entity and issues the X.509 certificate. The certificate includes the public key of the entity, information about the identity, and the signature of the CA.</li>
<li>The entity installs the certificate on their web server and configures their website to use HTTPS, which enables encrypted communication between the server and the client.</li>
</ul>
<p>The process of revoking an X.509 certificate involves the following steps:</p>
<ul>
<li>The entity or the CA detects that the certificate needs to be revoked. For example, the entity may have lost control of their private key, or the identity information in the certificate may have changed.</li>
<li>The entity or the CA requests the revocation of the certificate.</li>
<li>The CA updates its certificate revocation list to indicate that the certificate has been revoked. The CRL is a list of all the revoked certificates that the CA has issued.</li>
<li>When a client connects to a website, it checks the certificate against the CRL to make sure it has not been revoked. If the certificate has been revoked, the client will not trust the website and will not establish a secure connection.</li>
</ul>
<p>An X.509 certificate contains several key fields that provide information about the identity of the entity and the certificate itself. Some of the key fields are:</p>
<ul>
<li>The version number of the X.509 certificate format.</li>
<li>A unique identifier assigned to the certificate by the certificate authority (CA).</li>
<li>Information about the entity that the certificate represents, such as its name, address, and public key.</li>
<li>Information about the CA that issued the certificate, such as its name and address.</li>
<li>The start and end dates of the certificate's validity period, during which the certificate can be trusted.</li>
<li>The public key of the entity that the certificate represents.</li>
<li>The algorithm used by the CA to sign the certificate and verify its authenticity.</li>
<li>The signature of the CA, which is used to verify the authenticity of the certificate.</li>
</ul>
<h2 id="heading-perfect-forward-secrecy-pfs">Perfect Forward Secrecy (PFS)</h2>
<p>There's one more thing we should touch on before leaving the world of encrypted web sessions. Perfect Forward Secrecy (PFS) is a security property in cryptography that ensures that the confidentiality of past sessions cannot be compromised even if the encryption keys used in those sessions are later disclosed. </p>
<p>This is achieved by using ephemeral keys, which are generated for each session and discarded after the session is completed. The ephemeral keys are used to establish a secure key exchange, and are never stored, so they cannot be used to decrypt past sessions even if they are later disclosed. </p>
<p>PFS is an important property in secure communication protocols, as it ensures that even if an attacker is able to obtain the encryption keys for a single session, they will not be able to use those keys to compromise past or future sessions.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>With this knowledge of encryption's inner workings, you'll be better able to assess the safety of your internet browsing activities. You'll also know what you need to do to encrypt the websites you yourself might manage.</p>
<p>This article and the accompanying video are excerpted from <a target="_blank" href="https://www.udemy.com/course/complete-lpi-security-essentials-exam-study-guide/?referralCode=C2B6802EDB99578238B5">my Complete LPI Security Essentials Exam Study Guide course</a>. And there's much more technology goodness available at <a target="_blank" href="https://bootstrap-it.com/">bootstrap-it.com</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Does a VPN Work? Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Do you worry about online security while using public Wi-Fi? Or has someone told you that you might get hacked when using an insecure connection and someone will steal all your details? Well, you might have also heard that you should use a VPN to pro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-does-a-vpn-work/</link>
                <guid isPermaLink="false">66ba2a44c346e93df556afea</guid>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ information security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ privacy ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ vpn ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tejan Singh ]]>
                </dc:creator>
                <pubDate>Tue, 24 Jan 2023 00:08:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/privecstasy-CXlqHmQy3MY-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Do you worry about online security while using public Wi-Fi? Or has someone told you that you might get hacked when using an insecure connection and someone will steal all your details?</p>
<p>Well, you might have also heard that you should use a VPN to protect your online privacy. But do you have any idea what it is and how it works?</p>
<p>Don’t worry – in this article, we will go through everything that you need to know to about what and when to use a VPN and when to avoid using it. So, without any further delay, let’s get started.</p>
<h2 id="heading-what-is-a-vpn">What is a VPN?</h2>
<p>VPN stands for Virtual Private Network. It is a type of network you can connect to which will help you protect your online security and privacy.</p>
<p>A VPN acts as a tunnel through which all your data goes from your location to your destination. It's all properly encrypted and secure so that any outside party can’t see what data you are transferring.</p>
<p>There are many advantages to using VPNs, such as:</p>
<ul>
<li>Privacy</li>
<li>Anonymity</li>
<li>Security</li>
<li>Encryption</li>
<li>Masking or changing your original IP address, so others can’t track you</li>
</ul>
<p>We'll discuss these advantages and more further down in this article, but first you need to understand how a VPN works so you can use it properly.</p>
<h2 id="heading-how-does-a-vpn-work">How Does a VPN Work?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-223.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.cactusvpn.com/beginners-guide-to-vpn/vpn-encryption/">Image source</a></em></p>
<p>A VPN works by routing / forwarding all your data from your laptop or phone through your VPN to the internet, rather than directly through your ISP. </p>
<p>When you use a VPN, it encrypts all your data on the client side. Then after the data is encrypted, it's passed through a VPN tunnel which others can’t access, and then it reaches the internet.</p>
<p>But before going through the VPN tunnel, the request is first sent to your ISP, but as it's encrypted, ISP can’t figure out what you are trying to access. So it forwards your request to your VPN server. Then the VPN sends the request to your desired IP address or website.</p>
<h2 id="heading-advantages-of-using-a-vpn">Advantages of Using a VPN</h2>
<p>Now let's discuss some of the advantages in more detail.</p>
<h3 id="heading-unblock-websites-amp-bypass-filters">Unblock websites &amp; bypass filters</h3>
<p>There might be scenarios where you won’t be able to access certain websites which are blocked by your office or school or college department, but you still want or need to access them. </p>
<p>These websites may include social networking sites, movie downloading websites, or any kind of media streaming websites. </p>
<p>In these cases, a VPN will help you bypass all the blocking filters and let you access the websites that you wish to access without anyone’s help and others will have no idea what you're accessing.</p>
<h3 id="heading-bypass-regional-restrictions">Bypass regional restrictions</h3>
<p>People in certain countries cannot access any websites outside their country like YouTube or Google because their government doesn't want them to use any other websites. </p>
<p>If you're in one of these places and still want to access these blocked websites, then a VPN can help by bypassing all the regional restrictions. You'll be able to access all the restricted or blocked content without letting the government know about your activity.</p>
<h3 id="heading-access-geo-blocked-websites">Access geo-blocked websites</h3>
<p>There are several websites, special offers, and services which are available for specific countries or regions. But what if you also want to take advantage of that opportunity, but it’s not accessible in your region?</p>
<p>A VPN can help you by changing your IP address which will change your location on the internet. Then you will seem to be a user from that country and you can also have all the benefits that people in that particular region are enjoying.</p>
<h3 id="heading-change-your-ip-address">Change your IP address</h3>
<p>Your ISP is tracking your every move on the internet – which websites you are visiting, the amount of time you are spending there, and when you log in and log out from a website. </p>
<p>But sometimes you may need to hide your browsing history/activity from your local network/ISP. In that case, using a VPN can help you keep all your records encrypted, and your ISP will have no idea what you are doing with your internet. All your internet browsing activity will be masked by the VPN.</p>
<h3 id="heading-online-anonymity-and-privacy">Online anonymity and privacy</h3>
<p>Everything on the internet is tracking you. Website and web servers that you use or visit know your IP and location. That can be used to their advantage and every time you visit the same website, they will know that it’s you, and they will track your usage and your behavior. This isn't necessarily a good thing since you are giving them a lot of information without knowing what. </p>
<p>A VPN can help keep your identity anonymous so you don't need to worry about identity leakage or any kind of tracking activity.</p>
<h3 id="heading-enhanced-security">Enhanced security</h3>
<p>As discussed above, using VPN can keep your identity safe and also keeps your data encrypted while you browse the internet. As a result, it enhances security and the chances that someone might hack you will be lower. </p>
<p>So, using VPN will keep you safe when you are using any public Wi-Fi or browsing websites which are not secure.</p>
<h2 id="heading-disadvantages-of-vpn">Disadvantages of VPN</h2>
<p>There are some downsides to using a VPN as well:</p>
<h3 id="heading-slows-your-connections">Slows your connections</h3>
<p>VPNs tend to slow your internet connection. As the VPN servers might be located far away from you (might be in some other geographic location or country), your data will need to travel farther across the internet and will slow your connection speed.</p>
<h3 id="heading-vpns-log-your-activities">VPNs log your activities</h3>
<p>VPNs keep logs of your activities. You heard right. Regardless of what policies they have, even if they say that they don’t keep any logs, they do. Governments have taken action against VPNs, and the VPN companies tend to deliver all the activity logs of a user in cases of international crime, terrorist activity, or hacking. </p>
<p>So – it goes without saying – make sure you don’t use VPNs for any illegal activities. Use it instead to protect yourself and your identity from malicious hackers.</p>
<h3 id="heading-specific-blockades-of-vpn-services">Specific blockades of VPN services</h3>
<p>There are many websites and streaming services like Netflix which will not allow any unusual VPN users to access their content. So, there might be many cases where your VPN will help, but there are many websites and servers which won't allow you to access them using a VPN.</p>
<h3 id="heading-cost">Cost</h3>
<p>Although there are many free VPN services which you can use, if you are planning to use VPN on regular basis then you might need to purchase a paid version. Free VPNs don’t provide good speed and the amount of data usage is also limited on a daily basis. VPNs cost around $10 to $15 per month for the premium services.</p>
<h2 id="heading-how-a-vpn-can-help-you-protect-your-online-identity">How a VPN Can Help You Protect Your Online Identity</h2>
<p>When you use the internet, the data you send or request through a web browser to any server (for example, when Google searching), along with your request, IP address (for example, your laptop or mobile) and destination IP address (like Google) first reaches your ISP. </p>
<p>The ISP monitors all your activity and then forwards your request to the destination IP address and also gets back the information in the same way.</p>
<p>All your information travels through a middle station, your ISP. They have all your history of using the internet and how you are using the internet. But when you are using a VPN, that's not the case.</p>
<p>Whenever you send any request to any website or server, instead of connecting directly to the server, it first reaches the VPN server. There, all your requests and information are encrypted and then sent forward to your desired website.</p>
<p>Your ISP is still there to monitor things. But if you're using VPN, it will automatically change the IP address of your destination to a different IP address and encrypt the destination IP address. This way, your ISP won’t be able to read it and will assume that all your requests were going to the IP address of the VPN. So it will forward all your requests to the VPN.</p>
<p>When your request or information reaches your VPN, it will be decrypted, and it will forward your request to the website you wish to access. The website or server will get the VPN request and will assume that the request is coming from that VPN server. It will allow the VPN to access the website and you'll be able to visit the website without letting your ISP know.</p>
<p>Similarly, when you download a file, all the traffic or information flows from a web server to the VPN. The VNP encrypts all the information and then forwards it to your ISP – which will still have no idea what’s going on, as the information is encrypted.</p>
<p>Finally, the info gets forwarded to your laptop or mobile. When it reaches your device, it will be decrypted, and you will be able to view the website as it's available to others.</p>
<h2 id="heading-frequently-asked-vpn-questions">Frequently Asked VPN Questions</h2>
<h3 id="heading-is-vpn-traffic-encrypted">Is VPN traffic encrypted?</h3>
<p>YES! As explained above, all the traffic passed through VPN is encrypted through various encryption algorithms like the RSA (Rivest–Shamir–Adleman) algorithm, AES (Advanced Encryption Standard), and others.</p>
<h3 id="heading-what-is-an-always-on-vpn-what-is-a-kill-switch">What is an always-on VPN? What is a kill switch?</h3>
<p>I will try to explain this concept in approachable terms. Always on VPN is a service which allows you to automatically connect to a VPN whenever you are connected to the internet. These kinds of services are used by companies which don’t want outside users to access their data and only want their employees to access their data from an outside, remote location.</p>
<p>Whenever an employee, company, or user who has access to the resources tries to access, then they need to enter valid credentials to automatically connect to the VPN. This also allows them to access all their work and resources present inside the company from an outside or remote location.</p>
<p>A VPN kill switch is another major feature offered by VPN service providers. Whenever there is a sudden or accidental loss of a VPN connection, in that case, your information might get exposed.</p>
<p>To deal with that, a VPN kill switch is used to terminate your internet connection when there is no VPN connection. This is a very useful feature for protecting your data from outside users.</p>
<p>So, when the kill switch is ON, internet connections will be terminated. But when the kill switch is OFF, then the internet will not be terminated when there is a loss of VPN connection.</p>
<h3 id="heading-is-a-vpn-necessary">Is a VPN necessary?</h3>
<p>A VPN is not strictly necessary depending on your needs and activities, but it's useful. </p>
<p>Using VPN helps protect your online security, privacy, and anonymity. It will also protect you from malicious threats and trackers when you are using an unsecured website or using any unknown wi-fi connection which might be public.</p>
<h3 id="heading-is-a-vpn-100-safe">Is a VPN 100% safe?</h3>
<p>Nothing on the internet is 100% secure. There are and will always be ways to expose services like VPNs. But using a VPN will typically help you more than it'll harm you.</p>
<h3 id="heading-is-vpn-legal-in-india">Is VPN legal in India?</h3>
<p>Yes! VPNs are legal in India and can be used freely to access any content on the internet without any restrictions. Just remember that you should not use it for any illegal activity, as there are always ways to track you regardless of what VPN service you use.</p>
<h3 id="heading-do-vpns-log-or-store-my-data">Do VPNs log or store my data?</h3>
<p>VPNs log all your data and store all information, and it might be able to share your data with government authorities. There have been many cases where VPNs say they have a no logs policy but still keep logs of users and shared them with authorities.</p>
<h3 id="heading-what-is-the-main-difference-between-a-firewall-and-a-vpn">What is the main difference between a firewall and a VPN?</h3>
<table>
 <tbody><tr>
  <td>
  <p><span>&nbsp;&nbsp;Firewall</span></p>
  </td>
  <td>
  <p><span>VPN</span></p>
  </td>
 </tr>
 <tr>
  <td>
  <ul>
   <li><span>&nbsp;&nbsp;Software or hardware
       device&nbsp;</span></li>
  </ul>
  <p><span>&nbsp;</span></p>
  </td>
  <td>
  <ul>
   <li><span>Service or Server</span></li>
  </ul>
  <p><span>&nbsp;</span></p>
  </td>
 </tr>
 <tr>
  <td>
  <ul>
   <li><span>&nbsp;&nbsp;acts as a filter to allow
       and block websites and users to access a particular website</span></li>
  </ul>
  </td>
  <td>
  <ul>
   <li><span>it encrypts the IP address and
       information from both source and destination and allows users to access
       all blocked or restricted websites and even private network information.</span></li>
  </ul>
  </td>
 </tr>
</tbody></table>

<h2 id="heading-conclusion">Conclusion</h2>
<p>VPNs definitely have their advantages and disadvantages. Organizations use them to protect their private networks and information. You can also use one to access blocked content, and to protect your privacy, anonymity and security. Using a VPN for legal activities is beneficial and adds extra security.</p>
<p>When you are not sure about using or accessing any unknown (public/private) wi-fi or unsecured untrusted website, then you should always use a VPN (free/paid). Although paid VPNs have their advantages, occasionally using free VPNs won’t harm you and will still serve the purpose.</p>
<p>And just remember – don't ever try to use a VPN to perform any illegal activities.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Homomorphic Encryption? ]]>
                </title>
                <description>
                    <![CDATA[ By Aris Zagakos In this article we will discuss Homomorphic Encryption, the problem that it solves, and the different types that exist.  Then we will write code in Python to show some of its capabilities in action. Here's what we'll cover: What is H... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/introduction-to-homomorphic-encryption/</link>
                <guid isPermaLink="false">66d461c5787a2a3b05af4423</guid>
                
                    <category>
                        <![CDATA[ cybersecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 26 Apr 2022 23:01:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/Homomorphic-Encryption-3--1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Aris Zagakos</p>
<p>In this article we will discuss Homomorphic Encryption, the problem that it solves, and the different types that exist. </p>
<p>Then we will write code in Python to show some of its capabilities in action.</p>
<h2 id="heading-heres-what-well-cover">Here's what we'll cover:</h2>
<ol>
<li>What is Homomorphic Encryption?</li>
<li>Advantages of Homomorphic Encryption</li>
<li>Types of Homomorphic Encryption</li>
<li>Paillier Cryptosystem</li>
<li>Conclusion and resources to learn more</li>
</ol>
<h2 id="heading-what-is-homomorphic-encryption">What is Homomorphic Encryption?</h2>
<p>The name Homomorphic comes from the algebra term Homomorphism.</p>
<blockquote>
<p>"Homomorphism is a structure-preserving map between two algebraic structures of the same type (such as two groups, two rings, or two vector spaces)." (Source: Wikipedia)</p>
</blockquote>
<p><code>Homomorphic Encryption</code> is a form of encryption that allows users to perform binary operations on encrypted data without ever decrypting the data. </p>
<p>This form of encryption allows information to be encrypted and outsourced to cloud services/environments for processing, without accessing the raw data.</p>
<h2 id="heading-advantages-of-homomorphic-encryption">Advantages of Homomorphic Encryption</h2>
<p>In today's world, if we want to perform computations on encrypted data such as mathematical operations, we have to decrypt them first. Then we have to make our computations, and finally encrypt the data again in order to send them back.</p>
<p>But what happens when the encrypted data is very sensitive and we don't want other services to have access to them? Here is where <code>Homomorphic encryption</code> comes into play.</p>
<p>A more practical example would be a system/service that processes medical information in order to diagnose if a patient has a condition or not.</p>
<p>The data we'd be sharing probably includes very sensitive information about the patient's medical history. So this is something we want to ensure won't be accessible to anyone else.</p>
<p>Using <code>Homomorphic Encryption</code>, the system/service can process the required computations on the encrypted data, returning the result of the diagnosis without knowing which information is being proceeded.</p>
<p>Sharing sensitive information through different platforms gives away our privacy. On the other hand, being able to modify and perform operations on data while they are encrypted ensures the privacy of the data.</p>
<h2 id="heading-types-of-homomorphic-encryption">Types of Homomorphic Encryption</h2>
<p>The goal of Homomorphic Encryption is the following: given any input such as<br><code>input := Enc(x1),...,Enc(xn)</code>, for any arbitrary function <code>f</code> that applies an infinite number of additions or multiplications such as <code>value := f(Enc(x1),...,Enc(xn))</code>, the value can be computed while the input is encrypted.</p>
<p>The arithmetic operations, at the end of the day, are implemented at the hardware level (as anything else) under arithmetic or boolean circuits. </p>
<p>The operations that we want to perform are Homomorphic Addition and Homomorphic Multiplication. The names Addition and Multiplication are given due to the similar behavior of binary addition and binary multiplication that logic gates XOR and AND have correspondingly. The combination of these two gates can represent any boolean function.</p>
<p>The factors make the complexity to be varied based on the number and the kind of operations.</p>
<p>Because of these restrictions and the problem of constructing a fully Homomorphic Encryption algorithm (supporting both Homomorphic Addition and Homomorphic Multiplication), over time there have been different schemes implemented.</p>
<p>The most common types of Homomorphic encryption are:</p>
<ul>
<li>Partially Homomorphic Encryption (PHE)</li>
<li>Somewhat Homomorphic Encryption (SHE)</li>
<li>Fully Homomorphic Encryption (FHE)</li>
</ul>
<p>Partial Homomorphic Encryption (PHE) allows only one operation to be performed on the ciphertext an infinite number of times. This operation can be only addition or only multiplication. </p>
<p>Partially Homomorphic Encryption algorithms are easier to design and are very useful in applications that use one arithmetic operation.</p>
<p>Somewhat Homomorphic Encryption (SHE) allows both addition and multiplication to be performed, but for a limited number of times. This limitation is evaluated to a certain depth in the circuit logic. This is a very important milestone to reach Fully Homomorphic Encryption.</p>
<p>Fully Homomorphic Encryption (FHE) allows both addition and multiplication to be performed on the ciphertext an infinite number of times, supporting arbitrary computations on encrypted data. </p>
<p>The major problem with Fully Homomorphic Encryption is the cost efficiency both in terms of speed and storage requirements compared to plaintext operations.</p>
<h2 id="heading-paillier-cryptosystem">Paillier Cryptosystem</h2>
<p>The Paillier Cryptosystem was invented by Pascal Paillier in 1999. It is a Partial Homomorphic Encryption (PHE) scheme and Additively Homomorphic. </p>
<p>It supports only the addition of two ciphertexts and not the multiplication between them. Also, a plaintext number can be added or multiplied to the ciphertext.</p>
<p>In this example we use <code>python-paillier</code>, a Python library for Partially Homomorphic Encryption using the Paillier cryptosystem.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> phe <span class="hljs-keyword">import</span> paillier

num1 = <span class="hljs-number">10</span>
num2 = <span class="hljs-number">20</span>

pub_key, priv_key = paillier.generate_paillier_keypair()
cipher_num1, cipher_num2 = pub_key.encrypt(num1), pub_key.encrypt(num2)

<span class="hljs-comment"># add two encrypted numbers together</span>
result = cipher_num1 + cipher_num2
result = priv_key.decrypt(result)
print(<span class="hljs-string">"add two encrypted numbers together:"</span>,result)

<span class="hljs-comment"># add an encrypted number to a plaintext number</span>
result = cipher_num1 + <span class="hljs-number">5</span>
result = priv_key.decrypt(result)
print(<span class="hljs-string">"add an encrypted number to a number:"</span>,result)

<span class="hljs-comment"># multiply an encrypted number by a plaintext number</span>
result = cipher_num1 * <span class="hljs-number">10</span>
result = priv_key.decrypt(result)
print(<span class="hljs-string">"multiply an encrypted number to a number:"</span>,result)
</code></pre>
<p>In the example above we generated a key pair of a public and a private key. Next, we encrypted both <code>num1</code> and <code>num2</code> with the public key and performed operations on their ciphertexts.</p>
<p>First, we added the two ciphers. After that, we took the <code>cipher_num1</code> and added to it a plaintext number. Last, we did the same process as before, but instead of addition, we multiplied the <code>cipher_num1</code> with a plaintext number this time. </p>
<p>The calculation of these operations takes place while the data is encrypted. Also, we can verify the integrity of the result each time by decrypting it using the private key.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Homomorphic Encryption (HE) looks like a dream when it comes to data privacy and protection. But its poor performance and high costs still keep it out of commercial/production applications. </p>
<p>But there have been many improvements in terms of speed lately. With the current pace, I believe that it will be adapted worldwide during the next years.</p>
<h3 id="heading-resources">Resources</h3>
<ul>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Homomorphism">Homomorphism</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Homomorphic_encryption">Homomorphic encryption</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Paillier_cryptosystem">Paillier cryptosystem</a></li>
<li><a target="_blank" href="https://python-paillier.readthedocs.io/en/develop/">python-paillier</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Manage Encryption at Scale with Envelope Encryption & Key Management Systems ]]>
                </title>
                <description>
                    <![CDATA[ Recently at work, I came across an interesting method to handle encryption at scale called envelope encryption.  First of all, it increases security and helps you ease out the management of encryption keys. But it's also a highly recommended pattern ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/envelope-encryption/</link>
                <guid isPermaLink="false">66bb457cce106b2510feda0d</guid>
                
                    <category>
                        <![CDATA[ Application Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rohit Jacob Mathew ]]>
                </dc:creator>
                <pubDate>Wed, 27 Oct 2021 22:52:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/1400-x-600.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Recently at work, I came across an interesting method to handle encryption at scale called envelope encryption. </p>
<p>First of all, it increases security and helps you ease out the management of encryption keys. But it's also a highly recommended pattern by PCI-DSS (Security Standard for Credit Card Processing) and results in much stronger data privacy and data protection of Personally Identifiable Information (PII). </p>
<p>When we think of data, there are 3 places we can think of encrypting it:</p>
<ul>
<li>At Rest – on hardware storage devices like a disk or in your devices</li>
<li>In Transit – while moving data between different locations like server to server through API calls</li>
<li>In Use – while it's being used by a server (this is a new concept and is still being researched)</li>
</ul>
<p>We will be dealing primarily with encryption at rest, and envelope encryption is a popular pattern for this use case.</p>
<h2 id="heading-so-what-is-envelope-encryption">So What is Envelope Encryption? 🤔</h2>
<p>Envelope encryption involves encrypting your data with a Data Encryption Key, then encrypting the Data Encryption Key (DEK) with a Customer Master Key (CMK). </p>
<p>You then store both the encrypted data and the encrypted DEK alongside each other in the database. This practice of using a wrapping key to encrypt data keys is known as envelope encryption.</p>
<p>You need to understand these two keys before we see how the encryption process takes place:</p>
<ol>
<li>Customer Master Key (CMK)</li>
<li>Data Encryption Key (DEK)</li>
</ol>
<h3 id="heading-customer-master-keysroot-keyskey-encryption-keys-cmk">Customer Master Keys/Root Keys/Key Encryption Keys (CMK)</h3>
<p>These are symmetric keys used to encrypt, decrypt, and re-encrypt data. They can also generate Data Encryption Keys that you can use outside of the KMS system. They follow the below rules:</p>
<ul>
<li>Access to these keys must be restricted to the least endpoints</li>
<li>Access to these keys should be secured through ACL</li>
<li>These keys must be stored in a location that is secure like a KMS of a Hardware Security Module (to comply with <a target="_blank" href="https://en.wikipedia.org/wiki/FIPS_140-2">FIPS 140-2</a>)</li>
</ul>
<p>In systems like Google Cloud Key Management Service, you have a hierarchy of keys as seen below (you can find more information <a target="_blank" href="https://cloud.google.com/security/encryption/default-encryption#encryption_key_hierarchy_and_root_of_trust">here</a>):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1635198625726/DgTfDZpGk.png" alt="Encryption Key Hierarchy at Google" width="1281" height="1625" loading="lazy"></p>
<h3 id="heading-data-encryption-keys-dek">Data Encryption Keys (DEK)</h3>
<p>Data keys are encryption keys you can use to encrypt data, including large amounts of data and other data encryption keys. </p>
<p>Unlike CMK's, which can't be downloaded, data keys are returned to you for use outside of the KMS. Some of the best practices for DEKs are as follows:</p>
<ul>
<li>You should generate DEKs locally</li>
<li>When stored, always ensure DEKs are encrypted at rest</li>
<li>For easy access, store the DEK near the data that it encrypts</li>
<li>Generate a new DEK every time you write the data. This means you don't need to rotate the DEKs.</li>
<li>Do not use the same DEK to encrypt data from two different users</li>
<li>Use a strong algorithm such as 256-bit Advanced Encryption Standard (AES)</li>
</ul>
<h2 id="heading-envelope-encryption-process">Envelope Encryption Process</h2>
<p>First, an API request is sent to KMS to generate Data key using CMK.</p>
<p>Then the KMS returns a response with Plain Data key and Encrypted Data key (using CMK).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1635198711784/Bm05yko4g.png" alt="Generate Data Keys" width="426" height="531" loading="lazy"></p>
<p>Data is encrypted using the Plain Data key, and then the Plain Data key is removed from memory.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1635198735343/vjqUrCTa1.png" alt="Encryption Process" width="479" height="289" loading="lazy"></p>
<p>The Encrypted Data and Encrypted Data Key are packaged together as an envelope and stored.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1635198756845/mXf8rwGhU.png" alt="Encryption Process With Data Stored at Rest" width="654" height="238" loading="lazy"></p>
<h2 id="heading-decryption-process">Decryption Process</h2>
<p>First, the Encrypted Data key is extracted from the envelope.</p>
<p>Then an API request is sent to KMS using Encrypted Data key which has information about CMK to be used in KMS for decryption.</p>
<p>The KMS returns a response with the Plain Data Key.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1635198816460/dl8Q5RoPKew.png" alt="Getting Plaintext Data Key" width="564" height="366" loading="lazy"></p>
<p>Then the Encrypted Data is decrypted using the Plain Data key, and the Plain Data Key is removed from memory.</p>
<h2 id="heading-how-is-envelope-encryption-different-from-other-encryption-patterns"><strong>How is Envelope Encryption Different From Other Encryption Patterns</strong>? 🤔</h2>
<p>Every service you build requires encryption at some point. This could be passwords or PII in a database, credentials for an external service, or even files in a filesystem.</p>
<h3 id="heading-configuration-files">Configuration Files</h3>
<p>You can easily handle some of these situations with a configuration file but they pose their own security risks like:</p>
<ul>
<li>Proper planning is needed to keep the data secure</li>
<li>Multiple formats are present, like YAML, JSON and XML to name a few</li>
<li>Exact storage locations may be hard-coded in the app, making deployment potentially problematic</li>
<li>Parsing of the config files can be problematic.</li>
</ul>
<h3 id="heading-symmetric-encryption">Symmetric Encryption</h3>
<p>You can encrypt data using a symmetric key but they suffer from a major issue which is Key Management.</p>
<p>You need to find a way to get the key to the party with whom you are sharing data. But if someone gets their hands on a symmetric key, they can decrypt everything encrypted with that key.</p>
<h3 id="heading-asymmetric-encryption">Asymmetric Encryption</h3>
<p>You can encrypt data using Asymmetric Encryption which is considered a standard now a days. However, some of its cons are:</p>
<ul>
<li>It is a slow process which makes its not suitable for decrypting bulk messages</li>
<li>When you lose your private key, your received messages will not be decrypted</li>
<li>If your private key is identified by an attacker, they can read all of your messages </li>
</ul>
<h3 id="heading-envelope-encryption">Envelope Encryption</h3>
<p>Some of the benefits offered by envelope encryption are:</p>
<ul>
<li><strong>A combination of benefits from symmetric and asymmetric encryption</strong> – The data is encrypted using a DEK which follows symmetric encryption. The DEK is encrypted by a CMK which follows asymmetric encryption. By using asymmetric encryption, encrypted DEKs can be shared and unencrypted only by those with access to the CMK, mitigating the key exchange problem of symmetric algorithms.</li>
<li><strong>Easier key management</strong> – Multiple DEKs can be encrypted under a singular root key and ease the management of keys in a KMS. You can also do more secure key maintenance by rotating your root keys, instead of rotating and re-encrypting all of your DEKs.</li>
<li><strong>Data key protection</strong> – Because we encrypt the data key with the CMK, we don't have to worry about storing the encrypted data key. Thus, we can safely store the encrypted data key alongside the encrypted data.</li>
</ul>
<h2 id="heading-why-key-management-systems-work-well-at-scale">Why Key Management Systems Work Well at Scale</h2>
<p>Envelope Encryption and KMSs working so well at scale because of <strong>Performance.</strong> Like we mentioned before, Asymmetric Encryptions are typically slow and Symmetric Encryptions are very fast but managing keys can be an issue. </p>
<p>So in Envelope Encryption, for a large quantity of data, you quickly encrypt it using symmetric encryption with a random key. Then just the key is encrypted using asymmetric encryption. This gives the benefits of asymmetric encryption, with the performance of symmetric encryption.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1635198563732/1E9VcEqZ-.png" alt="KMS Used at Scale in Google" width="2158" height="742" loading="lazy"></p>
<p>Key Management Systems like AWS KMS, Azure Key Vault, and Google Cloud Key Management Service gives you a fully managed service to store and manage encryption keys. These use envelope encryption internally, and they’re used by default in a lot of services that support encryption in cloud infrastructure providers like AWS, GCP, Azure, and others.</p>
<p>An ideal key management system should be highly available, it should control access to the master key(s), it should audit the key(s) usage, and finally, it should manage key(s) lifecycle.</p>
<p>Thus by having the above characteristics and by using envelope encryption internally, Key Management Systems are ideal to handle encryption at scale.</p>
<h2 id="heading-summary">Summary</h2>
<p>Envelope Encryption is one of the most trusted application security design patterns used at scale. It is the default encryption method used in services like AWS S3, GCP, and others. </p>
<p>Hopefully, this helps you understand how you can encrypt/decrypt a large amount of data using the envelope encryption method at scale in a more trusted setup.</p>
<p>Thanks for reading! I really hope that you find this article useful. I'm always interested to know your thoughts and am happy to answer any questions you might have. If you think this post was useful, please share it so others can read it, too.</p>
<p>P.S. – Do feel free to connect with me on <a target="_blank" href="https://www.linkedin.com/in/rohitjmathew">LinkedIn</a> or <a target="_blank" href="https://twitter.com/iamrohitjmathew">Twitter</a>.</p>
<h2 id="heading-resources">Resources</h2>
<p>This article leans heavily on the following material:</p>
<ul>
<li><a target="_blank" href="https://jayendrapatil.com/tag/envelope-encryption/">Google Cloud Data Encryption - Jayendra's Cloud Certification Blog -</a></li>
<li><a target="_blank" href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html">AWS KMS concepts - AWS</a></li>
<li><a target="_blank" href="https://lobster1234.github.io/2017/09/29/aws-kms-envelope-encryption/">AWS KMS and Envelope Encryption - Manish Pandit</a></li>
<li><a target="_blank" href="https://blog.nilayparikh.com/security/application/cloud-architecture-patterns-envelope-encryption-or-digital-envelope-with-public-cloud-providers-part-1/">Cloud Architecture Pattern: Envelope Encryption (or Digital Envelope) with Public Cloud Providers Part 1 - Nilay Parikh</a></li>
<li><a target="_blank" href="https://dev.to/chiragdm/aws-kms-envelope-encryption-3689">AWS KMS Envelope Encryption - Chirag Modi</a></li>
<li><a target="_blank" href="https://cloud.ibm.com/docs/key-protect?topic=key-protect-envelope-encryption">Protecting data with envelope encryption - IBM</a></li>
<li><a target="_blank" href="https://cloud.google.com/kms/docs/envelope-encryption">Envelope encryption - GCP</a></li>
<li><a target="_blank" href="https://cloud.google.com/security/encryption/default-encryption">Encryption at rest in Google Cloud - GCP</a></li>
</ul>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/StJ1NOQjAjo" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ End-to-End Encryption – Is Your Data Safe from Big Tech? ]]>
                </title>
                <description>
                    <![CDATA[ By Yehuda Clinton Every now and then we hear buzzing in the news about some egregious Big Tech privacy infringement. We are also frequently notified about all the new steps our apps are taking to further protect our privacy.  Most of us then weigh th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/end-to-end-encryption-is-your-data-safe/</link>
                <guid isPermaLink="false">66d461703dce891ac3a96836</guid>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ privacy ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 14 Jan 2021 00:28:41 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/cyber-security-3400657__340.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yehuda Clinton</p>
<p>Every now and then we hear buzzing in the news about some egregious Big Tech privacy infringement. We are also frequently notified about all the new steps our apps are taking to further protect our privacy. </p>
<p>Most of us then weigh the concerns and concede to the status quo without actually understanding the problem. As long as no one but us can see this message:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/e2ee.jpeg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Recently, WhatsApp announced that users must consent to sharing your data, including phone numbers and locations with Facebook. </p>
<p>Let's start with the basic question:</p>
<h2 id="heading-what-information-can-apps-websites-and-operating-systems-have-access-to">What information can apps, websites and operating systems have access to?</h2>
<p>Let's try delving into WhatsApp as they have recently been under attack.</p>
<p>Every WhatsApp user encounters a statement like "this personal message has end-to-end encryption." Which means that WhatsApp or anyone else shouldn't be able to decipher this message once it leaves your phone. </p>
<p>We should be able to trust that Facebook cannot read our WhatsApp messages on its server even if they store them until the recipient is connected. You can read WhatsApp's <a target="_blank" href="https://www.whatsapp.com/legal/privacy-policy">privacy policy here</a>.</p>
<p><strong>So far, no con game.</strong></p>
<p>What they don't mention in their privacy policy, however, is the in-app permissions about media and sensors. I'm referring to permission dialogs which pop up on first use.</p>
<p>I'm also referring to the data your OS shares with Facebook outside the app's ecosystem.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://android.stackexchange.com/questions/71802/help-understanding-whatsapps-permissions">https://android.stackexchange.com/questions/71802/help-understanding-whatsapps-permissions</a></div>
<p>While installing a new phone you could read this list of permissions accessed by the app including: Storage, location, Camera, Microphone, Accounts, Profile, Contacts and view apps running. </p>
<p>The above <em>StackExchange</em> article is over five years old and the list has changed since then. However you see a pattern of frequent changes to permissions and how difficult it can be to pin down when and how the app accesses media or device sensors.</p>
<h3 id="heading-how-does-big-tech-use-your-data">How does BIG-Tech use your data?</h3>
<p>Let's go through some of the permissions listed for WhatsApp:</p>
<ul>
<li><strong>your social media profile</strong> - details like 'phone number' and 'about'</li>
<li><strong>location and time</strong> - when you were at a given place</li>
<li><strong>Photos/Media/Files</strong> - hopefully they only use it for what they say</li>
<li><strong>contacts</strong> - they might share this within their ad algorithms </li>
<li><strong>camera</strong> - hopefully it's only in use when in an encrypted video call</li>
<li><strong>microphone</strong> - hopefully... but see <a target="_blank" href="https://www.quora.com/Can-Whatsapp-use-microphone-access-to-listen-to-converstations-even-when-not-being-used-for-audio-video-call-And-can-Facebook-use-that-data-to-shows-ads?share=1">this</a> and <a target="_blank" href="https://www.quora.com/Is-Facebook-listening-to-me-through-my-phones-microphone">this</a>. Sounds unclear</li>
<li><strong>gyroscope/accelerometer</strong> - determines when you're walking, sitting or driving</li>
<li><strong>light sensor</strong> - helps determine if your phone is in your pocket or against your head and so on</li>
</ul>
<h3 id="heading-so-do-they-directly-or-indirectly-use-these-sensors-when-you-dont-expect">So do they directly or indirectly use these sensors when you don't expect?</h3>
<p>Facebook may not have to admit the answer to this, as google-play-services collects much of this information and shares it with them in different ways. Our best answer is that we can't really prove it one way or the other. </p>
<p>It is all fine for most people if Big-Tech just uses our data to market relevant ads to us, but how can we know? Also if they aren't doing so today there's nothing stopping them from doing so one day.</p>
<h3 id="heading-how-they-get-away-with-it">How they get away with it</h3>
<p>We can see from other cases that large tech companies usually have each others' backs on these issues. Big-Tech has an established data-centric way of powering the online world. They don't seem to like competition. </p>
<p>Note how the Parler app was booted from AWS and at the same time as being banned from the different app stores. There is plenty of other incitement happening on AWS hosted apps or Google. Even if there was ongoing pressure to dump Parler, being a growing social media app likely sealed their fate. </p>
<h2 id="heading-so-what-are-the-alternatives">So what are the alternatives?</h2>
<h3 id="heading-telegramhttpstelegramorg-amp-signal"><a target="_blank" href="https://telegram.org">Telegram</a> &amp; Signal</h3>
<p><strong>Telegram</strong> is a privacy focused instant messaging platform with some 500 million users. Although the app feels like top social networking its CEO <a target="_blank" href="https://techcrunch.com/2020/12/23/telegram-to-launch-an-ad-platform-as-it-approaches-500-million-users/">does not intend to monetize by utilizing user data</a>. </p>
<p>Its mobile apps are open source so we can know exactly how it uses your phone data. This also allows us to assess the strength of the end-to-end encryption.</p>
<p><strong>Signal</strong> is a completely open source messaging and calling service. Its non profit nature assures you that there's no ads or fees, but it's a bit more complicated to use and a lower quality service.</p>
<h3 id="heading-how-to-keep-your-telegram-private-and-secure">How to keep your telegram private and secure</h3>
<p>Use the settings to control who can see your photo, groups/channels or phone number. You can make your account name an alias and have your real name within your profile which can only be seen by your friends.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/telegram.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-you-are-trading-for-privacy">What you are trading for Privacy?</h2>
<p>When using WhatsApp and similar social media, you're forced to adhere to the political and moral standards of Silicon Valley. As much as you may hate it, they do fairly well at protecting you from scams, harassment, and other criminal activities. </p>
<p>If you decide to use an alternative, like Telegram, you should be ready to be your own filter. The Telegram or Signal apps may not be safe for children without careful supervision. There are <a target="_blank" href="https://www.mspy.com/telegram.html">versions of the app available</a> which allow parents to monitor their children's messages and contacts. </p>
<p>If you wish to learn more about underlying technologies we encounter daily, read <a target="_blank" href="https://bootstrap-it.com/davidclinton/keeping-up/">this book by David Clinton</a>.</p>
<p>If you are looking for encryption with your devices consider taking my <a target="_blank" href="https://www.manning.com/liveproject/secure-business-infrastructure-with-a-custom-vpn?a_aid=bootstrap-it&amp;a_bid=b9d7d398&amp;chan=VPN">VPN course from Manning Publications</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Encryption Algorithms Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Megan Kaczanowski Cryptography, at its most basic, is the science of using codes and ciphers to protect messages.  Encryption is encoding messages with the intent of only allowing the intended recipient to understand the meaning of the message. It... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understanding-encryption-algorithms/</link>
                <guid isPermaLink="false">66d46074b3016bf139028d7b</guid>
                
                    <category>
                        <![CDATA[ cybersecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ethical Hacking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hacking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 01 May 2020 00:16:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9b58740569d1a4ca2b3f.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Megan Kaczanowski</p>
<p>Cryptography, at its most basic, is the science of using codes and ciphers to protect messages. </p>
<p>Encryption is encoding messages with the intent of only allowing the intended recipient to understand the meaning of the message. It is a two way function (you need to be able to undo whatever scrambling you’ve done to the message). This is designed to protect data in transit. </p>
<p>If you're looking for a general background on the difference between symmetric and asymmetric algorithms and a general overview of what encryption is, start <a target="_blank" href="https://medium.com/swlh/how-to-send-secret-messages-1c106250b884">here</a>. This article will primarily cover two of the most commonly used encryption algorithms. </p>
<p>As a general overview, there was a major problem with symmetric algorithms when they were first created - they only functioned effectively if both parties already knew the shared secret. If they didn't, securely exchanging a key without a third party eves-dropping was extremely difficult. </p>
<p>And if a third party obtained the key, it was very easy for them to then break the encryption, defeating the purpose of secure communication. </p>
<p>Diffie-Hellman solved this problem by allowing strangers to exchange information over public channels which can be used to form a shared key. A shared key is difficult to crack, even if all communications are monitored.</p>
<h2 id="heading-how-does-diffie-hellman-work">How does Diffie-Hellman work?</h2>
<p>Diffie-Hellman is what's called a key exchange protocol. This is the primary use for Diffie-Hellman, though it could be used for encryption as well (it typically isn't, because it's more efficient to use D-H to exchange keys, then switch to a (significantly faster) symmetric encryption for data transmission). </p>
<p>The way this works is as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screen-Shot-2019-10-04-at-5.45.13-PM.png" alt="Image" width="600" height="400" loading="lazy">
_<a target="_blank" href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange#/media/File:Diffie-Hellman_Key_Exchange.svg">https://en.wikipedia.org/wiki/Diffie–Hellman_key_exchange#/media/File:Diffie-Hellman_Key_Exchange.svg</a>_</p>
<p>Basically, there are two parties, Alice and Bob, which agree on a starting color (arbitrary but has to be different every time). They also have a secret color they keep to themselves. They then mix this color with the shared color, resulting in two different colors. They then pass this color to the other party, who mixes it with their secret color, resulting in the same ending secret color. </p>
<p>This relies upon the idea that it's relatively easy to mix two colors together, but it is very difficult to separate them in order to find the secret color. In practice, this is done with mathematics.</p>
<p>For example:</p>
<ol>
<li>Bob and Alice agree on two numbers, a large prime, p = 29, and base g = 5</li>
<li>Now Bob picks a secret number, x (x = 4) and does the following: X = g^x % p (in this case % indicates the remainder. For example 3%2 is 3/2, where the remainder is 1). X = 5 ^4 % 29 = 625 % 29 = 16</li>
<li>Alice also picks a secret number, y (y = 8) and does the following: Y = g^y % p.  Y = 5 ^ 8 % 29 = 390,625 % 29 = 24</li>
<li>Bob sends X to Alice and Alice sends Y to Bob.</li>
<li>Then Bob does the following: K = Y^x % p, K = 24 ^ 4 % 29 = 331,776 % 29 = 16</li>
<li>Alice then does the following: K = X^y % p, K = 16 ^ 8 % 29 = 4,294,967,296 % 29 = 16</li>
</ol>
<p>The great (<em>possibly magic</em>) thing about this, is that both Bob and Alice have the same number, K, and can now use this to talk secretly, because no one else knows K.</p>
<p>The security of this protocol is predicated on a few things:</p>
<ol>
<li>(Fact) It's relatively easy to generate prime numbers, even large prime numbers (like p).</li>
<li>(Fact) Modular exponentiation is easy. In other words, it's relatively easy to compute X = g ^ x % p.</li>
<li>(Assumption based on current computing power and mathematics) Modular root extraction without the prime factors is very hard. Essentially, it's very hard to find K without knowing x and y, even if you've snooped on the traffic and can see p, g, X, and Y.</li>
</ol>
<p>Thus, assuming this was implemented correctly, it's relatively easy to do the math required to create the key, but is extremely difficult and time consuming to do the math required to try to break the key by brute forcing it. </p>
<p>Even if an attacker could compromise this key, Diffie-Hellman allows for perfect forward secrecy.</p>
<h3 id="heading-what-is-perfect-forward-secrecy">What is perfect forward secrecy?</h3>
<p>This is the idea that if you crack the encryption that the server is using to communicate now, it doesn’t mean that all communications that the server has ever carried out are able to be read. </p>
<p>In other words, it only allows you to see the communications that are being used now (ie with this secret key). Since each set of communications has a different secret key, you would have to crack them all separately. </p>
<p>This is possible if each session has a different, ephemeral key for each session. Because Diffie-Hellman always uses new random values for each session, (therefore generating new keys for each session) it is called Ephemeral Diffie Hellman (EDH or DHE). Many cipher suites use this to achieve perfect forward secrecy.</p>
<p>As Diffie-Hellman allows you to exchange key material in plaintext without worrying about compromising the shared secret, and the math is too complicated for an attacker to brute force, the attacker can't derive the session key (and even if they could, using different, ephemeral, keys for each session means that they could only snoop on this session - not any in the past or future). </p>
<p>Forward secrecy is enabled with any Diffie-Hellman key exchange, but only ephemeral key exchange (a different key for every session) provides perfect forward secrecy. </p>
<p><a target="_blank" href="https://scotthelme.co.uk/perfect-forward-secrecy/">Here's a post</a> from Scott Helme talking about this in more depth and explaining how to enable this on your servers.</p>
<h3 id="heading-what-are-diffie-hellmans-limitations">What are Diffie-Hellman's limitations?</h3>
<p>The biggest limitation of D-H is that is doesn't verify identity. In other words, anyone can claim to be Alice or Bob and there is no built-in mechanism for verifying that their statement is true. </p>
<p>In addition, if the implementation is not carried out in a secure manner, the algorithm could be cracked with enough dedicated resources (unlikely, but possible for academic teams or nation-state actors). </p>
<p>For example, this could occur if the random number generator is not provided with adequate entropy to support the desired strength - in other words, because computer generated numbers are never truly random, the degree to which you've artificially injected uncertainness matters to the strength of your implementation.</p>
<p>Additionally, there was an attack demonstrated in 2015 which showed that when the same prime numbers were used by many servers as the beginning of the key exchange, the overall security of Diffie-Hellman was lower than expected. </p>
<p>Essentially an attacker could simply precompute the attack against that prime, making it easier to compromise sessions for any server which has used that prime number. </p>
<p>This occurred because millions of servers were using the same prime numbers for key exchanges. Precomputing this type of attack still requires either academic or nation-state level resources and is unlikely to impact the vast majority of people. </p>
<p>However, luckily for those who have to worry about nation-state attackers, there is a different way to achieve the DH key exchange using elliptic curve cryptography (ECDHE). This is out of the scope of this article, but if you're interested in learning more about the math behind this exchange, check out <a target="_blank" href="https://vincent.bernat.ch/en/blog/2011-ssl-perfect-forward-secrecy">this article</a>.</p>
<p>For a more detailed look at the weaknesses of DH, check out <a target="_blank" href="https://cert.europa.eu/static/WhitePapers/CERT-EU-SWP_16-002_Weaknesses%20in%20Diffie-Hellman%20Key%20v1_0.pdf">this whitepaper</a> and <a target="_blank" href="https://weakdh.org/">this website.</a></p>
<h2 id="heading-rsa">RSA</h2>
<p>RSA is named for the creators  –  Rivest, Shamir, Adleman – and it is a manner of generating public and private keys. </p>
<p>Technically there are two RSA algorithms (one used for digital signatures, and one used for asymmetric encryption.) - this article covers the asymmetric encryption algorithm. </p>
<p>This allows for key exchange - you first assign each party to the transaction public/private keys, then you generate a symmetric key, and finally, you use the public/private key pairs to securely communicate the shared symmetric key. </p>
<p>Because asymmetric encryption is generally slower than symmetric encryption, and doesn't scale as well, using asymmetric encryption to securely exchange symmetric keys is very common.</p>
<p>So, how does it work?</p>
<ol>
<li>Pick 2 very large prime numbers (at least 512 bits, or 155 decimal digits each), x and y (these numbers need to be secret and randomly chosen)</li>
<li>Find the product, ie z = x*y</li>
<li>Select an odd public integer, e, between 3 and n - 1, and has no common factors (other than 1) with (x-1)(y-1) (so it is relatively prime to x - 1 and y - 1).</li>
<li>Find the least common multiple of x - 1 and y - 1, and call it L.</li>
<li>Calculate the private exponent, d, from x, y, and e. de = 1 % L. d is the inverse of e % L (you know that an inverse exists because e is relatively prime to z - 1 and y - 1). This system works because p = (p ^ e) ^d % z.</li>
<li>Output (z, e) as the public key and (z, d) as the private key.</li>
</ol>
<p>Now, if Bob would like to send a message to Alice, he generates the ciphertext(C) from the plain text(P) using this formula:</p>
<p>C = P^e % z</p>
<p>In order to decrypt this message, Alice computes the following:</p>
<p>P = C^d % z</p>
<p>The relationship between d and e ensures that encryption and decryption functions are inverses. That means that the decryption function is able to successfully recover the original message, and that it's quite hard to recover the original message without the private key (z, d) (or prime factors x and y). </p>
<p>This also means that you can make z and e public without compromising the security of the system, making it easy to communicate with others with whom you don't already have a shared secret key.</p>
<p>You can also use the operations in reverse to get a digital signature of the message. First, you use the decryption operation on the plaintext. For example, s = SIGNATURE(p) = p ^ d % z.</p>
<p>Then, the recipient can verify the digital signature by applying the encryption function and comparing the result with the message. For example, m = VERIFY(s) = S ^ e % z.</p>
<p>Often when this is done, the plaintext is a hash of the message, meaning you can sign the message (regardless of length) with only one exponentiation.</p>
<p>The security of system is based on a few things: </p>
<ol>
<li>(Fact) It's relatively easy to generate prime numbers, even large prime numbers (like x and y).</li>
<li>(Fact) Multiplication is easy. It's very easy to find z.</li>
<li>(Assumption based on current mathematics) Factoring is hard. Given z, it's relatively hard to recover x and y. It is do-able, but it takes a while, and it is expensive.   </li>
</ol>
<p><a target="_blank" href="http://mathaware.org/mam/06/Kaliski.pdf">One estimate</a> says that recovering the prime factors of a 1024-bit number would take a year on a machine which cost $10 million. Doubling the size would exponentially increase the amount of work needed (several billion times more work).   </p>
<p>As technology continues to advance, these costs (and the work required) will decrease, but at this point, this type of encryption, properly implemented, is an unlikely source of compromise.   </p>
<p>Generally the only hackers with this type of money and dedication to a single target are nation-states. Plus, if there's an easier way to compromise a system (see below), that's probably a better option.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screen-Shot-2019-10-05-at-11.18.45-AM.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://xkcd.com/538/">https://xkcd.com/538/</a></em></p>
<ol start="4">
<li><p>(Fact) Modular exponentiation is easy. In other words, it's relatively easy to compute c = p ^ e % z.</p>
</li>
<li><p>(Fact) Modular root extraction - reversing the process above - is easy if you have the prime factors (if you have z, c, e, and the prime factors x and y, it's easy to find p such that c = p ^ e % z).</p>
</li>
<li><p>(Assumption based on current computing power and mathematics) Modular root extraction without the prime factors is very hard (if you have z, c, e, but not x and y, it's relatively hard to find p such that c = p ^ e % z, particularly if a is sufficiently large).</p>
</li>
</ol>
<p>Want to learn more about the math from much smarter people? Check out <a target="_blank" href="http://mathaware.org/mam/06/Kaliski.pdf">this article.</a></p>
<h2 id="heading-great-which-is-better">Great, which is better?</h2>
<p>It depends on your use case. There are a few differences between the two algorithms - first, perfect forward secrecy (PFS), which we talked about earlier in context of Diffie-Hellman. While technically you <em>could</em> generate ephemeral RSA key pairs, and provide perfect forward secrecy with RSA, the computational cost is much higher than for Diffie-Hellman - meaning that Diffie-Hellman is a better choice for SSL/TLS implementations where you want perfect forward secrecy.  </p>
<p>While there are some performance differences between the two algorithms (in terms of work required from the server), the performance differences generally aren't large enough to make a difference when choosing one over the other. </p>
<p>Instead, in general, the primary consideration when determining which is better depends on which one is more supported for your use case (for example, when implementing SSL you'll want Diffie Hellman due to perfect forward secrecy) or which is more popular or accepted as the standard in the industry. </p>
<p>For example, while Diffie-Hellman was US government approved, and supported by an institutional body, the standard wasn't released - whereas RSA (standardized by a private organization) provided a free standard, meaning that RSA became very popular among private organizations. </p>
<p>If you're interested in reading more, there's a great thread <a target="_blank" href="https://security.stackexchange.com/questions/35471/is-there-any-particular-reason-to-use-diffie-hellman-over-rsa-for-key-exchange/35472#35472">here</a> on the differences.</p>
<p>Interested in learning how to hackers use cryptographic attacks? Try <a target="_blank" href="https://cryptopals.com/">this</a> set of challenges from Cryptopals.</p>
<div class="embed-wrapper">
        <blockquote class="twitter-tweet">
          <a href="https://twitter.com/preinheimer/status/841273046317060105?lang=en"></a>
        </blockquote>
        <script defer="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></div>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
