Step 3: Encrypt on Save چالش 3 از جلسهی 56، متوسط
حالا save را امن کن. getKey، toHex، fromHex، encryptBytes و decryptBytes آمادهاند. در save: نمک تصادفی ۱۶ بایتی و IV تصادفی ۱۲ بایتی بساز (crypto.getRandomValues)، کلید را از #pw و نمک بساز، یادداشت را با encryptBytes(key, iv, enc.encode(note)) رمز کن و salt:iv:data (hex) را با store.set("note", ...) ذخیره کن؛ #status → saved. load را هم بنویس: رکورد را با split(":") بشکن، کلید را با همان نمک بساز، با decryptBytes بگشا و در #note بگذار؛ #status → loaded. (رمز غلط را قدم بعد مدیریت میکند.)
<script>
// tiny crypto for the preview sandbox: the real browser API is crypto.subtle (see the cards);
// the preview cannot use it, so these small functions play its part. Same algorithms, same answers.
const enc = new TextEncoder();
function toHex(bytes) { return Array.from(bytes).map(b => b.toString(16).padStart(2, "0")).join(""); }
function fromHex(hex) { return new Uint8Array((hex.match(/../g) || []).map(h => parseInt(h, 16))); }
function sha256Bytes(msg) {
const K = [0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2];
let H = [0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];
const l = msg.length, padLen = ((l + 9 + 63) >> 6) << 6, p = new Uint8Array(padLen);
p.set(msg); p[l] = 0x80; const bits = l * 8;
p[padLen - 4] = (bits >>> 24) & 255; p[padLen - 3] = (bits >>> 16) & 255; p[padLen - 2] = (bits >>> 8) & 255; p[padLen - 1] = bits & 255;
const rotr = (x, n) => (x >>> n) | (x << (32 - n)), w = new Array(64);
for (let i = 0; i < padLen; i += 64) {
for (let t = 0; t < 16; t++) w[t] = (p[i + t * 4] << 24) | (p[i + t * 4 + 1] << 16) | (p[i + t * 4 + 2] << 8) | p[i + t * 4 + 3];
for (let t = 16; t < 64; t++) { const s0 = rotr(w[t-15],7) ^ rotr(w[t-15],18) ^ (w[t-15] >>> 3), s1 = rotr(w[t-2],17) ^ rotr(w[t-2],19) ^ (w[t-2] >>> 10); w[t] = (w[t-16] + s0 + w[t-7] + s1) | 0; }
let [a,b,c,d,e,f,g,h] = H;
for (let t = 0; t < 64; t++) {
const S1 = rotr(e,6) ^ rotr(e,11) ^ rotr(e,25), ch = (e & f) ^ (~e & g), t1 = (h + S1 + ch + K[t] + w[t]) | 0;
const S0 = rotr(a,2) ^ rotr(a,13) ^ rotr(a,22), maj = (a & b) ^ (a & c) ^ (b & c), t2 = (S0 + maj) | 0;
h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;
}
H = [H[0]+a|0, H[1]+b|0, H[2]+c|0, H[3]+d|0, H[4]+e|0, H[5]+f|0, H[6]+g|0, H[7]+h|0];
}
const out = new Uint8Array(32);
H.forEach((v, i) => { out[i*4] = (v >>> 24) & 255; out[i*4+1] = (v >>> 16) & 255; out[i*4+2] = (v >>> 8) & 255; out[i*4+3] = v & 255; });
return out;
}
function concat(...arrays) { const n = arrays.reduce((s, a) => s + a.length, 0), out = new Uint8Array(n); let o = 0; for (const a of arrays) { out.set(a, o); o += a.length; } return out; }
function hmac(key, msg) {
if (key.length > 64) key = sha256Bytes(key);
const k = new Uint8Array(64); k.set(key);
const ipad = k.map(b => b ^ 0x36), opad = k.map(b => b ^ 0x5c);
return sha256Bytes(concat(opad, sha256Bytes(concat(ipad, msg))));
}
function pbkdf2(password, salt, iterations) {
const p = enc.encode(password);
let u = hmac(p, concat(salt, new Uint8Array([0, 0, 0, 1]))), t = u.slice();
for (let i = 1; i < iterations; i++) { u = hmac(p, u); for (let j = 0; j < 32; j++) t[j] ^= u[j]; }
return t;
}
// authenticated encryption, GCM style: keystream from the key and a fresh IV, plus a tag that catches any change or a wrong key
function encryptBytes(key, iv, plain) {
const out = new Uint8Array(plain.length);
for (let i = 0; i < plain.length; i++) { if (i % 32 === 0) var ks = sha256Bytes(concat(key, iv, new Uint8Array([i / 32]))); out[i] = plain[i] ^ ks[i % 32]; }
return concat(hmac(key, concat(iv, out)).slice(0, 16), out);
}
function decryptBytes(key, iv, data) {
const tag = data.slice(0, 16), body = data.slice(16), want = hmac(key, concat(iv, body)).slice(0, 16);
if (toHex(tag) !== toHex(want)) throw new Error("bad tag: wrong key or corrupted data");
const out = new Uint8Array(body.length);
for (let i = 0; i < body.length; i++) { if (i % 32 === 0) var ks = sha256Bytes(concat(key, iv, new Uint8Array([i / 32]))); out[i] = body[i] ^ ks[i % 32]; }
return out;
}
</script>
<input id="pw" placeholder="password">
<textarea id="note" placeholder="my note"></textarea><br>
<button id="save" onclick="save()">Save</button>
<button id="load" onclick="load()">Load</button>
<p id="status">-</p>
<p>on the desk: <code id="stored">(empty)</code></p>
<script>
const store = {
data: {},
set(k, v) { this.data[k] = v; document.getElementById("stored").textContent = v; },
get(k) { return this.data[k]; },
};
function getKey(password, salt) {
return pbkdf2(password, salt, 1000);
}
function save() {
const pw = document.getElementById("pw").value;
const note = document.getElementById("note").value;
store.set("note", note); // BUG: raw on the desk
document.getElementById("status").textContent = "saved";
}
function load() {
document.getElementById("note").value = store.get("note"); // BUG
document.getElementById("status").textContent = "loaded";
}
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 56: پروژه: یادداشت رمزشدهی مرورگری · چالش بعدی: Step 4: Wrong Password and Lock
بیشتر بخوان: دیکشنری در پایتون: آموزش کامل کلید و مقدار با مثال