我正试图找到一种方法来加密、解密表单数据,并使用Cordova构建windows应用程序将其存储在设备的本地文件中。
您可以直接在Cordova代码中调用WinRT API,也可以将代码包装到
custom plugin
. 任何你必须使用的方法
Windows.Security.Cryptography.DataProtection
做这项工作。
js代码示例:
if ((cordova.platformId == "windows")) {
var Cryptography = Windows.Security.Cryptography;
//Encrypt the msg string
function protectData(msg) {
var provider = new Cryptography.DataProtection.DataProtectionProvider("LOCAL=user");
var encoding = Cryptography.BinaryStringEncoding.utf8;
var buffMsg = Cryptography.CryptographicBuffer.convertStringToBinary(msg, encoding);
provider.protectAsync(buffMsg).done(function (buffData) {
//the encryption has succeeded
writeToFile(buffData);
});
}
//decrypt the buffProtected buffer
function unprotectData(buffProtected) {
var provider = new Cryptography.DataProtection.DataProtectionProvider("LOCAL=user");
var encoding = Cryptography.BinaryStringEncoding.utf8;
// Decrypt the protected message specified on input.
provider.unprotectAsync(buffProtected).then(function (data) {
var stringMsg = Cryptography.CryptographicBuffer.convertBinaryToString(Windows.Security.Cryptography.BinaryStringEncoding.utf8, data);
document.getElementById("divResult").innerText = stringMsg;
}, function (error) {
console.log(error);
});
}
function writeToFile(buffProtected) {
Windows.Storage.ApplicationData.current.localFolder.createFileAsync("test.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (storageFile) {
Windows.Storage.FileIO.writeBufferAsync(storageFile, buffProtected).done(function(){});
}, function (error) {
console.log(error);
})
}
function readFromFile() {
Windows.Storage.ApplicationData.current.localFolder.getFileAsync("test.txt").then(function (storageFile) {
var abc = storageFile;
Windows.Storage.FileIO.readBufferAsync(storageFile).then(function (buffData) {
//decrypt the data
unprotectData(buffData);
});
}, function (error) {
console.log(error);
});
}
document.getElementById("btnEncrypt").onclick = function () {
var data = document.getElementById("txtData").value;
protectData(data);
}
document.getElementById("btnDecrypt").onclick = function () {
readFromFile(unprotectData)
}
}
和Html:
<input type="text" id="txtData" placeholder="ToProtected Data" />
<button id="btnEncrypt">Encrypt Data</button>
<button id="btnDecrypt">Decrypt Data</button>
<div id="divResult"></div>