Skip to content

Instantly share code, notes, and snippets.

@akumbhani66
Created June 2, 2024 08:56
Show Gist options
  • Save akumbhani66/ada0f6c7a1497b3c39525f74ce05d472 to your computer and use it in GitHub Desktop.
Save akumbhani66/ada0f6c7a1497b3c39525f74ce05d472 to your computer and use it in GitHub Desktop.
Encrypt the file before uploading it to AWS S3 and decrypt it after downloading it from aws s3.
<!DOCTYPE html>
<html>
<head>
<title>File Encryption/Decryption</title>
</head>
<body>
<h1>File Encryption/Decryption</h1>
<h2>Encryption</h2>
<input type="file" id="fileInput" onchange="previewFile(event)" />
<img id="previewImg" style="max-width: 300px; display: none;" />
<input type="text" id="secretKey" placeholder="Enter secret key" />
<button onclick="encryptFile()">Encrypt File</button>
<a id="downloadEncryptedLink" style="display: none;">Download Encrypted File</a>
<h2>Decryption</h2>
<input type="file" id="encryptedFileInput" />
<input type="text" id="decryptionKey" placeholder="Enter secret key" />
<button onclick="decryptFile()">Decrypt File</button>
<a id="downloadDecryptedLink" style="display: none;">Download Decrypted File</a>
<script>
function previewFile(event) {
const file = event.target.files[0];
const previewImg = document.getElementById('previewImg');
if (file) {
const reader = new FileReader();
reader.onload = () => {
previewImg.src = reader.result;
previewImg.style.display = 'block';
};
reader.readAsDataURL(file);
} else {
previewImg.src = '';
previewImg.style.display = 'none';
}
}
function encryptFile() {
const file = document.getElementById('fileInput').files[0];
const secretKey = document.getElementById('secretKey').value;
if (!file || !secretKey) {
alert('Please select a file and enter a secret key.');
return;
}
const reader = new FileReader();
reader.onload = async () => {
const fileBytes = new Uint8Array(reader.result);
const iv = window.crypto.getRandomValues(new Uint8Array(16));
const encryptedBytes = await encryptData(fileBytes, secretKey, iv);
// Combine IV and encrypted bytes
const combinedBytes = new Uint8Array(iv.length + encryptedBytes.length);
combinedBytes.set(iv);
combinedBytes.set(encryptedBytes, iv.length);
const encryptedBlob = new Blob([combinedBytes], { type: file.type });
const encryptedUrl = URL.createObjectURL(encryptedBlob);
const downloadLink = document.getElementById('downloadEncryptedLink');
downloadLink.href = encryptedUrl;
downloadLink.download = `encrypted_${file.name}`;
downloadLink.style.display = 'inline';
};
reader.readAsArrayBuffer(file);
}
async function encryptData(data, secretKey, iv) {
const cryptoKey = await window.crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secretKey),
{ name: 'AES-CBC' },
false,
['encrypt']
);
const encryptedBytes = await window.crypto.subtle.encrypt(
{ name: 'AES-CBC', iv },
cryptoKey,
data
);
return new Uint8Array(encryptedBytes);
}
function decryptFile() {
const encryptedFile = document.getElementById('encryptedFileInput').files[0];
const secretKey = document.getElementById('decryptionKey').value;
if (!encryptedFile || !secretKey) {
alert('Please select an encrypted file and enter the secret key.');
return;
}
const reader = new FileReader();
reader.onload = async () => {
const combinedBytes = new Uint8Array(reader.result);
// Extract IV and encrypted bytes
const iv = combinedBytes.slice(0, 16);
const encryptedBytes = combinedBytes.slice(16);
const decryptedBytes = await decryptData(encryptedBytes, secretKey, iv);
const decryptedBlob = new Blob([decryptedBytes], { type: encryptedFile.type });
const decryptedUrl = URL.createObjectURL(decryptedBlob);
const downloadLink = document.getElementById('downloadDecryptedLink');
downloadLink.href = decryptedUrl;
downloadLink.download = `decrypted_${encryptedFile.name}`;
downloadLink.style.display = 'inline';
const img = document.createElement('img');
img.src = decryptedUrl;
document.body.appendChild(img);
};
reader.readAsArrayBuffer(encryptedFile);
}
async function decryptData(encryptedData, secretKey, iv) {
const cryptoKey = await window.crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secretKey),
{ name: 'AES-CBC' },
false,
['decrypt']
);
const decryptedBytes = await window.crypto.subtle.decrypt(
{ name: 'AES-CBC', iv },
cryptoKey,
encryptedData
);
return new Uint8Array(decryptedBytes);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment