/// <summary> /// This method trigger the authentication when user is setup on device. /// </summary> /// <returns>The credentials.</returns> /// <param name="callback">Callback.</param> public AuthenticationStatusEnum VerifyCredentials(Action <AuthenticationStatusEnum> callback) { Debug.WriteLine("Verify credentials called"); var record = new SecRecord(SecKind.GenericPassword) { Service = AppConstants.FullAppName, UseOperationPrompt = "Triggering Authentication by OS" }; SecStatusCode result; SecKeyChain.QueryAsRecord(record, out result); Debug.WriteLine("result " + result.ToString()); if (SecStatusCode.Success == result) { return(AuthenticationStatusEnum.Success); } else if (SecStatusCode.ItemNotFound == result) { //authenticated but no record found return(AuthenticationStatusEnum.NotFound); } else { //not able authenticate - user cancelled return(AuthenticationStatusEnum.Error); } }
void Protocol(SecProtocol protocol) { var rec = new SecRecord(SecKind.InternetPassword) { Account = "Protocol" }; SecKeyChain.Remove(rec); // it might already exists (or not) rec = new SecRecord(SecKind.InternetPassword) { Account = "Protocol", ValueData = NSData.FromString("Password"), Protocol = protocol, Server = "www.xamarin.com" }; Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add"); SecStatusCode code; var match = SecKeyChain.QueryAsRecord(rec, out code); Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord"); Assert.That(match.Protocol, Is.EqualTo(protocol), "Protocol"); }
public static bool SaveUserPassword(string username, string password) { var success = false; var searchRecord = new SecRecord(SecKind.InternetPassword) { Server = "Test1", Account = username.ToLower() }; SecStatusCode queryCode; var record = SecKeyChain.QueryAsRecord(searchRecord, out queryCode); if (queryCode == SecStatusCode.ItemNotFound) { record = new SecRecord(SecKind.InternetPassword) { Server = "Test1", Account = username.ToLower(), ValueData = NSData.FromString(password) }; var addCode = SecKeyChain.Add(record); success = (addCode == SecStatusCode.Success); } if (queryCode == SecStatusCode.Success && record != null) { record.ValueData = NSData.FromString(password); var updateCode = SecKeyChain.Update(searchRecord, record); success = (updateCode == SecStatusCode.Success); } return(success); }
public string GetIdentifier() { string serial = string.Empty; var rec = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString("uidNumber") }; SecStatusCode res; var match = SecKeyChain.QueryAsRecord(rec, out res); if (res == SecStatusCode.Success) { serial = match.ValueData.ToString(); } else { var uidNumberRecord = new SecRecord(SecKind.GenericPassword) { Label = "uid", ValueData = NSData.FromString(Guid.NewGuid().ToString()), Generic = NSData.FromString("uidNumber") }; var err = SecKeyChain.Add(uidNumberRecord); serial = uidNumberRecord.ValueData.ToString(); } return(serial); }
string AttemptGetDeviceId() { var record = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString(uniqueRecordName) }; SecStatusCode securityStatusCode; var recordMatch = SecKeyChain.QueryAsRecord(record, out securityStatusCode); if (securityStatusCode == SecStatusCode.Success) { return(recordMatch.ValueData.ToString()); } else { var newRecord = new SecRecord(SecKind.GenericPassword) { ValueData = NSData.FromString(Guid.NewGuid().ToString()), Generic = NSData.FromString(uniqueRecordName) }; SecKeyChain.Add(newRecord); return(newRecord.ValueData.ToString()); } }
public override void GetStoredKeyValuePairs(string[] keynames) { UIApplication.SharedApplication.InvokeOnMainThread(delegate { string sAccessGroup = KeyChainAccessGroup; List <KeyPair> foundKeyPairs = new List <KeyPair>(); foreach (string key in keynames) { SecRecord srSearchCriteria = new SecRecord(SecKind.GenericPassword) { Account = key }; if (sAccessGroup != null) { srSearchCriteria.AccessGroup = sAccessGroup; } SecStatusCode keyResult; SecRecord srFoundKey = SecKeyChain.QueryAsRecord(srSearchCriteria, out keyResult); if (keyResult == SecStatusCode.Success) { if (srFoundKey != null) { foundKeyPairs.Add(SecRecordToKeyPair(srFoundKey)); } } } SystemLogger.Log(SystemLogger.Module.PLATFORM, "GetStoredKeyValuePairs - Found: " + foundKeyPairs.Count); IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Appverse.OnKeyValuePairsFound", foundKeyPairs); }); }
/// <summary> /// Gets a password for a specific username. /// </summary> /// <param name="username">the username to query. Not case sensitive. May not be NULL.</param> /// <param name="serviceId">the service description to use. Not case sensitive. May not be NULL.</param> /// <param name="synchronizable"> /// Defines if the record you want to get is syncable via iCloud keychain or not. Note that using the same username and service ID /// but different synchronization settings will result in two keychain entries. /// </param> /// <returns> /// The password or NULL if no matching record was found. /// </returns> private static string GetPassword(string username, string serviceId, bool synchronizable) { if (username == null) { throw new ArgumentNullException("userName"); } if (serviceId == null) { throw new ArgumentNullException("serviceId"); } // Querying is case sesitive - we don't want that. username = username.ToLower( ); serviceId = serviceId.ToLower( ); SecStatusCode code; // Query the record. SecRecord queryRec = new SecRecord(SecKind.GenericPassword) { Service = serviceId, Label = serviceId, Account = username, Synchronizable = synchronizable }; queryRec = SecKeyChain.QueryAsRecord(queryRec, out code); // If found, try to get password. if (code == SecStatusCode.Success && queryRec != null && queryRec.Generic != null) { // Decode from UTF8. return(NSString.FromData(queryRec.Generic, NSStringEncoding.UTF8)); } // Something went wrong. return(null); }
public Task <T> GetAsync <T>(string key) { var formattedKey = string.Format(_keyFormat, key); byte[] dataBytes = null; using (var existingRecord = GetKeyRecord(formattedKey)) using (var record = SecKeyChain.QueryAsRecord(existingRecord, out SecStatusCode resultCode)) { if (resultCode == SecStatusCode.ItemNotFound) { return(Task.FromResult((T)(object)null)); } CheckError(resultCode); dataBytes = record.Generic.ToArray(); } var dataString = Encoding.UTF8.GetString(dataBytes); if (typeof(T) == typeof(string)) { return(Task.FromResult((T)(object)dataString)); } else { return(Task.FromResult(JsonConvert.DeserializeObject <T>(dataString, _jsonSettings))); } }
internal static string GetGoogleApiKey() { var query = new SecRecord(SecKind.GenericPassword) { Service = getKeyChainServiceString(), }; SecStatusCode res; var rec = SecKeyChain.QueryAsRecord(query, out res); switch (res) { case SecStatusCode.ItemNotFound: { return(""); } case SecStatusCode.Success: { return(NSString.FromData(rec.ValueData, NSStringEncoding.UTF8)); } default: { Debug.WriteLine("キーチェーンからのGoogle API Key取得に失敗. SecKeyChain.QueryAsRecordの結果 ---> " + res); return(""); } } }
public string Unprotect(string key) { var existingRecord = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString(key.ToLower()), Service = NSBundle.MainBundle.BundleIdentifier, Label = key.ToLower(), Account = key.ToLower(), Synchronizable = _synchronizable }; // Locate the entry in the keychain, using the label, service and account information. // The result code will tell us the outcome of the operation. SecStatusCode resultCode; existingRecord = SecKeyChain.QueryAsRecord(existingRecord, out resultCode); if (resultCode == SecStatusCode.Success) { return(NSString.FromData(existingRecord.ValueData, NSStringEncoding.UTF8)); } else { return(null); } }
void Protocol(SecProtocol protocol) { var rec = new SecRecord(SecKind.InternetPassword) { Account = $"Protocol-{protocol}-{CFBundle.GetMain ().Identifier}-{GetType ().FullName}-{Process.GetCurrentProcess ().Id}", }; try { SecKeyChain.Remove(rec); // it might already exists (or not) rec = new SecRecord(SecKind.InternetPassword) { Account = "Protocol", ValueData = NSData.FromString("Password"), Protocol = protocol, Server = "www.xamarin.com" }; Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add"); SecStatusCode code; var match = SecKeyChain.QueryAsRecord(rec, out code); Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord"); Assert.That(match.Protocol, Is.EqualTo(protocol), "Protocol"); } finally { // Clean up after us SecKeyChain.Remove(rec); } }
public bool Remove(string key) { key = KeyPrefix + key; SecRecord record = new SecRecord(SecKind.GenericPassword) { Account = key, Service = Service }; using (record) using (SecRecord match = SecKeyChain.QueryAsRecord(record, out SecStatusCode result)) { if (result == SecStatusCode.Success) { result = SecKeyChain.Remove(record); if (result != SecStatusCode.Success && result != SecStatusCode.ItemNotFound) { throw new Exception($"Error removing record: {result}"); } return(true); } } return(false); }
public Task <string> GetAsync(string key) { key = KeyPrefix + key; SecRecord record = new SecRecord(SecKind.GenericPassword) { Account = key, Service = Service }; using (record) using (SecRecord match = SecKeyChain.QueryAsRecord(record, out var result)) { if (result == SecStatusCode.Success) { return(Task.FromResult(NSString.FromData(match.ValueData, NSStringEncoding.UTF8).ToString())); } if (result == SecStatusCode.ItemNotFound) { return(Task.FromResult <string>(null)); } throw new Exception($"Error querying record: {result}"); } }
/// <summary> /// Record the date this application was installed (or the date that we started recording installation date). /// </summary> private static void StampInstallDate() { try { var query = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString("repostumble_install_date") }; SecStatusCode secStatusCode; SecKeyChain.QueryAsRecord(query, out secStatusCode); if (secStatusCode == SecStatusCode.Success) { return; } var newRec = new SecRecord(SecKind.GenericPassword) { Label = "RepoStumble Install Date", Description = "The first date RepoStumble was installed", ValueData = NSData.FromString(DateTime.UtcNow.ToString()), Generic = NSData.FromString("repostumble_install_date") }; SecKeyChain.Add(newRec); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } }
public void SaveUserInfo(string userId, string userName, string password) { var rec = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString("password") }; SecStatusCode res; var match = SecKeyChain.QueryAsRecord(rec, out res); if (res == SecStatusCode.Success) { res = SecKeyChain.Remove(rec); } var s = new SecRecord(SecKind.GenericPassword) { Service = "BodyReportUserInfo", Account = userId + (char)3 + userName, ValueData = NSData.FromString(password), Generic = NSData.FromString("password") }; res = SecKeyChain.Add(s); }
void AuthenticationType(SecAuthenticationType type) { var rec = new SecRecord(SecKind.InternetPassword) { Account = "AuthenticationType" }; SecKeyChain.Remove(rec); // it might already exists (or not) rec = new SecRecord(SecKind.InternetPassword) { Account = $"{CFBundle.GetMain ().Identifier}-{GetType ().FullName}-{Process.GetCurrentProcess ().Id}", ValueData = NSData.FromString("Password"), AuthenticationType = type, Server = "www.xamarin.com" }; Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add"); var query = new SecRecord(SecKind.InternetPassword) { Account = rec.Account, AuthenticationType = rec.AuthenticationType, Server = rec.Server, }; SecStatusCode code; var match = SecKeyChain.QueryAsRecord(query, out code); Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord"); Assert.That(match.AuthenticationType, Is.EqualTo(type), "AuthenticationType"); }
public KeyValuePair <string, string>?Load() { SecStatusCode res; var rec = new SecRecord(SecKind.GenericPassword) { Account = "login", Label = "login", Service = "login", }; var match = SecKeyChain.QueryAsRecord(rec, out res); SecStatusCode res2; var rec2 = new SecRecord(SecKind.GenericPassword) { Account = "password", Label = "password", Service = "password", }; var match2 = SecKeyChain.QueryAsRecord(rec2, out res2); if (match != null && match2 != null) { return(new KeyValuePair <string, string>(match.ValueData.ToString(), match2.ValueData.ToString())); } return(null); }
public override void ViewDidLoad() { base.ViewDidLoad(); existingRec = new SecRecord(SecKind.GenericPassword) { Service = KeyChain.Service, Label = KeyChain.Label }; SecStatusCode code; SecRecord match = SecKeyChain.QueryAsRecord(existingRec, out code); if (code == SecStatusCode.Success) { txtLogin.Text = match.Account.ToString(); txtPassword.Text = match.ValueData.ToString(); } txtLogin.EditingDidBegin += textFieldDidBeginEditing; txtPassword.EditingDidBegin += textFieldDidBeginEditing; btnLogin.TouchUpInside += btnLoginTouchUpInside; CreateLeftView("логин.png", txtLogin); CreateLeftView("пароль.png", txtPassword); }
byte[] ILegacyCachePersistence.LoadCache() { try { SecStatusCode res; var rec = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString(LocalSettingsContainerName), Accessible = SecAccessible.Always, Service = NAME + " Service", Account = NAME + " cache", Label = NAME + " Label", Comment = NAME + " Cache", Description = "Storage for cache" }; if (keychainGroup != null) { rec.AccessGroup = keychainGroup; } var match = SecKeyChain.QueryAsRecord(rec, out res); if (res == SecStatusCode.Success && match != null && match.ValueData != null) { return(match.ValueData.ToArray()); } } catch (Exception ex) { MsalLogger.Default.WarningPiiWithPrefix(ex, "Failed to load adal cache: "); // Ignore as the cache seems to be corrupt } return(null); }
public static List <string> LoadTokens() { if (ExistsSetting() == false) { CreateEmptySetting(); } var query = new SecRecord(SecKind.GenericPassword) { Account = KEYCHAIN_ACCOUNT, Service = KEYCHAIN_SERVICE, }; SecStatusCode status; var record = SecKeyChain.QueryAsRecord(query, out status); if (status == SecStatusCode.Success) { var data = record.ValueData; var tokens = JsonConvert.DeserializeObject <List <string> >(data.ToString()); return(tokens); } else { throw new IOException(status.ToString()); } }
private string GetTeamId() { var queryRecord = new SecRecord(SecKind.GenericPassword) { Service = "", Account = TeamIdKey, Accessible = SecAccessible.Always }; SecRecord match = SecKeyChain.QueryAsRecord(queryRecord, out SecStatusCode resultCode); if (resultCode == SecStatusCode.ItemNotFound) { SecKeyChain.Add(queryRecord); match = SecKeyChain.QueryAsRecord(queryRecord, out resultCode); } if (resultCode == SecStatusCode.Success) { return(match.AccessGroup.Split('.')[0]); } throw new MsalClientException( MsalError.CannotAccessPublisherKeyChain, MsalErrorMessage.CannotAccessPublisherKeyChain); }
private static SecRecord QueryRecord(SecRecord toSearch) { SecStatusCode res; var match = SecKeyChain.QueryAsRecord(toSearch, out res); return(match); }
public void SetSecured(string key, string value, string clientId, string service, string sharedGroupId) { var s = new SecRecord(SecKind.GenericPassword) { Service = $"{clientId}-{key}-{service}", }; SecStatusCode res; var match = SecKeyChain.QueryAsRecord(s, out res); if (res == SecStatusCode.Success) { var remStatus = SecKeyChain.Remove(s); } s.ValueData = NSData.FromString(value); if (!string.IsNullOrWhiteSpace(sharedGroupId)) { s.AccessGroup = sharedGroupId; } var err = SecKeyChain.Add(s); Console.WriteLine(err); }
public string GetSecured(string identifier, string clientId, string clientSecret, string sharedGroup) { var key = $"{clientId}-{identifier}-{clientSecret}"; try { var result = System.Text.Encoding.UTF8.GetString(BlobCache.LocalMachine.Get(key).Wait()); return(result); } catch (Exception ex) { try{ var rec = new SecRecord(SecKind.InternetPassword) { Service = key, Account = identifier, }; SecStatusCode res; var match = SecKeyChain.QueryAsRecord(rec, out res); if (res != SecStatusCode.Success) { return(""); } var result = match.ValueData.ToString(); SetSecured(identifier, result, clientId, clientSecret, sharedGroup); return(result); } catch (Exception) { } } return(""); }
private Tuple <SecStatusCode, SecRecord> FindRecord(string alias) { var secRecord = NewSecRecord(alias, null); var found = SecKeyChain.QueryAsRecord(secRecord, out var secStatusCode); return(new Tuple <SecStatusCode, SecRecord>(secStatusCode, found)); }
private SecRecord GetExistingRecord(string key) { var existingRecord = GetKeyRecord(key); SecKeyChain.QueryAsRecord(existingRecord, out var resultCode); return(resultCode == SecStatusCode.Success ? existingRecord : null); }
void AuthenticationType(SecAuthenticationType type) { var rec = new SecRecord(SecKind.InternetPassword) { Account = "AuthenticationType" }; SecKeyChain.Remove(rec); // it might already exists (or not) rec = new SecRecord(SecKind.InternetPassword) { Account = "AuthenticationType", ValueData = NSData.FromString("Password"), AuthenticationType = type, Server = "www.xamarin.com" }; Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add"); SecStatusCode code; var match = SecKeyChain.QueryAsRecord(rec, out code); Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord"); Assert.That(match.AuthenticationType, Is.EqualTo(type), "AuthenticationType"); }
public async Task <T> GetAsync <T>(string key) { var appId = await _getAppId.Invoke(); var formattedKey = string.Format(_keyFormat, appId, key); byte[] dataBytes = null; using (var existingRecord = GetKeyRecord(formattedKey)) using (var record = SecKeyChain.QueryAsRecord(existingRecord, out var resultCode)) { if (resultCode == SecStatusCode.ItemNotFound || resultCode == SecStatusCode.InteractionNotAllowed) { return((T)(object)null); } CheckError(resultCode); dataBytes = record.Generic.ToArray(); } var dataString = Encoding.UTF8.GetString(dataBytes); if (typeof(T) == typeof(string)) { return((T)(object)dataString); } else { return(JsonConvert.DeserializeObject <T>(dataString, _jsonSettings)); } }
void Accessible(SecAccessible access) { var rec = new SecRecord(SecKind.GenericPassword) { Account = "Username" }; SecKeyChain.Remove(rec); // it might already exists (or not) rec = new SecRecord(SecKind.GenericPassword) { Account = "Username", ValueData = NSData.FromString("Password"), Accessible = access }; Assert.That(SecKeyChain.Add(rec), Is.EqualTo(SecStatusCode.Success), "Add"); SecStatusCode code; var match = SecKeyChain.QueryAsRecord(rec, out code); Assert.That(code, Is.EqualTo(SecStatusCode.Success), "QueryAsRecord"); Assert.That(match.Accessible, Is.EqualTo(access), "Accessible"); }
public override string Get(string key) { try { key = key.ToLower(); if (string.IsNullOrEmpty(key)) { return(null); } SecStatusCode code; SecRecord queryRec = new SecRecord(SecKind.GenericPassword) { Service = serviceId, Label = serviceId, Account = key, Synchronizable = false }; queryRec = SecKeyChain.QueryAsRecord(queryRec, out code); if (code == SecStatusCode.Success && queryRec != null && queryRec.Generic != null) { string value = NSString.FromData(queryRec.Generic, NSStringEncoding.UTF8); value = Crypto.Decrypt(value, "KeyChainService_iOS"); return(value); } return(null); } catch (Exception) { return(null); } }