Created
September 29, 2015 09:57
-
-
Save cjgaliana/a9fb0d4d9af3cb5e7029 to your computer and use it in GitHub Desktop.
Secure Storage for Xamarin.iOS
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
| using System; | |
| using System.Threading.Tasks; | |
| using Security; | |
| using Foundation; | |
| using System.Collections.Generic; | |
| namespace SecureStorageTest | |
| { | |
| public class SecureStorage | |
| { | |
| private string serviceName = "secureSTorageTest"; | |
| public Task StoreValueAsync(string key, string value) | |
| { | |
| var queryRecord = new SecRecord (SecKind.GenericPassword) | |
| { | |
| Service = this.serviceName, | |
| Label = key, | |
| Account = key | |
| }; | |
| SecStatusCode resultCode; | |
| var data = SecKeyChain.QueryAsRecord (queryRecord, out resultCode); | |
| if (resultCode == SecStatusCode.Success) { | |
| var deleteResultCode = SecKeyChain.Remove (queryRecord); | |
| if (deleteResultCode != SecStatusCode.Success) { | |
| throw new Exception ("The key already exists in the secure storage and is not possible update it"); | |
| } | |
| } | |
| SecKeyChain.Add (new SecRecord(SecKind.GenericPassword) | |
| { | |
| Service = this.serviceName, | |
| Account = key, | |
| Label = key, | |
| ValueData = NSData.FromString(value, NSStringEncoding.UTF8) | |
| }); | |
| return Task.FromResult (0); | |
| } | |
| public Task<string> GetValueAsync(string key) | |
| { | |
| var queryRecord = new SecRecord (SecKind.GenericPassword) { | |
| Account = key, | |
| Label = key, | |
| Service = this.serviceName | |
| }; | |
| SecStatusCode resultCode; | |
| var existingRecord = SecKeyChain.QueryAsRecord (queryRecord, out resultCode); | |
| if (resultCode != SecStatusCode.Success) { | |
| throw new KeyNotFoundException (string.Format("The Secure storage does not contain the key '{0}'", key)); | |
| } | |
| string result = NSString.FromData (existingRecord.ValueData, NSStringEncoding.UTF8); | |
| return Task.FromResult (result); | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment