Skip to content

Instantly share code, notes, and snippets.

@jeffotoni
Last active July 14, 2018 12:24
Show Gist options
  • Save jeffotoni/be6a7441bd764cfdcb87766f55950a64 to your computer and use it in GitHub Desktop.
Save jeffotoni/be6a7441bd764cfdcb87766f55950a64 to your computer and use it in GitHub Desktop.
<input type='file' accept='*' onchange='openFile(event)'><br>
<textarea id='output' rows=9 cols=35></textarea>
<script>
var openFile = function(event) {
var output = document.getElementById('output');
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataText = reader.result;
output.value = dataText
encryptText(dataText, "senha1224").
then(buffCry => {
console.log(buffCry);
output.value += "\n\ncrypt:\n" + ab2str(buffCry);
} , err => {
output.value += "\n\ncrypt:\n" + err
});
};
// reader.readAsArrayBuffer(input.files[0]);
reader.readAsBinaryString(input.files[0]);
};
const encryptText = async (plainText, password) => {
const ptUtf8 = new TextEncoder().encode(plainText);
const pwUtf8 = new TextEncoder().encode(password);
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);
const iv = crypto.getRandomValues(new Uint8Array(12));
const alg = { name: 'AES-GCM', iv: iv };
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']);
return crypto.subtle.encrypt(alg, key, ptUtf8);
}
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment