protected override Task <SecureValueResult> NativeSetSecureValue(SetSecureValueRequestConfiguration setSecureValueRequestConfig, CancellationToken cancellationToken) { #if __MAC__ return(Task.FromResult(new SecureValueResult { Status = FingerprintAuthenticationResultStatus.NotAvailable, ErrorMessage = "Not implemented for the current platform." })); #else var key = setSecureValueRequestConfig.Key.ToLower(); var serviceId = setSecureValueRequestConfig.ServiceId.ToLower(); var secureAccessControl = new SecAccessControl( SecAccessible.WhenPasscodeSetThisDeviceOnly, SecAccessControlCreateFlags.UserPresence); if (secureAccessControl == null) { return(Task.FromResult(new SecureValueResult { Status = FingerprintAuthenticationResultStatus.UnknownError, ErrorMessage = "Unable to create secure access control object." })); } var statusCode = SecKeyChain.Add(new SecRecord(SecKind.GenericPassword) { Service = serviceId, Label = serviceId, Account = key, Generic = NSData.FromString(setSecureValueRequestConfig.Value, NSStringEncoding.UTF8), UseNoAuthenticationUI = true, AccessControl = secureAccessControl }); return(Task.FromResult(new SecureValueResult { Status = FingerprintAuthenticationResultStatus.Succeeded, })); #endif }
public override void Save(Account account, string serviceId) { var statusCode = SecStatusCode.Success; var serializedAccount = account.Serialize(); var data = NSData.FromString(serializedAccount, NSStringEncoding.UTF8); // // Remove any existing record // var existing = FindAccount(account.Username, serviceId); if (existing != null) { var query = new SecRecord(SecKind.GenericPassword); query.Service = serviceId; query.Account = account.Username; statusCode = SecKeyChain.Remove(query); if (statusCode != SecStatusCode.Success) { throw new Exception("Could not save account to KeyChain: " + statusCode); } } // // Add this record // var record = new SecRecord(SecKind.GenericPassword); record.Service = serviceId; record.Account = account.Username; record.Generic = data; record.Accessible = SecAccessible.WhenUnlocked; statusCode = SecKeyChain.Add(record); if (statusCode != SecStatusCode.Success) { throw new Exception("Could not save account to KeyChain: " + statusCode); } }
private void SetText(string html) { // Create HTML data sting var stringType = new NSAttributedStringDocumentAttributes { DocumentType = NSDocumentType.HTML }; var nsError = new NSError(); var htmlData = NSData.FromString(html, NSStringEncoding.Unicode); using var htmlString = new NSAttributedString(htmlData, stringType, out _, ref nsError); var mutableHtmlString = htmlString.RemoveTrailingNewLines(); mutableHtmlString.EnumerateAttributes(new NSRange(0, mutableHtmlString.Length), NSAttributedStringEnumeration.None, (NSDictionary value, NSRange range, ref bool stop) => { var md = new NSMutableDictionary(value); var font = md[UIStringAttributeKey.Font] as UIFont; if (font != null) { md[UIStringAttributeKey.Font] = Control.Font.WithTraitsOfFont(font); } else { md[UIStringAttributeKey.Font] = Control.Font; } var foregroundColor = md[UIStringAttributeKey.ForegroundColor] as UIColor; if (foregroundColor == null || foregroundColor.IsEqualToColor(UIColor.Black)) { md[UIStringAttributeKey.ForegroundColor] = Control.TextColor; } mutableHtmlString.SetAttributes(md, range); }); mutableHtmlString.SetLineHeight(Element); mutableHtmlString.SetLinksStyles(Element); Control.AttributedText = mutableHtmlString; }
public void AfterAccess(TokenCacheNotificationArgs args) { if (args.TokenCache.HasStateChanged) { try { var s = 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" }; var err = SecKeyChain.Remove(s); if (err != SecStatusCode.Success) { PlatformPlugin.Logger.Warning(null, "Failed to remove cache record: " + err); } if (args.TokenCache.Count > 0) { s.ValueData = NSData.FromArray(args.TokenCache.Serialize()); err = SecKeyChain.Add(s); if (err != SecStatusCode.Success) { PlatformPlugin.Logger.Warning(null, "Failed to save cache record: " + err); } } args.TokenCache.HasStateChanged = false; } catch (Exception ex) { PlatformPlugin.Logger.Warning(null, "Failed to save cache: " + ex); } } }
void SetText() { try { var htmlText = Markdown.ToHtml(Element.Text); var htmlData = NSData.FromString(htmlText); if (htmlData != null && htmlData.Length > 0) { NSAttributedString attributedString = null; var error = new NSError(); attributedString = new NSAttributedString(htmlData, new NSAttributedStringDocumentAttributes { DocumentType = NSDocumentType.HTML, StringEncoding = NSStringEncoding.UTF8 }, ref error); Control.AttributedText = attributedString; } } catch { } }
public string QueryRecord(string key) { SecStatusCode status; var rec = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString(key) }; var match = SecKeyChain.QueryAsRecord(rec, out status); if (SecStatusCode.Success == status && null != match) { Debug.WriteLine($"{match.Account};{match.ValueData.ToString ()}"); return(match.Account); } Debug.WriteLine("Nothing found."); return(string.Empty); }
public static void InitTextViewWithSpacingAndHTMLFormat(UITextView label, FontType fontType, string rawText, double lineHeight, float fontSize, float maxFontSize) { NSAttributedStringDocumentAttributes documentAttributes = new NSAttributedStringDocumentAttributes { DocumentType = NSDocumentType.HTML }; documentAttributes.StringEncoding = NSStringEncoding.UTF8; NSError error = null; NSAttributedString attributedString = new NSAttributedString(NSData.FromString(rawText, NSStringEncoding.UTF8), documentAttributes, ref error); NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle(); paragraphStyle.LineHeightMultiple = new nfloat(lineHeight); NSMutableAttributedString text = new NSMutableAttributedString(attributedString); NSRange range = new NSRange(0, attributedString.Length); text.AddAttribute(UIStringAttributeKey.ParagraphStyle, paragraphStyle, range); text.AddAttribute(UIStringAttributeKey.Font, Font(fontType, fontSize, maxFontSize), range); label.AttributedText = text; label.TextColor = ColorHelper.TEXT_COLOR_ON_BACKGROUND; label.TextAlignment = LayoutUtils.GetTextAlignment(); }
public void SetToken(string token) { var record = FetchRecord(ACCOUNT, out var searchRecord); if (record == null) { record = new SecRecord(SecKind.InternetPassword) { Service = SERVICE, Label = SERVICE, Account = ACCOUNT, ValueData = NSData.FromString(token) }; SecKeyChain.Add(record); return; } record.ValueData = NSData.FromString(token); SecKeyChain.Update(searchRecord, record); }
static public void SetSecured(string key, string value, string service) { #if __OSX__ AkavacheAuthStorage.Shared.SetSecured(key, value, "MusicApps", service, ""); return; #endif var s = new SecRecord(SecKind.GenericPassword) { Service = $"MusicApps-{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); var err = SecKeyChain.Add(s); }
public static bool SetHtml(this UILabel lbl, string html, bool failBacktoText = true) { if (string.IsNullOrEmpty(html)) { return(true); } var attr = new NSAttributedStringDocumentAttributes(); var nsError = new NSError(); attr.DocumentType = NSDocumentType.HTML; var unicode = NSData.FromString(html, NSStringEncoding.Unicode); lbl.AttributedText = new NSAttributedString(unicode, attr, ref nsError); var flag = lbl.AttributedText.Length > 0; if (!flag && failBacktoText) { lbl.Text = html; } return(flag); }
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 bool SecuStorageSet(string key, string value) { SecRecord record = CreateGenericSecRecord(key); SecStatusCode resultCode; SecKeyChain.QueryAsRecord(record, out resultCode); if (resultCode == SecStatusCode.Success) { SecKeyChain.Remove(record); } record.ValueData = NSData.FromString(value, NSStringEncoding.UTF8); resultCode = SecKeyChain.Add(record); if (resultCode != SecStatusCode.Success) { throw new AccessViolationException("Failed to set key: " + key); } return(true); }
protected void ProvideRtf(NSPasteboard pboard, NSPasteboardItem item, string type) { var s = GetHtmlWithoutMetadata(); if (s == null) { return; } var nsdata = NSData.FromString(s, NSStringEncoding.UTF8); var options = new NSMutableDictionary { [Pasteboard.NSDocumentTypeDocumentAttribute] = (NSString)Pasteboard.NSHTMLTextDocumentType, [Pasteboard.NSCharacterEncodingDocumentAttribute] = new NSNumber((ulong)NSStringEncoding.UTF8) }; var rtf = new NSAttributedString(nsdata, options, out NSDictionary attributes, out NSError error); options[Pasteboard.NSDocumentTypeDocumentAttribute] = (NSString)Pasteboard.NSRTFTextDocumentType; nsdata = rtf.GetData(new NSRange(0, rtf.Length), options, out error); item.SetDataForType(nsdata, Pasteboard.NSPasteboardTypeRTF); }
protected override void OnElementChanged(ElementChangedEventArgs<Label> e) { base.OnElementChanged(e); if (e.NewElement == null) { return; } var attr = new NSAttributedStringDocumentAttributes(); var nsError = new NSError(); attr.DocumentType = NSDocumentType.HTML; var text = e.NewElement.Text; text = "<style>body{font-family: '" + this.Control.Font.Name + "'; font-size:" + this.Control.Font.PointSize + "px;}</style>" + text; var myHtmlData = NSData.FromString(text, NSStringEncoding.Unicode); Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError); }
public static SecStatusCode UpdateKeychain() { var secret = NSData.FromString(UIDevice.CurrentDevice.IdentifierForVendor.ToString(), NSStringEncoding.Unicode); var update = new SecRecord(SecKind.GenericPassword) { ValueData = secret }; var query = new SecRecord(SecKind.GenericPassword) { Service = NSBundle.MainBundle.BundleIdentifier, Account = "SecurityViewAccount", AccessControl = new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly, SecAccessControlCreateFlags.UserPresence), UseNoAuthenticationUI = true, ValueData = secret, UseOperationPrompt = "Authenticate to Update" }; return(SecKeyChain.Update(query, update)); }
public void KeyEncryption() { const int keySize = 512; string keyIdentifier = Guid.NewGuid().ToString(); string publicKeyIdentifier = GetPublicKeyIdentifierWithTag(keyIdentifier); string privateKeyIdentifier = GetPrivateKeyIdentifierWithTag(keyIdentifier); // Configure parameters for the joint keypair. var keyPairAttr = new NSMutableDictionary(); keyPairAttr[KSec.AttrKeyType] = KSec.AttrKeyTypeRSA; keyPairAttr[KSec.AttrKeySizeInBits] = NSNumber.FromInt32(keySize); // Configure parameters for the private key var privateKeyAttr = new NSMutableDictionary(); privateKeyAttr[KSec.AttrIsPermanent] = NSNumber.FromBoolean(true); privateKeyAttr[KSec.AttrApplicationTag] = NSData.FromString(privateKeyIdentifier, NSStringEncoding.UTF8); // Configure parameters for the public key var publicKeyAttr = new NSMutableDictionary(); publicKeyAttr[KSec.AttrIsPermanent] = NSNumber.FromBoolean(true); publicKeyAttr[KSec.AttrApplicationTag] = NSData.FromString(publicKeyIdentifier, NSStringEncoding.UTF8); // Parent the individual key parameters to the keypair one. keyPairAttr[KSec.PublicKeyAttrs] = publicKeyAttr; keyPairAttr[KSec.PrivateKeyAttrs] = privateKeyAttr; // Generate the RSA key. SecKey publicKey, privateKey; SecStatusCode code = SecKey.GenerateKeyPair(keyPairAttr, out publicKey, out privateKey); Verify.Operation(code == SecStatusCode.Success, "status was " + code); byte[] plainText = new byte[0]; // when this buffer is non-empty, Encrypt works! byte[] cipherText; code = publicKey.Encrypt(SecPadding.OAEP, plainText, out cipherText); Verify.Operation(code == SecStatusCode.Success, "status was " + code); }
private void SaveKey(string keyName, string value) { if (this.Log().IsEnabled(LogLevel.Debug)) { this.Log().Debug($"Saving the key (key name: '{keyName}')."); } var record = new SecRecord(SecKind.GenericPassword) { Service = keyName.ToLowerInvariant(), }; var status = SecKeyChain.Remove(record); if (status == SecStatusCode.Success || status == SecStatusCode.ItemNotFound) { record.AccessControl = new SecAccessControl( SecAccessible.WhenPasscodeSetThisDeviceOnly, _fallbackOnPasscodeAuthentication ? SecAccessControlCreateFlags.UserPresence : SecAccessControlCreateFlags.TouchIDCurrentSet ); record.Generic = NSData.FromString(value); var result = SecKeyChain.Add(record); if (result != SecStatusCode.Success) { throw new SecurityException(result); } if (this.Log().IsEnabled(LogLevel.Information)) { this.Log().Info($"Successfully saved the key (key name: '{keyName}')."); } } else { throw new SecurityException(status); } }
protected override void OnElementChanged(ElementChangedEventArgs <View> elementChangedEventArgs) { base.OnElementChanged(elementChangedEventArgs); if (elementChangedEventArgs.NewElement != null) { referenceLink = (ReferenceLink)elementChangedEventArgs.NewElement; if (referenceLink == null) { return; } referenceLink.PropertyChanged += OnPropertyChanged; NSAttributedString attributedString = null; var htmlData = NSData.FromString(referenceLink.HtmlText); if (htmlData != null) { NSError error = new NSError(); attributedString = new NSAttributedString(htmlData, new NSAttributedStringDocumentAttributes { DocumentType = NSDocumentType.HTML, StringEncoding = NSStringEncoding.UTF8 }, ref error); } var action = referenceLink.Action; textView = new UITextView(); textView.TextColor = UIColor.Gray; textView.ApplySubtitlesLinks(action(), referenceLink.Sources, attributedString); textView.Editable = false; textView.ScrollEnabled = false; textView.Font = UIFont.SystemFontOfSize((nfloat)referenceLink.FontSize); // replace old Label with new TextView SetNativeControl(textView); } }
public static MayFail <object> RegisterGoogleApiKey(string googleApiKey) { var dic = NSBundle.MainBundle.InfoDictionary; var appName = dic["CFBundleName"]; var service = getKeyChainServiceString(); var rec = new SecRecord(SecKind.GenericPassword) { Label = appName + " - Google Shortener APIのキー", Description = appName + "がURLの短縮に使うGoogle Shortener APIのキーを保存します.", Service = service, ValueData = NSData.FromString(googleApiKey), }; var addRet = SecKeyChain.Add(rec); switch (addRet) { case SecStatusCode.DuplicateItem: { var query = rec; var updateRet = SecKeyChain.Update(query, rec); if (updateRet != SecStatusCode.Success) { Debug.WriteLine(updateRet); return(MayFailFactory.NewFail <object>("キーチェーンへの保存に失敗しました.")); } return(MayFailFactory.NewSuccess <object>(null)); } case SecStatusCode.Success: { return(MayFailFactory.NewSuccess <object>(null)); } default: { Debug.WriteLine(addRet); return(MayFailFactory.NewFail <object>("キーチェーンへの保存に失敗しました.")); } } }
public static void StoreTokenKeyChain(Guid token) { var record = GetTokenKeyChain(out SecRecord tokenQuery); if (record == null) { record = new SecRecord(SecKind.GenericPassword) { Service = ServiceName, Account = TokenKey, Label = TokenKey, ValueData = NSData.FromString(token.ToString( )) }; SecStatusCode statusCode = SecKeyChain.Add(record); Console.WriteLine("KeyChain Status Code: " + statusCode); return; } record.ValueData = NSData.FromString(token.ToString( )); SecKeyChain.Update(tokenQuery, record); }
public static void BeforeAccess(TokenCacheNotificationArgs args) { if (args.TokenCache.Count > 0) { // We assume that the cache has not changed since last write return; } 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" }; var match = SecKeyChain.QueryAsRecord(rec, out res); if (res == SecStatusCode.Success && match != null && match.ValueData != null) { byte[] dataBytes = match.ValueData.ToArray(); if (dataBytes != null) { args.TokenCache.Deserialize(dataBytes); } } } catch (Exception ex) { CallState.Default.Logger.Warning(null, "Failed to load cache: "); CallState.Default.Logger.ErrorPii(null, ex); // Ignore as the cache seems to be corrupt } }
/// <summary> /// Gets the items for beginning drag session. /// </summary> /// <returns>The items for beginning drag session.</returns> /// <param name="tableView">Table view.</param> /// <param name="session">Session.</param> /// <param name="indexPath">Index path.</param> public UIDragItem[] GetItemsForBeginningDragSession(UITableView tableView, IUIDragSession session, NSIndexPath indexPath) { var section = Element.Model.GetSection(indexPath.Section); if (!section.UseDragSort) { return(new UIDragItem[] {}); } // set "sectionIndex,rowIndex" as string var data = NSData.FromString($"{indexPath.Section},{indexPath.Row}"); var itemProvider = new NSItemProvider(); itemProvider.RegisterDataRepresentation(UTType.PlainText, NSItemProviderRepresentationVisibility.All, (completionHandler) => { completionHandler(data, null); return(null); }); return(new UIDragItem[] { new UIDragItem(itemProvider) }); }
public static void SetPassword(string username, string password) { SecRecord searchRecord; var record = FetchRecord(username, out searchRecord); if (record == null) { record = new SecRecord(SecKind.InternetPassword) { Service = ServiceName, Label = ServiceName, Account = username, ValueData = NSData.FromString(password) }; SecKeyChain.Add(record); return; } record.ValueData = NSData.FromString(password); SecKeyChain.Update(searchRecord, record); }
public static void SetPat(string pat) { SecRecord searchRecord; var record = FetchKeychainRecord(out searchRecord); if (record == null) { record = new SecRecord(SecKind.InternetPassword) { Server = _serviceName, Label = _serviceName, Account = _account, ValueData = NSData.FromString(pat) }; SecKeyChain.Add(record); return; } record.ValueData = NSData.FromString(pat); SecKeyChain.Update(searchRecord, record); }
//a simple way to generate and persist unique id for ios device using keychain. This unique id won't change even if app is uninstalled and re-installed. //only for devices pre ios 6 (from here: http://david-smith.org/iosversionstats/, only < 5% devices) private string UniqueID() { var query = new SecRecord(SecKind.GenericPassword); query.Service = NSBundle.MainBundle.BundleIdentifier; query.Account = "UniqueID"; var uniqueId = SecKeyChain.QueryAsData(query); if (uniqueId == null) { query.ValueData = NSData.FromString(Guid.NewGuid().ToString()); var err = SecKeyChain.Add(query); if (err != SecStatusCode.Success && err != SecStatusCode.DuplicateItem) { _logger.i("IOSDeviceService", "Failed to save unique id", null); } return(query.ValueData.ToString()); } return(uniqueId.ToString()); }
private bool storeRecordInKeychainInternal(string key, string value, SecAccessible access) { try { var secRecord = new SecRecord(SecKind.GenericPassword) { ValueData = NSData.FromString(value), Account = key, Service = "PlayOnCloudServiceID", Accessible = access }; var error = SecKeyChain.Add(secRecord); if (error == SecStatusCode.DuplicateItem) { if (SecKeyChain.Remove(secRecord) == SecStatusCode.ItemNotFound) { var oldSecRecord = new SecRecord(SecKind.GenericPassword) { ValueData = NSData.FromString(value), Account = key, Service = "PlayOnCloudServiceID" }; SecKeyChain.Remove(oldSecRecord); } error = SecKeyChain.Add(secRecord); } return(error == SecStatusCode.Success); } catch (Exception ex) { Logger.Log("ERROR: StoreRecordInKeychain: " + ex); } return(false); }
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 override NSObject ContentsForType(string typeName, out NSError outError) { try { outError = null; var text = TextData; var data = NSData.FromString(text, NSStringEncoding.UTF8); Debug.WriteLine("SAVE " + LocalFilePath); Saving(this, new SavingEventArgs { TextData = text }); return(data); } catch (Exception ex) { Log.Error(ex); outError = new NSError(new NSString("Praeclarum"), 334); return(new NSData()); } }
private void PlatformWriteFile(string path, string contents) { if (FileExists(path)) { NSFileHandle handle = NSFileHandle.OpenUpdateUrl(NSUrl.CreateFileUrl(new[] { path }), out NSError error); if (error != null) { throw new NSErrorException(error); } else { handle.SeekToEndOfFile(); handle.WriteData(NSData.FromString(contents)); handle.CloseFile(); } } else { CreateFile(path, NSData.FromString(contents)); } }
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"); }