Metro应用存储数据方法

本文介绍了一种利用Cryptography库保护和加载应用数据的方法,通过数据保护提供者实现本地用户数据的安全存储。
save : function(key, value, callback) {
            var _usrBuffer;
            var _protectedUsr;

            var dataProtectionProvider = new Windows.Security.Cryptography.DataProtection.DataProtectionProvider('LOCAL=user');

            _usrBuffer = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(value, Windows.Security.Cryptography.BinaryStringEncoding.utf8);

            var _usrPromise = dataProtectionProvider.protectAsync(_usrBuffer);
            _usrPromise.done(function (buffer) {
                _protectedUsr = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
            }, function (e) {
                var _e = e;
            });
            WinJS.Promise.join([_usrPromise]).then(function () {
                var localSettings = Windows.Storage.ApplicationData.current.localSettings;
                localSettings.values[key] = _protectedUsr;
                if (callback) {
                    callback();
                }
            });
        },
        load: function(key,callback){
            var localSettings = Windows.Storage.ApplicationData.current.localSettings;

            var _protectedUsr = localSettings.values[key];
            console.log("_protectedUsr:" + _protectedUsr);
            if (!_protectedUsr) {
                return;
            }
            if (_protectedUsr.trim() == '') {
                return;
            }

            var _usrBuffer;
            var value;

            var dataProtectionProvider = new Windows.Security.Cryptography.DataProtection.DataProtectionProvider();
            _usrBuffer = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(_protectedUsr);
            var _usrPromise = dataProtectionProvider.unprotectAsync(_usrBuffer); 
            _usrPromise.done(function (buffer) {
                value = Windows.Security.Cryptography.CryptographicBuffer.convertBinaryToString(Windows.Security.Cryptography.BinaryStringEncoding.utf8, buffer); 
            }, function (e) {
                var _e = e;
            });

            var object; 
            WinJS.Promise.join([_usrPromise]).done(function () {
                if (callback) {
                    callback(value);
                }
            });
            return object;
        },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值