Here are the examples of the csharp api System.Convert.ToBase64String(byte[], int, int, System.Base64FormattingOptions) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1193 Examples
19
View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public override string? Readreplacedtring(ISqDataRecordReader recordReader)
{
var base64Str = this.ReadNullable(recordReader);
return base64Str == null ? null : Convert.ToBase64String(base64Str);
}
19
View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public override string? Readreplacedtring(ISqDataRecordReader recordReader)
{
var base64Str = this.Read(recordReader);
return base64Str == null ? null : Convert.ToBase64String(base64Str);
}
19
View Source File : ExprPlainWriter.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public void VisitPlainProperty(string name, IReadOnlyList<byte>? value, int ctx)
{
this._buffer.Add(this._factory(ctx, ctx, null, false, name, value != null ? Convert.ToBase64String(value.ToArray()) : null));
}
19
View Source File : CSRedisClientStringTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
async public Task AppendAsync()
{
var key = "TestAppendAsync_null";
await rds.SetAsync(key, base.String);
await rds.AppendAsync(key, base.Null);
replacedert.Equal(await rds.GetAsync(key), base.String);
key = "TestAppendAsync_string";
await rds.SetAsync(key, base.String);
await rds.AppendAsync(key, base.String);
replacedert.Equal(await rds.GetAsync(key), base.String + base.String);
key = "TestAppendAsync_bytes";
await rds.SetAsync(key, base.Bytes);
await rds.AppendAsync(key, base.Bytes);
replacedert.Equal(Convert.ToBase64String(await rds.GetAsync<byte[]>(key)), Convert.ToBase64String(base.Bytes.Concat(base.Bytes).ToArray()));
}
19
View Source File : CSRedisClientStringTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void Append() {
var key = "TestAppend_null";
rds.Set(key, base.String);
rds.Append(key, base.Null);
replacedert.Equal(rds.Get(key), base.String);
key = "TestAppend_string";
rds.Set(key, base.String);
rds.Append(key, base.String);
replacedert.Equal(rds.Get(key), base.String + base.String);
var ms = new MemoryStream();
rds.Get(key, ms);
replacedert.Equal(Encoding.UTF8.GetString(ms.ToArray()), base.String + base.String);
ms.Close();
key = "TestAppend_bytes";
rds.Set(key, base.Bytes);
rds.Append(key, base.Bytes);
replacedert.Equal(Convert.ToBase64String(rds.Get<byte[]>(key)), Convert.ToBase64String(base.Bytes.Concat(base.Bytes).ToArray()));
}
19
View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void Append()
{
var key = "TestAppend_null";
cli.Set(key, String);
cli.Append(key, Null);
replacedert.Equal(cli.Get(key), String);
key = "TestAppend_string";
cli.Set(key, String);
cli.Append(key, String);
replacedert.Equal(cli.Get(key), String + String);
var ms = new MemoryStream();
cli.Get(key, ms);
replacedert.Equal(Encoding.UTF8.GetString(ms.ToArray()), String + String);
ms.Close();
key = "TestAppend_bytes";
cli.Set(key, Bytes);
cli.Append(key, Bytes);
replacedert.Equal(Convert.ToBase64String(cli.Get<byte[]>(key)), Convert.ToBase64String(Bytes.Concat(Bytes).ToArray()));
}
19
View Source File : AuthController.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
[HttpGet]
public IActionResult Code()
{
var code = CaptchaUtil.GetRandomEnDigitalText();
var verifyCode = CaptchaUtil.GenerateCaptchaImage(code);
RedisServer.Cache.Set($"Captcha:{verifyCode.CaptchaGUID}", verifyCode.CaptchaCode, 1800);
JObject result = new JObject();
result.Add("captchaCode", $"data:image/png;base64,{Convert.ToBase64String(verifyCode.CaptchaMemoryStream.ToArray())}");
result.Add("captchaGUID", verifyCode.CaptchaGUID);
return toResponse(result);
}
19
View Source File : FileChecker.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static void ReHashFiles(List<ModelFileInfo> rep, string folder, List<string> fileNames)
{
var dir = rep.ToDictionary(f => f.FileName);
var computeHash = new FastComputeHash();
foreach (var fileName in fileNames)
{
ModelFileInfo mfi;
if (!dir.TryGetValue(fileName, out mfi))
{
mfi = new ModelFileInfo()
{
FileName = fileName,
};
rep.Add(mfi);
}
var file = Path.Combine(folder, fileName);
var oldHash = mfi.Hash;
//if (MainHelper.DebugMode)
Loger.Log($"ReHashFile b {file} {(oldHash == null ? "" : Convert.ToBase64String(oldHash))}" + $"->{(mfi.Hash == null ? "" : Convert.ToBase64String(mfi.Hash))}");
GetCheckSum(mfi, file, computeHash);
//if (MainHelper.DebugMode)
Loger.Log($"ReHashFile e {file} {(oldHash == null ? "" : Convert.ToBase64String(oldHash))}" + $"->{(mfi.Hash == null ? "" : Convert.ToBase64String(mfi.Hash))}");
}
computeHash.Wait();
for (int i = 0; i < rep.Count; i++)
{
if (rep[i].Hash == null)
{
rep.RemoveAt(i--);
}
}
computeHash.Wait();
}
19
View Source File : PlayerCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[CommandHandler("reportbug", AccessLevel.Player, CommandHandlerFlag.RequiresWorld, 2,
"Generate a Bug Report",
"<category> <description>\n" +
"This command generates a URL for you to copy and paste into your web browser to submit for review by server operators and developers.\n" +
"Category can be the following:\n" +
"Creature\n" +
"NPC\n" +
"Item\n" +
"Quest\n" +
"Recipe\n" +
"Landblock\n" +
"Mechanic\n" +
"Code\n" +
"Other\n" +
"For the first three options, the bug report will include identifiers for what you currently have selected/targeted.\n" +
"After category, please include a brief description of the issue, which you can further detail in the report on the website.\n" +
"Examples:\n" +
"/reportbug creature Drudge Prowler is over powered\n" +
"/reportbug npc Ulgrim doesn't know what to do with Sake\n" +
"/reportbug quest I can't enter the portal to the Lost City of Frore\n" +
"/reportbug recipe I cannot combine Bundle of Arrowheads with Bundle of Arrowshafts\n" +
"/reportbug code I was killed by a Non-Player Killer\n"
)]
public static void HandleReportbug(Session session, params string[] parameters)
{
if (!PropertyManager.GetBool("reportbug_enabled").Item)
{
session.Network.EnqueueSend(new GameMessageSystemChat("The command \"reportbug\" is not currently enabled on this server.", ChatMessageType.Broadcast));
return;
}
var category = parameters[0];
var description = "";
for (var i = 1; i < parameters.Length; i++)
description += parameters[i] + " ";
description.Trim();
switch (category.ToLower())
{
case "creature":
case "npc":
case "quest":
case "item":
case "recipe":
case "landblock":
case "mechanic":
case "code":
case "other":
break;
default:
category = "Other";
break;
}
var sn = ConfigManager.Config.Server.WorldName;
var c = session.Player.Name;
var st = "ACE";
//var versions = ServerBuildInfo.GetVersionInfo();
var databaseVersion = DatabaseManager.World.GetVersion();
var sv = ServerBuildInfo.FullVersion;
var pv = databaseVersion.PatchVersion;
//var ct = PropertyManager.GetString("reportbug_content_type").Item;
var cg = category.ToLower();
var w = "";
var g = "";
if (cg == "creature" || cg == "npc"|| cg == "item" || cg == "item")
{
var objectId = new ObjectGuid();
if (session.Player.HealthQueryTarget.HasValue || session.Player.ManaQueryTarget.HasValue || session.Player.CurrentAppraisalTarget.HasValue)
{
if (session.Player.HealthQueryTarget.HasValue)
objectId = new ObjectGuid((uint)session.Player.HealthQueryTarget);
else if (session.Player.ManaQueryTarget.HasValue)
objectId = new ObjectGuid((uint)session.Player.ManaQueryTarget);
else
objectId = new ObjectGuid((uint)session.Player.CurrentAppraisalTarget);
//var wo = session.Player.CurrentLandblock?.GetObject(objectId);
var wo = session.Player.FindObject(objectId.Full, Player.SearchLocations.Everywhere);
if (wo != null)
{
w = $"{wo.WeenieClreplacedId}";
g = $"0x{wo.Guid:X8}";
}
}
}
var l = session.Player.Location.ToLOCString();
var issue = description;
var urlbase = $"https://www.accpp.net/bug?";
var url = urlbase;
if (sn.Length > 0)
url += $"sn={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sn))}";
if (c.Length > 0)
url += $"&c={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(c))}";
if (st.Length > 0)
url += $"&st={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(st))}";
if (sv.Length > 0)
url += $"&sv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sv))}";
if (pv.Length > 0)
url += $"&pv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(pv))}";
//if (ct.Length > 0)
// url += $"&ct={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ct))}";
if (cg.Length > 0)
{
if (cg == "npc")
cg = cg.ToUpper();
else
cg = char.ToUpper(cg[0]) + cg.Substring(1);
url += $"&cg={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cg))}";
}
if (w.Length > 0)
url += $"&w={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(w))}";
if (g.Length > 0)
url += $"&g={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(g))}";
if (l.Length > 0)
url += $"&l={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(l))}";
if (issue.Length > 0)
url += $"&i={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(issue))}";
var msg = "\n\n\n\n";
msg += "Bug Report - Copy and Paste the following URL into your browser to submit a bug report\n";
msg += "-=-\n";
msg += $"{url}\n";
msg += "-=-\n";
msg += "\n\n\n\n";
session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.AdminTell));
}
19
View Source File : SignRequest.cs
License : MIT License
Project Creator : ActiveLogin
License : MIT License
Project Creator : ActiveLogin
private static string? ToBase64EncodedString(byte[]? value)
{
if (value == null)
{
return null;
}
return Convert.ToBase64String(value);
}
19
View Source File : GrandIdApiClient.cs
License : MIT License
Project Creator : ActiveLogin
License : MIT License
Project Creator : ActiveLogin
private static string? GetBase64EncodedString(string? value)
{
if (value == null)
{
return null;
}
return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
}
19
View Source File : StreamVideoSourceHandler.cs
License : MIT License
Project Creator : adamfisher
License : MIT License
Project Creator : adamfisher
private string GetFileName(Stream stream, string format)
{
var hasher = MD5.Create();
var hashBytes = hasher.ComputeHash(stream);
stream.Position = 0;
var hash = Convert.ToBase64String(hashBytes)
.Replace("=", string.Empty)
.Replace("\\", string.Empty)
.Replace("/", string.Empty);
return $"{hash}_temp.{format}";
}
19
View Source File : PortalBusMessage.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public virtual void Initialize(IOwinContext context, IDataProtector protector)
{
var id = Guid.NewGuid().ToString();
var token = Convert.ToBase64String(protector.Protect(Encoding.UTF8.GetBytes(id)));
Id = id;
Token = token;
}
19
View Source File : EntityNamePrivacy.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string GetEnreplacedyName(string enreplacedyLogicalName)
{
if (string.IsNullOrEmpty(enreplacedyLogicalName))
{
return enreplacedyLogicalName;
}
return PortalEnreplacedyAllowedList.Contains(enreplacedyLogicalName)
? enreplacedyLogicalName
: Convert.ToBase64String(HashPii.ComputeHashPiiSha256(Encoding.UTF8.GetBytes(enreplacedyLogicalName)));
}
19
View Source File : AnnotationDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IAnnotationResult UpdateAnnotation(IAnnotation note, IAnnotationSettings settings = null)
{
var serviceContext = _dependencies.GetServiceContext();
var serviceContextForWrite = _dependencies.GetServiceContextForWrite();
if (settings == null)
{
settings = new AnnotationSettings(serviceContext);
}
var storageAccount = GetStorageAccount(serviceContext);
if (settings.StorageLocation == StorageLocation.AzureBlobStorage && storageAccount == null)
{
settings.StorageLocation = StorageLocation.CrmDoreplacedent;
}
AnnotationUpdateResult result = null;
if (settings.RespectPermissions)
{
var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
result = new AnnotationUpdateResult(note, enreplacedyPermissionProvider, serviceContext);
}
var isPostedByCurrentUser = false;
var noteContact = AnnotationHelper.GetNoteContact(note.Enreplacedy.GetAttributeValue<string>("subject"));
var currentUser = _dependencies.GetPortalUser();
if (noteContact != null && currentUser != null && currentUser.LogicalName == "contact" &&
currentUser.Id == noteContact.Id)
{
isPostedByCurrentUser = true;
}
// ReSharper disable once PossibleNullReferenceException
if (!settings.RespectPermissions || (result.PermissionsExist && result.PermissionGranted && isPostedByCurrentUser))
{
var enreplacedy = new Enreplacedy("annotation")
{
Id = note.AnnotationId
};
enreplacedy.SetAttributeValue("notetext", note.NoteText);
enreplacedy.SetAttributeValue("subject", note.Subject);
enreplacedy.SetAttributeValue("isdoreplacedent", note.FileAttachment != null);
if (note.FileAttachment != null)
{
var accept = GetAcceptRegex(settings.AcceptMimeTypes);
if (!accept.IsMatch(note.FileAttachment.MimeType))
{
throw new AnnotationException(settings.RestrictMimeTypesErrorMessage);
}
if (settings.MaxFileSize.HasValue && note.FileAttachment.FileSize > settings.MaxFileSize)
{
throw new AnnotationException(settings.MaxFileSizeErrorMessage);
}
note.FileAttachment.Annotation = enreplacedy;
switch (settings.StorageLocation)
{
case StorageLocation.CrmDoreplacedent:
var crmFile = note.FileAttachment as CrmAnnotationFile;
if (crmFile == null || crmFile.Doreplacedent == null || crmFile.Doreplacedent.Length == 0)
{
break;
}
if (!string.IsNullOrEmpty(settings.RestrictedFileExtensions))
{
var blocked = new Regex(@"\.({0})$".FormatWith(settings.RestrictedFileExtensions.Replace(";", "|")));
if (blocked.IsMatch(crmFile.FileName))
{
throw new AnnotationException(settings.RestrictedFileExtensionsErrorMessage);
}
}
enreplacedy.SetAttributeValue("filename", crmFile.FileName);
enreplacedy.SetAttributeValue("mimetype", crmFile.MimeType);
enreplacedy.SetAttributeValue("doreplacedentbody", Convert.ToBase64String(crmFile.Doreplacedent));
break;
case StorageLocation.AzureBlobStorage:
enreplacedy.SetAttributeValue("filename", note.FileAttachment.FileName + ".azure.txt");
enreplacedy.SetAttributeValue("mimetype", "text/plain");
var fileMetadata = new
{
Name = note.FileAttachment.FileName,
Type = note.FileAttachment.MimeType,
Size = (ulong)note.FileAttachment.FileSize,
Url = string.Empty
};
enreplacedy.SetAttributeValue("doreplacedentbody",
Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
break;
}
}
serviceContextForWrite.Attach(enreplacedy);
serviceContextForWrite.UpdateObject(enreplacedy);
serviceContextForWrite.SaveChanges();
if (note.FileAttachment is AzureAnnotationFile && settings.StorageLocation == StorageLocation.AzureBlobStorage)
{
var azureFile = note.FileAttachment as AzureAnnotationFile;
if (azureFile.GetFileStream() != null)
{
var container = GetBlobContainer(storageAccount, _containerName);
var oldName = note.Enreplacedy.GetAttributeValue<string>("filename");
var oldBlob = container.GetBlockBlobReference("{0:N}/{1}".FormatWith(enreplacedy.Id.ToString(), oldName));
oldBlob.DeleteIfExists();
azureFile.BlockBlob = UploadBlob(azureFile, container, note.AnnotationId);
var fileMetadata = new
{
Name = azureFile.FileName,
Type = azureFile.MimeType,
Size = (ulong)azureFile.FileSize,
Url = azureFile.BlockBlob.Uri.AbsoluteUri
};
enreplacedy.SetAttributeValue("doreplacedentbody",
Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
serviceContextForWrite.UpdateObject(enreplacedy);
serviceContextForWrite.SaveChanges();
}
}
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "edit_note", 1, new EnreplacedyReference("annotation", note.AnnotationId), "edit");
}
return result;
}
19
View Source File : AnnotationDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void CopyBlob(IAnnotation note, IEnumerable<Tuple<Guid, Guid>> newNoteInfos)
{
var azureBlob = note.FileAttachment as AzureAnnotationFile;
if (azureBlob == null)
{
return;
}
var fileName = azureBlob.FileName;
var fromBlob = azureBlob.BlockBlob;
if (fromBlob.Exists())
{
var context = _dependencies.GetServiceContextForWrite();
foreach (var newNoteInfo in newNoteInfos)
{
var newNoteId = newNoteInfo.Item2;
var storageAccount = GetStorageAccount(context);
var container = GetBlobContainer(storageAccount, _containerName);
var toBlob = container.GetBlockBlobReference("{0:N}/{1}".FormatWith(newNoteId.ToString("N"), fileName));
toBlob.DeleteIfExists();
toBlob.StartCopy(fromBlob);
var azureFile = note.FileAttachment as AzureAnnotationFile;
var enreplacedy = new Enreplacedy("annotation")
{
Id = newNoteId
};
var fileMetadata = new
{
Name = azureFile.FileName,
Type = azureFile.MimeType,
Size = (ulong)azureFile.FileSize,
Url = toBlob.Uri.AbsoluteUri
};
enreplacedy.SetAttributeValue("doreplacedentbody",
Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
context.Attach(enreplacedy);
context.SaveChanges();
}
}
}
19
View Source File : AnnotationDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IAnnotationResult CreateAnnotation(IAnnotation note, IAnnotationSettings settings = null)
{
var serviceContext = _dependencies.GetServiceContext();
var serviceContextForWrite = _dependencies.GetServiceContextForWrite();
if (settings == null)
{
settings = new AnnotationSettings(serviceContext);
}
var storageAccount = GetStorageAccount(serviceContext);
if (settings.StorageLocation == StorageLocation.AzureBlobStorage && storageAccount == null)
{
settings.StorageLocation = StorageLocation.CrmDoreplacedent;
}
AnnotationCreateResult result = null;
if (settings.RespectPermissions)
{
var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
result = new AnnotationCreateResult(enreplacedyPermissionProvider, serviceContext, note.Regarding);
}
// ReSharper disable once PossibleNullReferenceException
if (!settings.RespectPermissions ||
(result.PermissionsExist && result.PermissionGranted))
{
var enreplacedy = new Enreplacedy("annotation");
if (note.Owner != null)
{
enreplacedy.SetAttributeValue("ownerid", note.Owner);
}
enreplacedy.SetAttributeValue("subject", note.Subject);
enreplacedy.SetAttributeValue("notetext", note.NoteText);
enreplacedy.SetAttributeValue("objectid", note.Regarding);
enreplacedy.SetAttributeValue("objecttypecode", note.Regarding.LogicalName);
if (note.FileAttachment != null)
{
var acceptMimeTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptMimeTypes);
var acceptExtensionTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptExtensionTypes);
if (!(acceptExtensionTypes.IsMatch(Path.GetExtension(note.FileAttachment.FileName).ToLower()) ||
acceptMimeTypes.IsMatch(note.FileAttachment.MimeType)))
{
throw new AnnotationException(settings.RestrictMimeTypesErrorMessage);
}
if (settings.MaxFileSize.HasValue && note.FileAttachment.FileSize > settings.MaxFileSize)
{
throw new AnnotationException(settings.MaxFileSizeErrorMessage);
}
note.FileAttachment.Annotation = enreplacedy;
switch (settings.StorageLocation)
{
case StorageLocation.CrmDoreplacedent:
var crmFile = note.FileAttachment as CrmAnnotationFile;
if (crmFile == null)
{
break;
}
if (!string.IsNullOrEmpty(settings.RestrictedFileExtensions))
{
var blocked = new Regex(@"\.({0})$".FormatWith(settings.RestrictedFileExtensions.Replace(";", "|")));
if (blocked.IsMatch(crmFile.FileName))
{
throw new AnnotationException(settings.RestrictedFileExtensionsErrorMessage);
}
}
enreplacedy.SetAttributeValue("filename", crmFile.FileName);
enreplacedy.SetAttributeValue("mimetype", crmFile.MimeType);
enreplacedy.SetAttributeValue("doreplacedentbody", Convert.ToBase64String(crmFile.Doreplacedent));
break;
case StorageLocation.AzureBlobStorage:
enreplacedy.SetAttributeValue("filename", note.FileAttachment.FileName + ".azure.txt");
enreplacedy.SetAttributeValue("mimetype", "text/plain");
var fileMetadata = new
{
Name = note.FileAttachment.FileName,
Type = note.FileAttachment.MimeType,
Size = (ulong)note.FileAttachment.FileSize,
Url = string.Empty
};
enreplacedy.SetAttributeValue("doreplacedentbody",
Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
break;
}
}
// Create annotaion but skip cache invalidation.
var id = (serviceContext as IOrganizationService).ExecuteCreate(enreplacedy, RequestFlag.ByPreplacedCacheInvalidation);
if (result != null) result.Annotation = note;
note.AnnotationId = enreplacedy.Id = id;
note.Enreplacedy = enreplacedy;
if (note.FileAttachment is AzureAnnotationFile && settings.StorageLocation == StorageLocation.AzureBlobStorage)
{
var container = GetBlobContainer(storageAccount, _containerName);
var azureFile = (AzureAnnotationFile)note.FileAttachment;
azureFile.BlockBlob = UploadBlob(azureFile, container, note.AnnotationId);
var fileMetadata = new
{
Name = azureFile.FileName,
Type = azureFile.MimeType,
Size = (ulong)azureFile.FileSize,
Url = azureFile.BlockBlob.Uri.AbsoluteUri
};
enreplacedy.SetAttributeValue("doreplacedentbody",
Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
serviceContextForWrite.UpdateObject(enreplacedy);
serviceContextForWrite.SaveChanges();
// NB: This is basically a hack to support replication. Keys are gathered up and stored during replication, and the
// actual blob replication is handled here.
var key = note.AnnotationId.ToString("N");
if (HttpContext.Current.Application.AllKeys.Contains(NoteReplication.BlobReplicationKey))
{
var replication =
HttpContext.Current.Application[NoteReplication.BlobReplicationKey] as Dictionary<string, Tuple<Guid, Guid>[]>;
if (replication != null && replication.ContainsKey(key))
{
CopyBlob(note, replication[key]);
replication.Remove(key);
}
}
}
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "create_note", 1, note.Enreplacedy.ToEnreplacedyReference(), "create");
}
return result;
}
19
View Source File : Substitution.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public override void Render(Context context, TextWriter result)
{
var html = context.Registers["htmlHelper"] as HtmlHelper;
if (html == null)
{
return;
}
var source = NodeList.Cast<string>().Aggregate(new StringBuilder(), (sb, token) => sb.Append(token));
var viewSupportsDonuts = context.ViewSupportsDonuts();
context.Stack(() =>
{
// If donuts are supported then call the LiquidSubsreplacedution action, otherwise render the liquid code directly.
if (viewSupportsDonuts)
{
var encodedSource = Convert.ToBase64String(Encoding.UTF8.GetBytes(source.ToString()));
result.Write(html.Action("LiquidSubsreplacedution", "Layout", new { encodedSource }, viewSupportsDonuts));
}
else
{
html.RenderLiquid(source.ToString(), "Subsreplacedution string, but donuts not supported", result);
}
});
}
19
View Source File : JsonBase64Converter.cs
License : MIT License
Project Creator : Adyen
License : MIT License
Project Creator : Adyen
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var json = JsonConvert.SerializeObject(value, Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
writer.WriteValue(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(json)));
}
19
View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen
License : MIT License
Project Creator : Adyen
public HttpWebRequest GetHttpWebRequest(string endpoint, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
{
//Add default headers
var httpWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Accept-Charset", "UTF-8");
httpWebRequest.Headers.Add("Cache-Control", "no-cache");
httpWebRequest.UserAgent = $"{config.ApplicationName} {ClientConfig.UserAgentSuffix}{ClientConfig.LibVersion}";
if (!string.IsNullOrWhiteSpace(requestOptions?.IdempotencyKey))
{
httpWebRequest.Headers.Add("Idempotency-Key", requestOptions?.IdempotencyKey);
}
//Use one of two authentication method.
if (isApiKeyRequired || !string.IsNullOrEmpty(config.XApiKey))
{
httpWebRequest.Headers.Add("x-api-key", config.XApiKey);
}
else if (!string.IsNullOrEmpty(config.Preplacedword))
{
var authString = config.Username + ":" + config.Preplacedword;
var bytes = Encoding.UTF8.GetBytes(authString);
var credentials = Convert.ToBase64String(bytes);
httpWebRequest.Headers.Add("Authorization", "Basic " + credentials);
httpWebRequest.UseDefaultCredentials = true;
}
if (config.Proxy != null)
{
httpWebRequest.Proxy = config.Proxy;
}
httpWebRequest.ServerCertificateValidationCallback = ServerCertificateValidationCallback;
return httpWebRequest;
}
19
View Source File : SaleToPoiMessageSecuredEncryptor.cs
License : MIT License
Project Creator : Adyen
License : MIT License
Project Creator : Adyen
public SaleToPoiMessageSecured Encrypt(string saleToPoiMessage, MessageHeader messageHeader,
EncryptionCredentialDetails encryptionCredentialDetails)
{
var encryptionDerivedKey = _encryptionDerivedKeyGenerator.Generate(encryptionCredentialDetails);
var saleToPoiMessageJson = saleToPoiMessage;
var saleToPoiMessageByteArray = Encoding.UTF8.GetBytes(saleToPoiMessageJson);
var ivMod = _ivModGenerator.GenerateRandomMod();
var saleToPoiMessageAesEncrypted = _aesEncryptor.Encrypt(saleToPoiMessageByteArray,
encryptionDerivedKey,
ivMod);
var saleToPoiMessageAesEncryptedHmac = _hmacSha256Wrapper.HMac(saleToPoiMessageByteArray,
encryptionDerivedKey.HmacKey);
var saleToPoiMessageSecured = new SaleToPoiRequestSecured
{
MessageHeader = messageHeader,
NexoBlob = Convert.ToBase64String(saleToPoiMessageAesEncrypted),
SecurityTrailer = new SecurityTrailer
{
KeyVersion = encryptionCredentialDetails.KeyVersion,
KeyIdentifier = encryptionCredentialDetails.KeyIdentifier,
Hmac = saleToPoiMessageAesEncryptedHmac,
Nonce = ivMod,
AdyenCryptoVersion = encryptionCredentialDetails.AdyenCryptoVersion
}
};
return saleToPoiMessageSecured;
}
19
View Source File : MusicallyApiExtensions.cs
License : MIT License
Project Creator : AeonLucid
License : MIT License
Project Creator : AeonLucid
public static IFlurlRequest WithSignParam(this IFlurlRequest request, string action, string bizType, string domain, string version = "default")
{
var requestInfo = JsonConvert.SerializeObject(new RequestInfoParam
{
ac = action,
bz = bizType,
dm = domain,
ver = "default"
});
var requestInfoEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(requestInfo));
return request.SetQueryParam("___d", requestInfoEncoded);
}
19
View Source File : MusicallyApiExtensions.cs
License : MIT License
Project Creator : AeonLucid
License : MIT License
Project Creator : AeonLucid
public static IFlurlRequest WithSignHeaders(this IFlurlRequest request, MusicallyClient api)
{
var requestId = Guid.NewGuid().ToString();
var requestInfo = JsonConvert.SerializeObject(new RequestInfo
{
Os = "android 8.0.0",
Version = "6.9.0",
SliderShowCookie = string.Empty,
XRequestId = requestId,
Url = request.Url.ToString(),
OsType = "android",
DeviceId = api.Cache.Device.DeviceId,
Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
});
var requestInfoEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(requestInfo));
var requestSignature = api.ApiSignature.GetSignature(requestInfoEncoded, api.Cache.Device.DeviceId).GetAwaiter().GetResult();
return request
.WithHeader("X-Request-ID", requestId)
.WithHeader("X-Request-Info5", requestInfoEncoded)
.WithHeader("X-Request-Sign5", requestSignature.Sign);
}
19
View Source File : AzureKeyVaultXmlEncryptor.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private async Task<EncryptedXmlInfo> EncryptAsync(XElement plaintextElement)
{
byte[] value;
using (var memoryStream = new MemoryStream())
{
plaintextElement.Save(memoryStream, SaveOptions.DisableFormatting);
value = memoryStream.ToArray();
}
using var symmetricAlgorithm = DefaultSymmetricAlgorithmFactory();
var symmetricBlockSize = symmetricAlgorithm.BlockSize / 8;
var symmetricKey = new byte[symmetricBlockSize];
var symmetricIV = new byte[symmetricBlockSize];
_randomNumberGenerator.GetBytes(symmetricKey);
_randomNumberGenerator.GetBytes(symmetricIV);
byte[] encryptedValue;
using (var encryptor = symmetricAlgorithm.CreateEncryptor(symmetricKey, symmetricIV))
{
encryptedValue = encryptor.TransformFinalBlock(value, 0, value.Length);
}
var wrappedKey = await _client.WrapKeyAsync(_keyId, DefaultKeyEncryption, symmetricKey).ConfigureAwait(false);
var element = new XElement("encryptedKey",
new XComment(" This key is encrypted with Azure KeyVault. "),
new XElement("kid", wrappedKey.Kid),
new XElement("key", Convert.ToBase64String(wrappedKey.Result)),
new XElement("iv", Convert.ToBase64String(symmetricIV)),
new XElement("value", Convert.ToBase64String(encryptedValue)));
return new EncryptedXmlInfo(element, typeof(AzureKeyVaultXmlDecryptor));
}
19
View Source File : RSA.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private static string EncryptString(string source, BigInteger d, BigInteger n)
{
int len = source.Length;
int len1 = 0;
int blockLen = 0;
if ((len % 128) == 0)
len1 = len / 128;
else
len1 = len / 128 + 1;
string block = "";
List<string> vals = new List<string>();
for (int i = 0; i < len1; i++)
{
if (len >= 128)
blockLen = 128;
else
blockLen = len;
block = source.Substring(i * 128, blockLen);
byte[] oText = System.Text.Encoding.Default.GetBytes(block);
BigInteger biText = new BigInteger(oText);
BigInteger biEnText = biText.modPow(d, n);
vals.Add(Convert.ToBase64String(biEnText.getBytes()));
len -= blockLen;
}
return string.Join("@", vals.ToArray());
}
19
View Source File : Http.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24
public static bool CheckIn()
{
try
{
#if DEFAULT_EKE
Crypto.GenRsaKeys();
Utils.GetStage GetStage = new Utils.GetStage
{
action = "staging_rsa",
pub_key = Crypto.GetPubKey(),
session_id = Utils.GetSessionId()
};
Config.SessionId = GetStage.session_id;
string SerializedData = Crypto.EncryptStage(Utils.GetStage.ToJson(GetStage));
var result = Get(SerializedData);
string final_result = Crypto.Decrypt(result);
Utils.StageResponse StageResponse = Utils.StageResponse.FromJson(final_result);
Config.tempUUID = StageResponse.uuid;
Config.Psk = Convert.ToBase64String(Crypto.RsaDecrypt(Convert.FromBase64String(StageResponse.session_key)));
#endif
Utils.CheckIn CheckIn = new Utils.CheckIn
{
action = "checkin",
ip = Utils.GetIPAddress(),
os = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", "").ToString() + " " + Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", ""),
user = Environment.UserName.ToString(),
host = Environment.MachineName.ToString(),
domain = Environment.UserDomainName.ToString(),
pid = Process.GetCurrentProcess().Id,
uuid = Config.PayloadUUID,
architecture = Utils.GetArch()
};
#if DEFAULT
string FinalSerializedData = Convert.ToBase64String(Encoding.UTF8.GetBytes(Config.PayloadUUID + Utils.CheckIn.ToJson(CheckIn)));
#elif (DEFAULT_PSK || DEFAULT_EKE)
string FinalSerializedData = Crypto.EncryptCheckin(Utils.CheckIn.ToJson(CheckIn));
#endif
var new_result = Get(FinalSerializedData);
#if (DEFAULT_PSK || DEFAULT_EKE)
string last_result = Crypto.Decrypt(new_result);
#endif
#if DEFAULT
Utils.CheckInResponse CheckInResponse = Utils.CheckInResponse.FromJson(new_result);
#elif (DEFAULT_PSK || DEFAULT_EKE)
Utils.CheckInResponse CheckInResponse = Utils.CheckInResponse.FromJson(last_result);
#endif
Config.UUID = CheckInResponse.id;
if (CheckInResponse.status == "success")
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
19
View Source File : BlobService.cs
License : MIT License
Project Creator : akasarto
License : MIT License
Project Creator : akasarto
private Uri BuildUriBase64(BlobInfo blobInfo, string label, int? width = null, int? height = null, string bgColor = null, string fgColor = null)
{
var dynamicTextImage = new DynamicTextImage(
width ?? 500,
height ?? 500,
bgColor ?? _configs.DefaultThumbBackgroundHexColor,
fgColor ?? _configs.DefaultThumbForegroundHexColor
);
using (var imageStream = dynamicTextImage.Build(label))
{
var encodedData = Convert.ToBase64String(imageStream.ToArray());
var embeddedUri = $"data:{blobInfo.ContentType};base64,{encodedData}";
return new Uri(embeddedUri, UriKind.Absolute);
}
}
19
View Source File : Argon2id.cs
License : MIT License
Project Creator : alecgn
License : MIT License
Project Creator : alecgn
public Argon2idHashResult ComputeHash(byte[] stringToComputeHashBytes, int iterations, int kBmemorySize, int degreeOfParallelism, int amountBytesToReturn,
byte[] salt = null, byte[] replacedociatedData = null, byte[] knownSecret = null)
{
try
{
salt = salt ?? CommonMethods.GenerateSalt(); // generate a 128 bits salt, if not provided
degreeOfParallelism = (degreeOfParallelism <= 0 ? Environment.ProcessorCount : degreeOfParallelism);
using (var argon2id = new Konscious.Security.Cryptography.Argon2id(stringToComputeHashBytes)
{
Salt = salt,
DegreeOfParallelism = degreeOfParallelism,
Iterations = iterations,
MemorySize = kBmemorySize,
replacedociatedData = replacedociatedData,
KnownSecret = knownSecret
})
{
var hashBytes = argon2id.GetBytes(amountBytesToReturn);
return new Argon2idHashResult()
{
Success = true,
HashBytes = hashBytes,
HashString = Convert.ToBase64String(hashBytes),
Message = MessageStrings.Hash_ComputeSuccess,
SaltBytes = salt,
Iterations = iterations,
DegreeOfParallelism = degreeOfParallelism,
KBMemorySize = kBmemorySize,
replacedociatedData = replacedociatedData,
KnownSecret = knownSecret
};
}
}
catch (Exception ex)
{
return new Argon2idHashResult()
{
Success = false,
Message = ex.ToString()
};
}
}
19
View Source File : JsonSerializer.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
private void WriteBytes(byte[] bytes)
{
#if !SILVERLIGHT
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None));
#else
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length));
#endif
}
19
View Source File : AccountUtility.cs
License : MIT License
Project Creator : allartprotocol
License : MIT License
Project Creator : allartprotocol
public static async void CreateAccount(Account account, SolanaRpcClient rpcClient, string toPublicKey = "", long ammount = 1000)
{
Keypair k = WalletKeyPair.GenerateKeyPairFromMnemonic(WalletKeyPair.GenerateNewMnemonic());
toPublicKey = k.publicKey;
RequestResult<ResponseValue<BlockHash>> blockHash = await rpcClient.GetRecentBlockHashAsync();
var tx = new TransactionBuilder().SetRecentBlockHash(blockHash.Result.Value.Blockhash).
AddInstruction(SystemProgram.CreateAccount(account.GetPublicKey, toPublicKey, ammount, (long)SystemProgram.AccountDataSize, SystemProgram.ProgramId)).Build(new List<Account>() { account, new Account(k.privateKeyByte, k.publicKeyByte) });
RequestResult<string> firstSig = await rpcClient.SendTransactionAsync(Convert.ToBase64String(tx));
}
19
View Source File : WalletBaseComponent.cs
License : MIT License
Project Creator : allartprotocol
License : MIT License
Project Creator : allartprotocol
public async void CreateAccount(Account account, string toPublicKey = "", long ammount = 1000)
{
Keypair keypair = WalletKeyPair.GenerateKeyPairFromMnemonic(WalletKeyPair.GenerateNewMnemonic());
toPublicKey = keypair.publicKey;
RequestResult<ResponseValue<BlockHash>> blockHash = await activeRpcClient.GetRecentBlockHashAsync();
var transaction = new TransactionBuilder().SetRecentBlockHash(blockHash.Result.Value.Blockhash).
AddInstruction(SystemProgram.CreateAccount(account.GetPublicKey, toPublicKey, ammount,
(long)SystemProgram.AccountDataSize, SystemProgram.ProgramId))
.Build(new List<Account>() {
account,
new Account(keypair.privateKeyByte, keypair.publicKeyByte)
});
RequestResult<string> firstSig = await activeRpcClient.SendTransactionAsync(Convert.ToBase64String(transaction));
}
19
View Source File : WalletBaseComponent.cs
License : MIT License
Project Creator : allartprotocol
License : MIT License
Project Creator : allartprotocol
public async void TransferSol(Account fromAccount, string toPublicKey, long ammount = 10000000)
{
RequestResult<ResponseValue<BlockHash>> blockHash = await activeRpcClient.GetRecentBlockHashAsync();
var transaction = new TransactionBuilder().SetRecentBlockHash(blockHash.Result.Value.Blockhash).
AddInstruction(SystemProgram.Transfer(fromAccount.GetPublicKey, toPublicKey, ammount)).Build(fromAccount);
RequestResult<string> firstSig = await activeRpcClient.SendTransactionAsync(Convert.ToBase64String(transaction));
}
19
View Source File : WalletBaseComponent.cs
License : MIT License
Project Creator : allartprotocol
License : MIT License
Project Creator : allartprotocol
public async Task<RequestResult<string>> TransferSol(string toPublicKey, long ammount = 10000000)
{
RequestResult<ResponseValue<BlockHash>> blockHash = await activeRpcClient.GetRecentBlockHashAsync();
Account fromAccount = wallet.GetAccount(0);
var transaction = new TransactionBuilder().SetRecentBlockHash(blockHash.Result.Value.Blockhash).
AddInstruction(SystemProgram.Transfer(fromAccount.GetPublicKey, toPublicKey, ammount)).Build(fromAccount);
return await activeRpcClient.SendTransactionAsync(Convert.ToBase64String(transaction));
}
19
View Source File : MessagePackSerializer.Json.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
private static void ToJsonCore(ref MessagePackReader reader, TextWriter writer, MessagePackSerializerOptions options)
{
MessagePackType type = reader.NextMessagePackType;
switch (type)
{
case MessagePackType.Integer:
if (MessagePackCode.IsSignedInteger(reader.NextCode))
{
writer.Write(reader.ReadInt64().ToString(CultureInfo.InvariantCulture));
}
else
{
writer.Write(reader.ReadUInt64().ToString(CultureInfo.InvariantCulture));
}
break;
case MessagePackType.Boolean:
writer.Write(reader.ReadBoolean() ? "true" : "false");
break;
case MessagePackType.Float:
if (reader.NextCode == MessagePackCode.Float32)
{
writer.Write(reader.ReadSingle().ToString(CultureInfo.InvariantCulture));
}
else
{
writer.Write(reader.ReadDouble().ToString(CultureInfo.InvariantCulture));
}
break;
case MessagePackType.String:
WriteJsonString(reader.ReadString(), writer);
break;
case MessagePackType.Binary:
ArraySegment<byte> segment = ByteArraySegmentFormatter.Instance.Deserialize(ref reader, DefaultOptions);
writer.Write("\"" + Convert.ToBase64String(segment.Array, segment.Offset, segment.Count) + "\"");
break;
case MessagePackType.Array:
{
int length = reader.ReadArrayHeader();
options.Security.DepthStep(ref reader);
try
{
writer.Write("[");
for (int i = 0; i < length; i++)
{
ToJsonCore(ref reader, writer, options);
if (i != length - 1)
{
writer.Write(",");
}
}
writer.Write("]");
}
finally
{
reader.Depth--;
}
return;
}
case MessagePackType.Map:
{
int length = reader.ReadMapHeader();
options.Security.DepthStep(ref reader);
try
{
writer.Write("{");
for (int i = 0; i < length; i++)
{
// write key
{
MessagePackType keyType = reader.NextMessagePackType;
if (keyType == MessagePackType.String || keyType == MessagePackType.Binary)
{
ToJsonCore(ref reader, writer, options);
}
else
{
writer.Write("\"");
ToJsonCore(ref reader, writer, options);
writer.Write("\"");
}
}
writer.Write(":");
// write body
{
ToJsonCore(ref reader, writer, options);
}
if (i != length - 1)
{
writer.Write(",");
}
}
writer.Write("}");
}
finally
{
reader.Depth--;
}
return;
}
case MessagePackType.Extension:
ExtensionHeader extHeader = reader.ReadExtensionFormatHeader();
if (extHeader.TypeCode == ReservedMessagePackExtensionTypeCode.DateTime)
{
DateTime dt = reader.ReadDateTime(extHeader);
writer.Write("\"");
writer.Write(dt.ToString("o", CultureInfo.InvariantCulture));
writer.Write("\"");
}
#if !UNITY_2018_3_OR_NEWER
else if (extHeader.TypeCode == ThisLibraryExtensionTypeCodes.TypelessFormatter)
{
// prepare type name token
var privateBuilder = new StringBuilder();
var typeNameTokenBuilder = new StringBuilder();
SequencePosition positionBeforeTypeNameRead = reader.Position;
ToJsonCore(ref reader, new StringWriter(typeNameTokenBuilder), options);
int typeNameReadSize = (int)reader.Sequence.Slice(positionBeforeTypeNameRead, reader.Position).Length;
if (extHeader.Length > typeNameReadSize)
{
// object map or array
MessagePackType typeInside = reader.NextMessagePackType;
if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map)
{
privateBuilder.Append("{");
}
ToJsonCore(ref reader, new StringWriter(privateBuilder), options);
// insert type name token to start of object map or array
if (typeInside != MessagePackType.Array)
{
typeNameTokenBuilder.Insert(0, "\"$type\":");
}
if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map)
{
privateBuilder.Append("}");
}
if (privateBuilder.Length > 2)
{
typeNameTokenBuilder.Append(",");
}
privateBuilder.Insert(1, typeNameTokenBuilder.ToString());
writer.Write(privateBuilder.ToString());
}
else
{
writer.Write("{\"$type\":\"" + typeNameTokenBuilder.ToString() + "}");
}
}
#endif
else
{
var data = reader.ReadRaw((long)extHeader.Length);
writer.Write("[");
writer.Write(extHeader.TypeCode);
writer.Write(",");
writer.Write("\"");
writer.Write(Convert.ToBase64String(data.ToArray()));
writer.Write("\"");
writer.Write("]");
}
break;
case MessagePackType.Nil:
reader.Skip();
writer.Write("null");
break;
default:
throw new MessagePackSerializationException($"code is invalid. code: {reader.NextCode} format: {MessagePackCode.ToFormatName(reader.NextCode)}");
}
}
19
View Source File : CertesWrapper.cs
License : GNU General Public License v3.0
Project Creator : aloopkin
License : GNU General Public License v3.0
Project Creator : aloopkin
private string DumpStoreContentsAsPEMBundle(StoreName name)
{
X509Store store = new X509Store(name, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var chain = "";
X509Certificate2Collection certsW = store.Certificates.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.KeyCertSign, true);
foreach (X509Certificate2 certW in certsW)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("-----BEGIN CERTIFICATE-----");
builder.AppendLine(Convert.ToBase64String(certW.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
builder.AppendLine("-----END CERTIFICATE-----");
chain += builder.ToString();
}
store.Close();
return chain;
}
19
View Source File : ByteArrayExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static string ToBase64String([NotNull] this byte[] inArray, int offset, int length, Base64FormattingOptions options)
{
return Convert.ToBase64String(inArray, offset, length, options);
}
19
View Source File : AfCodeService.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
public async Task<string> CreateAfCodeAsync(string url, AfCodeType codeType)
{
var bk = await _bkRepository.GetAsync(url);
if (bk == null)
{
return string.Empty;
}
var code = new AfCode
{
replacedle = bk.replacedle,
Url = bk.Url,
Tags = bk.Tags?.ToArray() ?? Array.Empty<string>(),
};
switch (codeType)
{
case AfCodeType.JsonBase64:
{
var json = JsonSerializer.Serialize(code);
var base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(json));
return CreateCode(base64String);
}
case AfCodeType.CompressionJsonBase64:
{
var json = JsonSerializer.Serialize(code);
var input = Encoding.UTF8.GetBytes(json).AsMemory();
var readOnlyMemory = Compress(input);
var base64String = Convert.ToBase64String(readOnlyMemory.Span);
return CreateCode(base64String);
}
case AfCodeType.Cloud:
throw new NotImplementedException();
case AfCodeType.PlainText:
{
var json = JsonSerializer.Serialize(code);
return CreateCode(json);
}
default:
throw new ArgumentOutOfRangeException(nameof(codeType), codeType, null);
}
string CreateCode(string payload)
{
return $"{Consts.AfCodeSchemaPrefix}{codeType:D}{payload}";
}
}
19
View Source File : EncryptionUtils.cs
License : Apache License 2.0
Project Creator : AndcultureCode
License : Apache License 2.0
Project Creator : AndcultureCode
public static string GenerateHash(string value, string salt, int iterationCount = 10000, ushort bits = 256)
{
if (iterationCount < 10000)
{
throw new ArgumentOutOfRangeException("Iteration count must be at least 10000");
}
ValidateBits(bits, 256);
return Convert.ToBase64String(KeyDerivation.Pbkdf2(
iterationCount: iterationCount,
numBytesRequested: bits / 8,
preplacedword: value,
prf: KeyDerivationPrf.HMACSHA1,
salt: Convert.FromBase64String(salt)
));
}
19
View Source File : ApnSender.cs
License : MIT License
Project Creator : andrei-m-code
License : MIT License
Project Creator : andrei-m-code
private string CreateJwtToken()
{
var header = JsonHelper.Serialize(new { alg = "ES256", kid = CleanP8Key(settings.P8PrivateKeyId) });
var payload = JsonHelper.Serialize(new { iss = settings.TeamId, iat = ToEpoch(DateTime.UtcNow) });
var headerBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(header));
var payloadBasae64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(payload));
var unsignedJwtData = $"{headerBase64}.{payloadBasae64}";
var unsignedJwtBytes = Encoding.UTF8.GetBytes(unsignedJwtData);
using (var dsa = AppleCryptoHelper.GetEllipticCurveAlgorithm(CleanP8Key(settings.P8PrivateKey)))
{
var signature = dsa.SignData(unsignedJwtBytes, 0, unsignedJwtBytes.Length, HashAlgorithmName.SHA256);
return $"{unsignedJwtData}.{Convert.ToBase64String(signature)}";
}
}
19
View Source File : Sprites.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
public static string SpriteToBase64(Sprite input)
{
return Convert.ToBase64String(input.texture.EncodeToPNG());
}
19
View Source File : Base64Sprites.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil
License : GNU Lesser General Public License v3.0
Project Creator : angturil
public static string SpriteToBase64(Sprite input)
{
return Convert.ToBase64String(input.texture.EncodeToJPG());
}
19
View Source File : Base64Sprites.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil
License : GNU Lesser General Public License v3.0
Project Creator : angturil
public static string Texture2DToBase64(Texture2D tex)
{
return Convert.ToBase64String(tex.EncodeToJPG());
}
19
View Source File : RSAHelperExtend.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static string RSAPrivateKeyJavaToDotNet(string privateKey)
{
RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
}
19
View Source File : RSAHelperExtend.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static string RSAPublicKeyJavaToDotNet(string publicKey)
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
}
19
View Source File : OCR.razor.cs
License : MIT License
Project Creator : AnkitSharma-007
License : MIT License
Project Creator : AnkitSharma-007
protected async Task ViewImage(InputFileChangeEventArgs e)
{
if (e.File.Size > MaxFileSize)
{
status = $"The file size is {e.File.Size} bytes, this is more than the allowed limit of {MaxFileSize} bytes.";
return;
}
else if (!e.File.ContentType.Contains("image"))
{
status = "Please uplaod a valid image file";
return;
}
else
{
using var reader = new StreamReader(e.File.OpenReadStream(MaxFileSize));
var format = "image/jpeg";
var imageFile = await e.File.RequestImageFileAsync(format, 640, 480);
using var fileStream = imageFile.OpenReadStream(MaxFileSize);
using var memoryStream = new MemoryStream();
await fileStream.CopyToAsync(memoryStream);
imageFileBytes = memoryStream.ToArray();
imagePreview = string.Concat("data:image/png;base64,", Convert.ToBase64String(memoryStream.ToArray()));
status = DefaultStatus;
}
}
19
View Source File : ByteBuffer.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
public string ToBase64()
{
return Convert.ToBase64String(_buffer.Span, Base64FormattingOptions.None);
}
19
View Source File : MessageMetadataExtensions.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public static void SetKey(this Metadata metadata, byte[]? key)
{
if (key is null)
return;
metadata.ParreplacedionKey = Convert.ToBase64String(key);
metadata.ParreplacedionKeyB64Encoded = true;
}
19
View Source File : HttpClientExtension.cs
License : MIT License
Project Creator : appsonsf
License : MIT License
Project Creator : appsonsf
public static void AddUserClaimsHeader(this HttpClient client, HttpContext context)
{
if (!context.User.Idenreplacedy.IsAuthenticated)
throw new InvalidOperationException("user do not Authenticated!");
var claimsDic = new Dictionary<string, string>();
foreach (var userClaim in context.User.Claims)
{
if (!claimsDic.ContainsKey(userClaim.Type))
claimsDic.Add(userClaim.Type, userClaim.Value);
}
var claimsString = JsonConvert.SerializeObject(claimsDic);
var claimsBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(claimsString));
if (client.DefaultRequestHeaders.Contains(UserClaimsHeaderName))
client.DefaultRequestHeaders.Remove(UserClaimsHeaderName);
client.DefaultRequestHeaders.Add(UserClaimsHeaderName, claimsBase64);
}
19
View Source File : BitsOfBinary.cs
License : MIT License
Project Creator : araditc
License : MIT License
Project Creator : araditc
public bool Input(Iq stanza) {
if (stanza.Type != IqType.Get)
return false;
var e = stanza.Data["data"];
if (e == null || e.NamespaceURI != "urn:xmpp:bob")
return false;
string cid = e.GetAttribute("cid");
if (cache.ContainsKey(cid)) {
BobData b = cache[cid];
var data = Xml.Element("data", "urn:xmpp:bob").Attr("cid", cid)
.Attr("type", b.Type)
.Text(Convert.ToBase64String(b.Data));
im.IqResult(stanza, data);
} else {
// If we don't have the item, return an 'item not found' error.
im.IqError(stanza, ErrorType.Cancel, ErrorCondition.ItemNotFound);
}
// We took care of this IQ request, so intercept it and don't preplaced it
// on to other handlers.
return true;
}
19
View Source File : TrackDialog.cs
License : MIT License
Project Creator : arafattehsin
License : MIT License
Project Creator : arafattehsin
private static Attachment GetInlineAttachment()
{
var imagePath = Path.Combine(Environment.CurrentDirectory, @"replacedets\food-track.PNG");
var imageData = Convert.ToBase64String(File.ReadAllBytes(imagePath));
return new Attachment
{
Name = @"replacedets\food-track.PNG",
ContentType = "image/png",
ContentUrl = $"data:image/png;base64,{imageData}",
};
}
See More Examples