-
-
Save marcelbuesing/c3051e417d0ad35da2da8c9d10c620ca to your computer and use it in GitHub Desktop.
WebCrypto
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>The HTML5 Herald</title> | |
<meta name="description" content="The HTML5 Herald"> | |
<meta name="author" content="SitePoint"> | |
<!--link rel="stylesheet" href="css/styles.css?v=1.0"--> | |
<input type="file" id="upload"> | |
<!--[if lt IE 9]> | |
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> | |
<![endif]--> | |
</head> | |
<body> | |
<script> | |
const crypto = window.crypto.subtle; | |
const readFile = (file) => { | |
const fileReader = new FileReader(); | |
fileReader.readAsArrayBuffer(file); | |
return new Promise((resolve, reject) => { | |
fileReader.addEventListener("load", ev => resolve(ev.target.result)); | |
window.setTimeout(() => reject("File load timeout"), 60 * 1000); | |
}); | |
}; | |
const algo = key => ({ | |
name: key.algorithm.name, | |
iv: window.crypto.getRandomValues(new Uint8Array(16)), | |
}); | |
const encryptFile = file => { | |
readFile(file) | |
.then(buffer => crypto.digest({ | |
name: "SHA-256" | |
}, buffer).then(hash => ({ | |
buffer: buffer, | |
hash: hash | |
}))) | |
.then(encObj => crypto.generateKey({ | |
name: "AES-CBC", | |
length: 128 | |
}, false, ["encrypt", "decrypt"]).then(key => Object.assign({}, encObj, { key: key }))) | |
.then(encObj => crypto.encrypt(algo(encObj.key), encObj.key, encObj.buffer)) | |
.then(encrypted => { | |
alert("done"); | |
}); | |
}; | |
const upload = document.getElementById("upload"); | |
upload.addEventListener("change", e => encryptFile(upload.files[0]), false); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment