broadfield-dev commited on
Commit
9c5b643
·
verified ·
1 Parent(s): 705abae

Create decoder.js

Browse files
Files changed (1) hide show
  1. server/decoder.js +114 -0
server/decoder.js ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const sharp = require('sharp');
2
+ const { webcrypto } = require('crypto');
3
+
4
+ // --- Helper to convert PEM to a format Web Crypto API can use ---
5
+ function pemToDer(pem) {
6
+ const b64 = pem
7
+ .replace(/-----BEGIN PRIVATE KEY-----/g, '')
8
+ .replace(/-----END PRIVATE KEY-----/g, '')
9
+ .replace(/\\n/g, '') // Handle escaped newlines from env vars
10
+ .replace(/\s/g, '');
11
+ const binaryDer = atob(b64);
12
+ const buffer = new ArrayBuffer(binaryDer.length);
13
+ const bytes = new Uint8Array(buffer);
14
+ for (let i = 0; i < binaryDer.length; i++) {
15
+ bytes[i] = binaryDer.charCodeAt(i);
16
+ }
17
+ return buffer;
18
+ }
19
+
20
+ // --- Extracts hidden data from an image buffer using Sharp ---
21
+ async function extractDataFromImage(imageBuffer) {
22
+ const { data: pixelData, info } = await sharp(imageBuffer).raw().toBuffer({ resolveWithObject: true });
23
+
24
+ const HEADER_BITS = 32; // 4 bytes for the length header
25
+ const channels = info.channels; // Typically 3 (RGB) or 4 (RGBA)
26
+
27
+ if (pixelData.length < Math.ceil(HEADER_BITS / channels) * channels) {
28
+ throw new Error("Image is too small to contain a valid header.");
29
+ }
30
+
31
+ let headerBinaryString = '';
32
+ for (let i = 0; i < HEADER_BITS; i++) {
33
+ const pixelIndex = Math.floor(i / 3);
34
+ const channelIndex = i % 3;
35
+ headerBinaryString += pixelData[pixelIndex * channels + channelIndex] & 1;
36
+ }
37
+
38
+ const headerBytes = new Uint8Array(HEADER_BITS / 8);
39
+ for (let i = 0; i < HEADER_BITS / 8; i++) {
40
+ headerBytes[i] = parseInt(headerBinaryString.substring(i * 8, (i + 1) * 8), 2);
41
+ }
42
+
43
+ const dataView = new DataView(headerBytes.buffer);
44
+ const dataLengthInBytes = dataView.getUint32(0, false);
45
+
46
+ if (dataLengthInBytes === 0) return new Uint8Array(0);
47
+
48
+ const dataLengthInBits = dataLengthInBytes * 8;
49
+ const bitOffset = HEADER_BITS;
50
+ const totalBitsToRead = bitOffset + dataLengthInBits;
51
+
52
+ if (pixelData.length < Math.ceil(totalBitsToRead / 3) * channels) {
53
+ throw new Error("Image is too small for the data specified in the header. File may be corrupt.");
54
+ }
55
+
56
+ let dataBinaryString = '';
57
+ for (let i = 0; i < dataLengthInBits; i++) {
58
+ const bitPosition = bitOffset + i;
59
+ const pixelIndex = Math.floor(bitPosition / 3);
60
+ const channelIndex = bitPosition % 3;
61
+ dataBinaryString += pixelData[pixelIndex * channels + channelIndex] & 1;
62
+ }
63
+
64
+ const dataBytes = new Uint8Array(dataLengthInBytes);
65
+ for (let i = 0; i < dataLengthInBytes; i++) {
66
+ dataBytes[i] = parseInt(dataBinaryString.substring(i * 8, (i + 1) * 8), 2);
67
+ }
68
+
69
+ return dataBytes;
70
+ }
71
+
72
+ // --- Decrypts the payload using RSA and AES ---
73
+ async function decryptHybridPayload(cryptoPayload, privateKeyPem) {
74
+ const ENCRYPTED_AES_KEY_LEN_SIZE = 4;
75
+ const AES_GCM_NONCE_SIZE = 12;
76
+
77
+ const privateKey = await webcrypto.subtle.importKey(
78
+ 'pkcs8', pemToDer(privateKeyPem), { name: 'RSA-OAEP', hash: 'SHA-256' }, true, ['decrypt']
79
+ );
80
+
81
+ const encryptedAesKeyLen = new DataView(cryptoPayload.buffer, 0, ENCRYPTED_AES_KEY_LEN_SIZE).getUint32(0, false);
82
+ let offset = ENCRYPTED_AES_KEY_LEN_SIZE;
83
+ const encryptedAesKey = cryptoPayload.slice(offset, offset + encryptedAesKeyLen);
84
+ offset += encryptedAesKeyLen;
85
+ const nonce = cryptoPayload.slice(offset, offset + AES_GCM_NONCE_SIZE);
86
+ offset += AES_GCM_NONCE_SIZE;
87
+ const ciphertextWithTag = cryptoPayload.slice(offset);
88
+
89
+ const decryptedAesKeyBytes = await webcrypto.subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, encryptedAesKey);
90
+ const aesKey = await webcrypto.subtle.importKey('raw', decryptedAesKeyBytes, { name: 'AES-GCM', length: 256 }, true, ['decrypt']);
91
+ const decryptedDataBuffer = await webcrypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, aesKey, ciphertextWithTag);
92
+
93
+ const decryptedText = new TextDecoder().decode(decryptedDataBuffer);
94
+ return JSON.parse(decryptedText);
95
+ }
96
+
97
+ // --- Main export function ---
98
+ async function decodeAuthFromImage(imageBuffer, privateKeyPem) {
99
+ try {
100
+ const cryptoPayload = await extractDataFromImage(imageBuffer);
101
+ if (cryptoPayload.length === 0) {
102
+ throw new Error("No data found in image.");
103
+ }
104
+ return await decryptHybridPayload(cryptoPayload, privateKeyPem);
105
+ } catch (error) {
106
+ console.error("Decoding failed:", error);
107
+ if (error.message.includes('decryption failed')) {
108
+ throw new Error("Decryption failed. The data may be corrupt or was not encrypted with the correct public key.");
109
+ }
110
+ throw error;
111
+ }
112
+ }
113
+
114
+ module.exports = { decodeAuthFromImage };