Here are the examples of the csharp api System.BitConverter.GetBytes(long) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
634 Examples
19
Source : GmicPipeServer.cs
with GNU General Public License v3.0
from 0xC0000054
with GNU General Public License v3.0
from 0xC0000054
private void WaitForConnectionCallback(IAsyncResult result)
{
if (server == null)
{
return;
}
try
{
server.EndWaitForConnection(result);
}
catch (ObjectDisposedException)
{
return;
}
byte[] replySizeBuffer = new byte[sizeof(int)];
server.ProperRead(replySizeBuffer, 0, replySizeBuffer.Length);
int messageLength = BitConverter.ToInt32(replySizeBuffer, 0);
byte[] messageBytes = new byte[messageLength];
server.ProperRead(messageBytes, 0, messageLength);
List<string> parameters = DecodeMessageBuffer(messageBytes);
if (!TryGetValue(parameters[0], "command=", out string command))
{
throw new InvalidOperationException("The first item must be a command.");
}
if (command.Equals("gmic_qt_get_max_layer_size", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the input mode.");
}
InputMode inputMode = ParseInputMode(mode);
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_get_max_layer_size' received. mode=" + inputMode.ToString());
#endif
string reply = GetMaxLayerSize(inputMode);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_get_cropped_images", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the input mode.");
}
if (!TryGetValue(parameters[2], "croprect=", out string packedCropRect))
{
throw new InvalidOperationException("The third item must be the crop rectangle.");
}
InputMode inputMode = ParseInputMode(mode);
RectangleF cropRect = GetCropRectangle(packedCropRect);
#if DEBUG
System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
"'gmic_qt_get_cropped_images' received. mode={0}, cropRect={1}",
inputMode.ToString(), cropRect.ToString()));
#endif
string reply = PrepareCroppedLayers(inputMode, cropRect);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_output_images", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the output mode.");
}
OutputMode outputMode = ParseOutputMode(mode);
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_output_images' received. mode=" + outputMode.ToString());
#endif
List<string> outputLayers = parameters.GetRange(2, parameters.Count - 2);
string reply = ProcessOutputImage(outputLayers, outputMode);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_release_shared_memory", StringComparison.Ordinal))
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_release_shared_memory' received.");
#endif
for (int i = 0; i < memoryMappedFiles.Count; i++)
{
memoryMappedFiles[i].Dispose();
}
memoryMappedFiles.Clear();
SendMessage(server, "done");
}
else if (command.Equals("gmic_qt_get_max_layer_data_length", StringComparison.Ordinal))
{
// This command is used to prevent images larger than 4GB from being used on a 32-bit version of G'MIC.
// Attempting to map an image that size into memory would cause an integer overflow when casting a 64-bit
// integer to the unsigned 32-bit size_t type.
long maxDataLength = 0;
foreach (GmicLayer layer in layers)
{
maxDataLength = Math.Max(maxDataLength, layer.Surface.Scan0.Length);
}
server.Write(BitConverter.GetBytes(sizeof(long)), 0, 4);
server.Write(BitConverter.GetBytes(maxDataLength), 0, 8);
}
// Wait for the acknowledgment that the client is done reading.
if (server.IsConnected)
{
byte[] doneMessageBuffer = new byte[4];
int bytesRead = 0;
int bytesToRead = doneMessageBuffer.Length;
do
{
int n = server.Read(doneMessageBuffer, bytesRead, bytesToRead);
bytesRead += n;
bytesToRead -= n;
} while (bytesToRead > 0 && server.IsConnected);
}
// Start a new server and wait for the next connection.
server.Dispose();
server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
server.BeginWaitForConnection(WaitForConnectionCallback, null);
}
19
Source : SequentialGuidGenerator.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public Guid Create(SequentialGuidType guidType)
{
lock (_lock)
{
var randomBytes = new byte[10];
_rng.GetBytes(randomBytes);
var timestamp = DateTime.UtcNow.Ticks / 10000L;
var timestampBytes = BitConverter.GetBytes(timestamp);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(timestampBytes);
}
var guidBytes = new byte[16];
switch (guidType)
{
case SequentialGuidType.Sequentialreplacedtring:
case SequentialGuidType.SequentialAsBinary:
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);
Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10);
// If formatting as a string, we have to reverse the order
// of the Data1 and Data2 blocks on little-endian systems.
if (guidType == SequentialGuidType.Sequentialreplacedtring && BitConverter.IsLittleEndian)
{
Array.Reverse(guidBytes, 0, 4);
Array.Reverse(guidBytes, 4, 2);
}
break;
case SequentialGuidType.SequentialAtEnd:
Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
break;
}
return new Guid(guidBytes);
}
}
19
Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
public static void SerializeLong(List<byte> byteList, long data)
{
byteList.AddRange(BitConverter.GetBytes(data));
}
19
Source : NTLM.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
public byte[] ProcessChallenge(byte[] Challenge)
{
byte[] bytes;
RdpPacket packet = new RdpPacket();
this.m_ChallengeMsg = Challenge;
packet.Write(Challenge, 0, Challenge.Length);
packet.Position = 0L;
long position = packet.Position;
if (packet.ReadString(8) != "NTLMSSP\0")
{
throw new Exception("Invalid negotiation token!");
}
if (packet.ReadLittleEndian32() != 2)
{
throw new Exception("Expected challenge!");
}
int count = packet.ReadLittleEndian16();
packet.ReadLittleEndian16();
int num4 = packet.ReadLittleEndian32();
uint flags = (uint) packet.ReadLittleEndian32();
DumpFlags(flags);
byte[] buffer = new byte[8];
packet.Read(buffer, 0, 8);
DumpHex(buffer, buffer.Length, "Server Challenge");
byte[] buffer2 = new byte[8];
packet.Read(buffer2, 0, 8);
int num5 = packet.ReadLittleEndian16();
packet.ReadLittleEndian16();
int num6 = packet.ReadLittleEndian32();
if ((flags & 0x2000000) != 0)
{
byte[] buffer3 = new byte[8];
packet.Read(buffer3, 0, 8);
}
if ((flags & 0x20000000) == 0)
{
throw new Exception("Strong Encryption not supported by server");
}
byte[] buffer4 = null;
if (count > 0)
{
buffer4 = new byte[count];
packet.Position = position + num4;
packet.Read(buffer4, 0, count);
Encoding.Unicode.GetString(buffer4, 0, buffer4.Length);
}
AV_PAIRS av_pairs = new AV_PAIRS();
byte[] buffer5 = null;
if (num5 <= 0)
{
throw new Exception("No TargetInfo!");
}
packet.Position = position + num6;
buffer5 = new byte[num5];
packet.Read(buffer5, 0, num5);
packet = new RdpPacket();
packet.Write(buffer5, 0, buffer5.Length);
packet.Position = 0L;
av_pairs.Parse(packet);
buffer5 = av_pairs.Serialise();
byte[] data = nTOWFv2(this.m_sDomain, this.m_sUsername, this.m_sPreplacedword);
if (Network.Logger != null)
{
if (Network.Logger.Reading)
{
data = this.m_Socket.GetBlob(PacketLogger.PacketType.NTLM_ResponseKeyNT);
}
else
{
this.m_Socket.AddBlob(PacketLogger.PacketType.NTLM_ResponseKeyNT, data);
}
}
byte[] blob = new byte[8];
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
provider.GetBytes(blob);
if (Network.Logger != null)
{
if (Network.Logger.Reading)
{
blob = this.m_Socket.GetBlob(PacketLogger.PacketType.NTLM_ClientChallenge);
}
else
{
this.m_Socket.AddBlob(PacketLogger.PacketType.NTLM_ClientChallenge, blob);
}
}
DumpHex(blob, blob.Length, "Client Challenge");
byte[] buffer8 = getLMv2Response(data, buffer, blob);
DumpHex(buffer8, buffer8.Length, "LM Response");
if (this.m_bNTLMv2)
{
Array.Clear(buffer8, 0, buffer8.Length);
}
bool bGenerateMIC = false;
if ((av_pairs.Timestamp.length <= 0) || !this.m_bNTLMv2)
{
bytes = BitConverter.GetBytes(DateTime.UtcNow.ToFileTimeUtc());
}
else
{
bytes = av_pairs.Timestamp.value;
bGenerateMIC = true;
av_pairs.ProcessForNTLMv2();
buffer5 = av_pairs.Serialise();
}
DumpHex(buffer5, buffer5.Length, "targetinfo");
byte[] keyExchangeKey = null;
byte[] buffer11 = getNTLMv2Response(data, buffer, blob, bytes, buffer5, out keyExchangeKey);
DumpHex(buffer11, buffer11.Length, "NTLMv2 Response");
if (Network.Logger != null)
{
if (Network.Logger.Reading)
{
keyExchangeKey = this.m_Socket.GetBlob(PacketLogger.PacketType.NTLM_KeyExchangeKey);
}
else
{
this.m_Socket.AddBlob(PacketLogger.PacketType.NTLM_KeyExchangeKey, keyExchangeKey);
}
}
byte[] encryptedRandomSessionKey = null;
byte[] buffer13 = null;
buffer13 = new byte[0x10];
provider.GetBytes(buffer13);
if (Network.Logger != null)
{
if (Network.Logger.Reading)
{
buffer13 = this.m_Socket.GetBlob(PacketLogger.PacketType.NTLM_ExportedSessionKey);
}
else
{
this.m_Socket.AddBlob(PacketLogger.PacketType.NTLM_ExportedSessionKey, buffer13);
}
}
encryptedRandomSessionKey = new byte[0x10];
RC4 rc = new RC4();
rc.engineInitEncrypt(keyExchangeKey);
encryptedRandomSessionKey = rc.crypt(buffer13);
if ((flags & 0x40000000) == 0)
{
encryptedRandomSessionKey = new byte[0];
buffer13 = keyExchangeKey;
}
this.InitSignKeys(buffer13);
return this.Authenticate(buffer8, buffer11, this.m_sDomain, this.m_sUsername, this.m_sWorkstation, encryptedRandomSessionKey, buffer13, bGenerateMIC);
}
19
Source : MD5.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
internal static byte[] GetHashFinalBlock(byte[] input, int ibStart, int cbSize, ABCDStruct ABCD, long len)
{
byte[] destinationArray = new byte[0x40];
byte[] bytes = BitConverter.GetBytes(len);
Array.Copy(input, ibStart, destinationArray, 0, cbSize);
destinationArray[cbSize] = 0x80;
if (cbSize <= 0x38)
{
Array.Copy(bytes, 0, destinationArray, 0x38, 8);
GetHashBlock(destinationArray, ref ABCD, 0);
}
else
{
GetHashBlock(destinationArray, ref ABCD, 0);
destinationArray = new byte[0x40];
Array.Copy(bytes, 0, destinationArray, 0x38, 8);
GetHashBlock(destinationArray, ref ABCD, 0);
}
byte[] buffer3 = new byte[0x10];
Array.Copy(BitConverter.GetBytes(ABCD.A), 0, buffer3, 0, 4);
Array.Copy(BitConverter.GetBytes(ABCD.B), 0, buffer3, 4, 4);
Array.Copy(BitConverter.GetBytes(ABCD.C), 0, buffer3, 8, 4);
Array.Copy(BitConverter.GetBytes(ABCD.D), 0, buffer3, 12, 4);
return buffer3;
}
19
Source : ASN1.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
protected static void UpdateLength(RdpPacket packet, string Identifier)
{
Fixup fixup = m_Fixup[Identifier];
m_Fixup.Remove(Identifier);
long position = packet.Position;
if (fixup.Length != -1)
{
long num2 = packet.Position - fixup.Offset;
if (num2 != fixup.Length)
{
throw new Exception("DER Tag length invalid");
}
}
else
{
long num3 = packet.Position - (fixup.Offset + 1L);
byte[] bytes = BitConverter.GetBytes(num3);
packet.Position = fixup.Offset;
if (num3 > 0xffffffL)
{
packet.WriteByte(0x84);
packet.InsertByte(bytes[3]);
position += 1L;
packet.InsertByte(bytes[2]);
position += 1L;
packet.InsertByte(bytes[1]);
position += 1L;
packet.InsertByte(bytes[0]);
position += 1L;
}
else if (num3 > 0xffffL)
{
packet.WriteByte(0x83);
packet.InsertByte(bytes[2]);
position += 1L;
packet.InsertByte(bytes[1]);
position += 1L;
packet.InsertByte(bytes[0]);
position += 1L;
}
else if (num3 > 0xffL)
{
packet.WriteByte(130);
packet.InsertByte(bytes[1]);
position += 1L;
packet.InsertByte(bytes[0]);
position += 1L;
}
else if (num3 > 0x7fL)
{
packet.WriteByte(0x81);
packet.InsertByte(bytes[0]);
position += 1L;
}
else
{
packet.WriteByte(bytes[0]);
}
packet.Position = position;
}
}
19
Source : Helpers.cs
with MIT License
from 71
with MIT License
from 71
public static byte[] GetJmpBytes(IntPtr destination)
{
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.Arm:
{
// LDR PC, [PC, #-4]
// $addr
byte[] result = new byte[8];
result[0] = 0x04;
result[1] = 0xF0;
result[2] = 0x1F;
result[3] = 0xE5;
BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 4);
return result;
}
case Architecture.Arm64:
{
// LDR PC, [PC, #-4]
// $addr
byte[] result = new byte[12];
result[0] = 0x04;
result[1] = 0xF0;
result[2] = 0x1F;
result[3] = 0xE5;
BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 4);
return result;
}
case Architecture.X64:
{
// movabs rax,$addr
// jmp rax
byte[] result = new byte[12];
result[0] = 0x48;
result[1] = 0xB8;
result[10] = 0xFF;
result[11] = 0xE0;
BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 2);
return result;
}
case Architecture.X86:
{
// push $addr
// ret
byte[] result = new byte[6];
result[0] = 0x68;
result[5] = 0xC3;
BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 1);
return result;
}
default:
throw UnsupportedArchitecture;
}
}
19
Source : Ryder.Lightweight.cs
with MIT License
from 71
with MIT License
from 71
public static byte[] GetJmpBytes(IntPtr destination)
{
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.Arm:
{
// LDR PC, [PC, #-4]
// $addr
byte[] result = new byte[8];
result[0] = 0x04;
result[1] = 0xF0;
result[2] = 0x1F;
result[3] = 0xE5;
BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 4);
return result;
}
case Architecture.Arm64:
{
// LDR PC, [PC, #-4]
// $addr
byte[] result = new byte[12];
result[0] = 0x04;
result[1] = 0xF0;
result[2] = 0x1F;
result[3] = 0xE5;
BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 4);
return result;
}
case Architecture.X64:
{
// movabs rax,$addr
// jmp rax
byte[] result = new byte[12];
result[0] = 0x48;
result[1] = 0xB8;
result[10] = 0xFF;
result[11] = 0xE0;
BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 2);
return result;
}
case Architecture.X86:
{
// push $addr
// ret
byte[] result = new byte[6];
result[0] = 0x68;
result[5] = 0xC3;
BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 1);
return result;
}
default:
throw UnsupportedArchitecture;
}
}
19
Source : Store.cs
with MIT License
from abdullin
with MIT License
from abdullin
public void SetCounter(long id) {
using (var tx = _le.BeginTransaction()) {
var key = FdbTuple.Create((byte) Tables.SysCounter);
if (id == 0) {
tx.Delete(_ld, key.GetBytes());
} else {
tx.Put(_ld, key.GetBytes(), BitConverter.GetBytes(id));
}
tx.Commit();
}
}
19
Source : Serializer.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public static byte[] FromDateTimeOffset(DateTimeOffset data, DateTimeOffset? timestamp = null)
=> BitConverter.GetBytes(data.ToFileTime()).AppendTimestamp(timestamp);
19
Source : Serializer.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public static byte[] FromTimeSpan(TimeSpan data, DateTimeOffset? timestamp = null)
=> BitConverter.GetBytes(data.Ticks).AppendTimestamp(timestamp);
19
Source : Serializer.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public static byte[] FromInt64(long data, DateTimeOffset? timestamp = null)
=> BitConverter.GetBytes(data).AppendTimestamp(timestamp);
19
Source : Serializer.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
private static byte[] FromDateTimeOffset(DateTimeOffset data)
=> BitConverter.GetBytes(data.ToFileTime());
19
Source : BytesWriter.cs
with MIT License
from adrenak
with MIT License
from adrenak
public BytesWriter WriteLong(Int64 value) {
var bytes = BitConverter.GetBytes(value);
EndianUtility.EndianCorrection(bytes);
WriteBytes(bytes);
return this;
}
19
Source : Extensions.cs
with MIT License
from adrenak
with MIT License
from adrenak
public static byte[] GetBytes(this long value) {
return BitConverter.GetBytes(value);
}
19
Source : NumericExtensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static byte[] ToBytes(this long n, bool bigEndian = true)
{
var bytes = BitConverter.GetBytes(n);
return GetBytesWithEndian(bytes, bigEndian);
}
19
Source : BlockTemplateMinerServiceTests.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
[Fact]
public async Task MinAsync_Success_Test()
{
var chain = await _chainService.GetChainAsync();
var hash = chain.BestChainHash;
var height = chain.BestChainHeight;
var blockHeader = await _minerService.CreateTemplateCacheAsync(hash, height, TimestampHelper.GetUtcNow(),
TimestampHelper.DurationFromMinutes(1));
var byteString = blockHeader.ToByteString();
var bytes = byteString.ToByteArray();
//Send Bytes to Client
#region Client Side
//Client side, you can search nonce and replace it
var nonce = BitConverter.GetBytes(long.MaxValue - 1);
var start = bytes.Find(nonce);
start.ShouldBeGreaterThan(0);
for (int i = 0; i < nonce.Length; i++)
{
bytes[start + i] = 9; //change nonce
}
bytes.Find(nonce).ShouldBe(-1);
var newHeader = BlockHeader.Parser.ParseFrom(ByteString.CopyFrom(bytes));
//Test mining method
newHeader.GetHash().ShouldBe(HashHelper.ComputeFrom(newHeader.ToByteArray()));
newHeader.GetHash().ShouldBe(HashHelper.ComputeFrom(bytes));
//Start mining
Random r = new Random();
while (HashHelper.ComputeFrom(bytes).Value[0] != 0)
{
//find first hash byte is 0
for (int i = 0; i < nonce.Length; i++)
{
bytes[start + i] = (byte) r.Next(); //change nonce, very slow, just for demo
}
}
#endregion
//Send bytes to Server
newHeader = BlockHeader.Parser.ParseFrom(ByteString.CopyFrom(bytes));
var newHeaderHash = newHeader.GetHash();
newHeaderHash.Value[0].ShouldBe((byte) 0); // first byte should be zero
var block = await _minerService.ChangeTemplateCacheBlockHeaderAndClearCacheAsync(newHeader);
block.GetHash().ShouldBe(newHeader.GetHash()); // check new block's header
block.Header.Signature.ShouldBeEmpty(); // check signature
}
19
Source : KernelTestAElfModule.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public override void ConfigureServices(ServiceConfigurationContext context)
{
var services = context.Services;
var transactionList = new List<Transaction>
{
new Transaction
{
From = SampleAddress.AddressList[0],
To = SampleAddress.AddressList[1],
MethodName = "GenerateConsensusTransactions"
}
};
services.AddTransient(o =>
{
var mockService = new Mock<ISystemTransactionGenerator>();
mockService.Setup(m =>
m.GenerateTransactionsAsync(It.IsAny<Address>(), It.IsAny<long>(), It.IsAny<Hash>()));
return mockService.Object;
});
services.AddTransient(o =>
{
var mockService = new Mock<ISystemTransactionGenerationService>();
mockService.Setup(m =>
m.GenerateSystemTransactionsAsync(It.IsAny<Address>(), It.IsAny<long>(), It.IsAny<Hash>()))
.Returns(Task.FromResult(transactionList));
return mockService.Object;
});
services.AddTransient<IBlockExecutingService, TestBlockExecutingService>();
//For BlockExtraDataService testing.
services.AddTransient(
builder =>
{
var dataProvider = new Mock<IBlockExtraDataProvider>();
ByteString bs = ByteString.CopyFrom(BitConverter.GetBytes(long.MaxValue - 1));
dataProvider.Setup(m => m.GetBlockHeaderExtraDataAsync(It.IsAny<BlockHeader>()))
.Returns(Task.FromResult(bs));
dataProvider.Setup(d => d.BlockHeaderExtraDataKey).Returns("TestExtraDataKey");
return dataProvider.Object;
});
services.AddTransient(provider =>
{
var mockService = new Mock<ISmartContractAddressService>();
return mockService.Object;
});
services.AddTransient<BlockValidationProvider>();
}
19
Source : ProcessExtensions.cs
with GNU General Public License v3.0
from aglab2
with GNU General Public License v3.0
from aglab2
private static bool WriteJumpOrCall(Process process, IntPtr addr, IntPtr dest, bool call)
{
var x64 = process.Is64Bit();
int jmpLen = x64 ? 12 : 5;
var instruction = new List<byte>(jmpLen);
if (x64)
{
instruction.AddRange(new byte[] { 0x48, 0xB8 }); // mov rax immediate
instruction.AddRange(BitConverter.GetBytes((long)dest));
instruction.AddRange(new byte[] { 0xFF, call ? (byte)0xD0 : (byte)0xE0 }); // jmp/call rax
}
else
{
int offset = unchecked((int)dest - (int)(addr + jmpLen));
instruction.AddRange(new byte[] { call ? (byte)0xE8 : (byte)0xE9 }); // jmp/call immediate
instruction.AddRange(BitConverter.GetBytes(offset));
}
MemPageProtect oldProtect;
process.VirtualProtect(addr, jmpLen, MemPageProtect.PAGE_EXECUTE_READWRITE, out oldProtect);
bool success = process.WriteBytes(addr, instruction.ToArray());
process.VirtualProtect(addr, jmpLen, oldProtect);
return success;
}
19
Source : GuidHelper.cs
with MIT License
from aishang2015
with MIT License
from aishang2015
public Guid Next()
{
var guidBytes = Guid.NewGuid().ToByteArray();
var counterBytes = BitConverter.GetBytes(Interlocked.Increment(ref _counter));
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(counterBytes);
}
guidBytes[08] = counterBytes[1];
guidBytes[09] = counterBytes[0];
guidBytes[10] = counterBytes[7];
guidBytes[11] = counterBytes[6];
guidBytes[12] = counterBytes[5];
guidBytes[13] = counterBytes[4];
guidBytes[14] = counterBytes[3];
guidBytes[15] = counterBytes[2];
return new Guid(guidBytes);
}
19
Source : HijackThread.cs
with MIT License
from Akaion
with MIT License
from Akaion
private static byte[] replacedembleShellcode(CallDescriptor callDescriptor, IntPtr completionFlagBuffer)
{
var shellcode = new List<byte>();
if (callDescriptor.IsWow64Call)
{
// pushf
shellcode.Add(0x9C);
// pusha
shellcode.Add(0x60);
// replacedemble the function parameters
if (callDescriptor.CallingConvention == CallingConvention.FastCall)
{
Parameterreplacedembler.replacedembleFastCallParameters(callDescriptor, ref shellcode);
}
else
{
Parameterreplacedembler.replacedembleStdCallParameters(callDescriptor, ref shellcode);
}
// mov eax, functionAddress
shellcode.Add(0xB8);
shellcode.AddRange(BitConverter.GetBytes((int) callDescriptor.FunctionAddress));
// call eax
shellcode.AddRange(new byte[] {0xFF, 0xD0});
if (callDescriptor.ReturnAddress != IntPtr.Zero)
{
// mov [returnAddress], eax
shellcode.Add(0xA3);
shellcode.AddRange(BitConverter.GetBytes((int) callDescriptor.ReturnAddress));
}
// mov BYTE PTR [completionFlagBuffer], 0x01
shellcode.AddRange(new byte[] {0xC6, 0x05});
shellcode.AddRange(BitConverter.GetBytes((int) completionFlagBuffer));
shellcode.Add(0x01);
// popa
shellcode.Add(0x61);
// popf
shellcode.Add(0x9D);
// ret
shellcode.Add(0xC3);
}
else
{
// pushf
shellcode.Add(0x9C);
// push rax
shellcode.Add(0x50);
// push rbx
shellcode.Add(0x53);
// push rcx
shellcode.Add(0x51);
// push rdx
shellcode.Add(0x52);
// push r8
shellcode.AddRange(new byte[] {0x41, 0x50});
// push r9
shellcode.AddRange(new byte[] {0x41, 0x51});
// push r10
shellcode.AddRange(new byte[] {0x41, 0x52});
// push r11
shellcode.AddRange(new byte[] {0x41, 0x53});
// replacedemble the function parameters
Parameterreplacedembler.replacedembleFastCallParameters(callDescriptor, ref shellcode);
// mov rax, functionAddress
shellcode.AddRange(new byte[] {0x48, 0xB8});
shellcode.AddRange(BitConverter.GetBytes((long) callDescriptor.FunctionAddress));
// sub rsp, 0x28
shellcode.AddRange(new byte[] {0x48, 0x83, 0xEC, 0x28});
// call rax
shellcode.AddRange(new byte[] {0xFF, 0xD0});
// add rsp, 0x28
shellcode.AddRange(new byte[] {0x48, 0x83, 0xC4, 0x28});
if (callDescriptor.ReturnAddress != IntPtr.Zero)
{
// mov [returnAddress], rax
shellcode.AddRange(new byte[] {0x48, 0xA3});
shellcode.AddRange(BitConverter.GetBytes((long) callDescriptor.ReturnAddress));
}
// mov rax, completionFlagBuffer
shellcode.AddRange(new byte[] {0x48, 0xB8});
shellcode.AddRange(BitConverter.GetBytes((long) completionFlagBuffer));
// mov BYTE PTR [rax], 0x01
shellcode.AddRange(new byte[] {0xC6, 0x00, 0x01});
// pop r11
shellcode.AddRange(new byte[] {0x41, 0x5B});
// pop r10
shellcode.AddRange(new byte[] {0x41, 0x5A});
// pop r9
shellcode.AddRange(new byte[] {0x41, 0x59});
// pop r8
shellcode.AddRange(new byte[] {0x41, 0x58});
// pop rdx
shellcode.Add(0x5A);
// pop rcx
shellcode.Add(0x59);
// pop rbx
shellcode.Add(0x5B);
// pop rax
shellcode.Add(0x58);
// popf
shellcode.Add(0x9D);
// ret
shellcode.Add(0xC3);
}
return shellcode.ToArray();
}
19
Source : MethodDetour.cs
with MIT License
from Akaion
with MIT License
from Akaion
private void PrepareDetour()
{
// Ensure both methods are JIT compiled
RuntimeHelpers.PrepareMethod(_originalMethodHandle);
RuntimeHelpers.PrepareMethod(_targetMethodHandle);
// Construct the shellcode needed to detour the method
var shellcode = new List<byte>();
if (Environment.Is64BitProcess)
{
// mov rax, targetMethodAddress
shellcode.AddRange(new byte[] {0x48, 0xB8});
shellcode.AddRange(BitConverter.GetBytes((long) _targetMethodHandle.GetFunctionPointer()));
// jmp rax
shellcode.AddRange(new byte[] {0xFF, 0xE0});
}
else
{
// mov eax, targetMethodAddress
shellcode.Add(0xB8);
shellcode.AddRange(BitConverter.GetBytes((int) _targetMethodHandle.GetFunctionPointer()));
// jmp eax
shellcode.AddRange(new byte[] {0xFF, 0xE0});
}
_detourBytes = shellcode.ToArray();
// Save the bytes of the original method
_originalMethodBytes = new byte[_detourBytes.Length];
Marshal.Copy(_originalMethodHandle.GetFunctionPointer(), _originalMethodBytes, 0, _detourBytes.Length);
}
19
Source : CreateThread.cs
with MIT License
from Akaion
with MIT License
from Akaion
private static byte[] replacedembleShellcode(CallDescriptor callDescriptor)
{
var shellcode = new List<byte>();
if (callDescriptor.IsWow64Call)
{
// replacedemble the function parameters
if (callDescriptor.CallingConvention == CallingConvention.FastCall)
{
Parameterreplacedembler.replacedembleFastCallParameters(callDescriptor, ref shellcode);
}
else
{
Parameterreplacedembler.replacedembleStdCallParameters(callDescriptor, ref shellcode);
}
// mov eax, functionAddress
shellcode.Add(0xB8);
shellcode.AddRange(BitConverter.GetBytes((int) callDescriptor.FunctionAddress));
// call eax
shellcode.AddRange(new byte[] {0xFF, 0xD0});
if (callDescriptor.ReturnAddress != IntPtr.Zero)
{
// mov [returnAddress], eax
shellcode.Add(0xA3);
shellcode.AddRange(BitConverter.GetBytes((int) callDescriptor.ReturnAddress));
}
// xor eax, eax
shellcode.AddRange(new byte[] {0x33, 0xC0});
// ret
shellcode.Add(0xC3);
}
else
{
// replacedemble the function parameters
Parameterreplacedembler.replacedembleFastCallParameters(callDescriptor, ref shellcode);
// mov rax, functionAddress
shellcode.AddRange(new byte[] {0x48, 0xB8});
shellcode.AddRange(BitConverter.GetBytes((long) callDescriptor.FunctionAddress));
// sub rsp, 0x28
shellcode.AddRange(new byte[] {0x48, 0x83, 0xEC, 0x28});
// call rax
shellcode.AddRange(new byte[] {0xFF, 0xD0});
// add rsp, 0x28
shellcode.AddRange(new byte[] {0x48, 0x83, 0xC4, 0x28});
if (callDescriptor.ReturnAddress != IntPtr.Zero)
{
// mov [returnAddress], rax
shellcode.AddRange(new byte[] {0x48, 0xA3});
shellcode.AddRange(BitConverter.GetBytes((long) callDescriptor.ReturnAddress));
}
// xor eax, eax
shellcode.AddRange(new byte[] {0x31, 0xC0});
// ret
shellcode.Add(0xC3);
}
return shellcode.ToArray();
}
19
Source : BitStream.cs
with MIT License
from Alexander-Scott
with MIT License
from Alexander-Scott
public void WriteInt64(long value)
{
WriteBytes(BitConverter.GetBytes(value), 64);
}
19
Source : BitStream.cs
with MIT License
from Alexander-Scott
with MIT License
from Alexander-Scott
public void WriteInt48(Int48 value)
{
WriteBytes(BitConverter.GetBytes((long) value), 48);
}
19
Source : WebassemblyModule.cs
with MIT License
from alexanderkyte
with MIT License
from alexanderkyte
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void Store64BitFrom64 (long input, int offset) {
var bytes = BitConverter.GetBytes (input);
this.memory [offset + 0] = bytes [0];
this.memory [offset + 1] = bytes [1];
this.memory [offset + 2] = bytes [2];
this.memory [offset + 3] = bytes [3];
this.memory [offset + 4] = bytes [4];
this.memory [offset + 5] = bytes [5];
this.memory [offset + 6] = bytes [6];
this.memory [offset + 7] = bytes [7];
}
19
Source : WebassemblyModule.cs
with MIT License
from alexanderkyte
with MIT License
from alexanderkyte
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void Store32BitFrom32 (long input, int offset) {
var bytes = BitConverter.GetBytes (input);
this.memory [offset + 0] = bytes [0];
this.memory [offset + 1] = bytes [1];
this.memory [offset + 2] = bytes [2];
this.memory [offset + 3] = bytes [3];
}
19
Source : WebassemblyModule.cs
with MIT License
from alexanderkyte
with MIT License
from alexanderkyte
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void Store16BitFrom64 (long input, int offset) {
var bytes = BitConverter.GetBytes (input);
this.memory [offset + 0] = bytes [0];
this.memory [offset + 1] = bytes [1];
}
19
Source : WebassemblyModule.cs
with MIT License
from alexanderkyte
with MIT License
from alexanderkyte
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void Store8BitFrom64 (long input, int offset) {
var bytes = BitConverter.GetBytes (input);
this.memory [offset + 0] = bytes [0];
}
19
Source : Message.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
public static void Write(byte[] buffer, ref int offset, long value)
{
buffer.CannotBeNullOrEmpty();
offset.MustBeGreaterThanOrEqualTo(0);
offset.MustBeLessThanOrEqualTo(buffer.Length - LongLength);
Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value)), 0, buffer, ref offset, LongLength);
}
19
Source : LongExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static byte[] GetBytes(this long value)
{
return BitConverter.GetBytes(value);
}
19
Source : Loader.cs
with BSD 3-Clause "New" or "Revised" License
from ambray
with BSD 3-Clause "New" or "Revised" License
from ambray
public KeyValuePair<int, IntPtr> BuildEntryPatch(IntPtr dest)
{
int i = 0;
IntPtr ptr;
ptr = Marshal.AllocHGlobal((IntPtr)PatchSize);
unsafe
{
var p = (byte*)ptr;
byte[] tmp = null;
if (IntPtr.Size == 4)
{
p[i] = 0xb8; // mov eax, <imm4>
i++;
var val = (Int32)dest;
tmp = BitConverter.GetBytes(val);
}
else
{
p[i] = 0x48; // rex
i++;
p[i] = 0xb8; // mov rax, <imm8>
i++;
var val = (Int64)dest;
tmp = BitConverter.GetBytes(val);
}
for (int j = 0; j < IntPtr.Size; j++)
p[i + j] = tmp[j];
i += IntPtr.Size;
p[i] = 0xff;
i++;
p[i] = 0xe0; // jmp [r|e]ax
i++;
}
return new KeyValuePair<int, IntPtr>(i, ptr);
}
19
Source : IdentityGenerator.cs
with MIT License
from amolines
with MIT License
from amolines
public static Guid NewSequentialGuid(IdenreplacedyGeneratorType guidType)
{
var randomBytes = new byte[10];
Rng.GetBytes(randomBytes);
var timestamp = DateTime.UtcNow.Ticks / 10000L;
var timestampBytes = BitConverter.GetBytes(timestamp);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(timestampBytes);
}
var guidBytes = new byte[16];
switch (guidType)
{
case IdenreplacedyGeneratorType.Sequentialreplacedtring:
case IdenreplacedyGeneratorType.SequentialAsBinary:
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);
Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10);
if (guidType == IdenreplacedyGeneratorType.Sequentialreplacedtring && BitConverter.IsLittleEndian)
{
Array.Reverse(guidBytes, 0, 4);
Array.Reverse(guidBytes, 4, 2);
}
break;
case IdenreplacedyGeneratorType.SequentialAtEnd:
Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
break;
}
return new Guid(guidBytes);
}
19
Source : DataBuffer.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public void SetInt64(int index, long value)
{
byte[] blob = BitConverter.GetBytes(value);
InternalSwap(blob);
SetBytes(index, blob);
}
19
Source : DataBuffer.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public void AddInt64(long value)
{
byte[] blob = BitConverter.GetBytes(value);
InternalSwap(blob);
AddBytes(blob);
}
19
Source : Extensions.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public static ModbusObject[] ToModbusRegister(this long value, ushort address, bool inverseRegisters = false)
{
byte[] bytes = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
var registers = new ModbusObject[bytes.Length / 2];
if (inverseRegisters)
{
int startAddress = address + registers.Length - 1;
for (int i = 0; i < registers.Length; i++)
{
registers[i] = new ModbusObject
{
Address = (ushort)(startAddress - i),
Type = ModbusObjectType.HoldingRegister,
HiByte = bytes[i * 2],
LoByte = bytes[i * 2 + 1]
};
}
}
else
{
for (int i = 0; i < registers.Length; i++)
{
registers[i] = new ModbusObject
{
Address = (ushort)(address + i),
Type = ModbusObjectType.HoldingRegister,
HiByte = bytes[i * 2],
LoByte = bytes[i * 2 + 1]
};
}
}
return registers;
}
19
Source : Register.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public static List<Register> Create(long value, ushort address, bool isInput = false)
{
if (address + 3 > Consts.MaxAddress)
throw new ArgumentOutOfRangeException(nameof(address));
var list = new List<Register>();
byte[] blob = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian)
Array.Reverse(blob);
for (int i = 0; i < blob.Length / 2; i++)
{
int bytePos = i * 2;
list.Add(new Register
{
Type = isInput ? ModbusObjectType.InputRegister : ModbusObjectType.HoldingRegister,
Address = Convert.ToUInt16(address + i),
HiByte = blob[bytePos],
LoByte = blob[bytePos + 1]
});
}
return list;
}
19
Source : PtrRemover.cs
with MIT License
from Andy53
with MIT License
from Andy53
public static List<IntPtr> RemovePointers(MachineType mt, List<IntPtr> srcList, byte[] bytes)
{
bool nullByte = false;
foreach (byte b in bytes)
{
if (b == 0x00)
{
nullByte = true;
}
}
for (int i = 0; i < srcList.Count; i++)
{
bool removed = false;
var ptr = BitConverter.GetBytes((long)srcList[i]);
for(int j = 0; j < ptr.Length; j++)
{
for(int k = 0; k < bytes.Length; k++)
{
if (bytes[k] == ptr[j] && removed == false)
{
srcList.RemoveAt(i);
removed = true;
i--;
}
if(mt == MachineType.I386 && removed == false && nullByte == true)
{
if(srcList[i].ToString("X8").Length < 7)
{
srcList.RemoveAt(i);
removed = true;
i--;
}
}
else if(mt == MachineType.x64 && removed == false && nullByte == true)
{
if (srcList[i].ToString("X").Length < 15)
{
srcList.RemoveAt(i);
removed = true;
i--;
}
}
}
}
}
return srcList;
}
19
Source : PtrRemover.cs
with MIT License
from Andy53
with MIT License
from Andy53
public static Dictionary<IntPtr, string> RemovePointers(MachineType mt, Dictionary<IntPtr, string> srcList, byte[] bytes)
{
bool nullByte = false;
foreach(byte b in bytes)
{
if(b == 0x00)
{
nullByte = true;
}
}
for (int i = 0; i < srcList.Count; i++)
{
bool removed = false;
var ptr = BitConverter.GetBytes((long)srcList.ElementAt(i).Key);
for (int j = 0; j < ptr.Length; j++)
{
for (int k = 0; k < bytes.Length; k++)
{
if (bytes[k] == ptr[j] && removed == false)
{
srcList.Remove(srcList.ElementAt(i).Key);
removed = true;
i--;
}
if (mt == MachineType.I386 && removed == false && nullByte == true)
{
if (srcList.ElementAt(i).Key.ToString("X").Length < 7)
{
srcList.Remove(srcList.ElementAt(i).Key);
removed = true;
i--;
}
}
else if (mt == MachineType.x64 && removed == false && nullByte == true)
{
if (srcList.ElementAt(i).Key.ToString("X").Length < 15)
{
srcList.Remove(srcList.ElementAt(i).Key);
removed = true;
i--;
}
}
}
}
}
return srcList;
}
19
Source : Thread_Info.cs
with MIT License
from Andy53
with MIT License
from Andy53
internal ErcResult<List<Tuple<byte[], byte[]>>> BuildSehChain()
{
ErcResult<List<Tuple<byte[], byte[]>>> sehList = new ErcResult<List<Tuple<byte[], byte[]>>>(ThreadCore);
sehList.ReturnValue = new List<Tuple<byte[], byte[]>>();
if (Teb.Equals(default(TEB)))
{
sehList.Error = new Exception("Error: TEB structure for this thread has not yet been populated. Call PopulateTEB first");
return sehList;
}
if(Teb.CurrentSehFrame == IntPtr.Zero)
{
sehList.Error = new Exception("Error: No SEH chain has been generated yet. An SEH chain will not be generated until a crash occurs.");
return sehList;
}
byte[] sehEntry;
byte[] sehFinal;
int arraySize = 0;
if(X64 == MachineType.x64)
{
arraySize = 8;
sehEntry = new byte[arraySize];
sehFinal = new byte[arraySize];
sehEntry = BitConverter.GetBytes((long)Teb.CurrentSehFrame);
}
else
{
arraySize = 4;
sehEntry = new byte[arraySize];
sehFinal = new byte[arraySize];
sehEntry = BitConverter.GetBytes((int)Teb.CurrentSehFrame);
}
for (int i = 0; i < sehFinal.Length; i++)
{
sehFinal[i] = 0xFF;
}
byte[] prevSEH = new byte[] { 0xFF };
string pattern_standard = File.ReadAllText(ThreadCore.PatternStandardPath);
string pattern_extended = File.ReadAllText(ThreadCore.PatternExtendedPath);
while (!sehEntry.SequenceEqual(sehFinal))
{
byte[] reversedSehEntry = new byte[arraySize];
byte[] nSeh = new byte[arraySize];
byte[] sehHolder = new byte[arraySize * 2];
int ret = 0;
if(X64 == MachineType.x64)
{
ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt64(sehEntry, 0), sehHolder, arraySize * 2, out int retInt);
Array.Copy(sehHolder, 0, sehEntry, 0, arraySize);
Array.Copy(sehHolder, arraySize, nSeh, 0, arraySize);
}
else
{
ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt32(sehEntry, 0), sehHolder, arraySize * 2, out int retInt);
Array.Copy(sehHolder, 0, sehEntry, 0, arraySize);
Array.Copy(sehHolder, arraySize, nSeh, 0, arraySize);
}
if (ret != 0 && ret != 1)
{
ERCException e = new ERCException("System error: An error occured when executing ReadProcessMemory\n Process Handle = 0x"
+ ThreadProcess.ProcessHandle.ToString("X") + " TEB Current Seh = 0x" + Teb.CurrentSehFrame.ToString("X") +
" Return value = " + ret + Environment.NewLine + "Win32Exception: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
sehList.Error = e;
sehList.LogEvent();
return sehList;
}
Array.Reverse(nSeh);
for(int i = 0; i < sehEntry.Length; i++)
{
reversedSehEntry[i] = sehEntry[i];
}
Array.Reverse(reversedSehEntry, 0, reversedSehEntry.Length);
if (prevSEH.SequenceEqual(reversedSehEntry))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
else if (!sehEntry.SequenceEqual(sehFinal) && !sehList.ReturnValue.Any(e => e.Item1.SequenceEqual(reversedSehEntry)))
{
Tuple<byte[], byte[]> tuple = new Tuple<byte[], byte[]>(reversedSehEntry, nSeh);
sehList.ReturnValue.Add(tuple);
}
if (pattern_standard.Contains(Encoding.Unicode.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.Unicode.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
if (pattern_standard.Contains(Encoding.ASCII.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.ASCII.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
if (pattern_standard.Contains(Encoding.UTF32.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.UTF32.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
if (pattern_standard.Contains(Encoding.UTF7.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.UTF7.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
if (pattern_standard.Contains(Encoding.UTF8.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.UTF8.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
prevSEH = new byte[reversedSehEntry.Length];
Array.Copy(reversedSehEntry, 0, prevSEH, 0, reversedSehEntry.Length);
}
SehChain = new List<Tuple<byte[], byte[]>>(sehList.ReturnValue);
return sehList;
}
19
Source : StreamUtils.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public static void WriteInt64(Stream stream, long i)
{
byte[] bytes = Convert(BitConverter.GetBytes(i));
stream.Write(bytes, 0, bytes.Length);
}
19
Source : LongSchema.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public ReadOnlySequence<byte> Encode(long message)
{
var array = BitConverter.GetBytes(message);
if (BitConverter.IsLittleEndian)
Array.Reverse(array);
return new(array);
}
19
Source : ExtendedBinaryReader.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
public long ReadInt64Reverse()
{
return this.ReadReverse<long>(BitConverter.GetBytes(this.ReadInt64()));
}
19
Source : ExtendedBinaryWriter.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
public void WriteReverse(long value)
{
this.WriteReverse(BitConverter.GetBytes(value));
}
19
Source : ZipEntry.Write.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private byte[] ConstructExtraField(bool forCentralDirectory)
{
var listOfBlocks = new System.Collections.Generic.List<byte[]>();
byte[] block;
// Conditionally emit an extra field with Zip64 information. If the
// Zip64 option is Always, we emit the field, before knowing that it's
// necessary. Later, if it turns out this entry does not need zip64,
// we'll set the header ID to rubbish and the data will be ignored.
// This results in additional overhead metadata in the zip file, but
// it will be small in comparison to the entry data.
//
// On the other hand if the Zip64 option is AsNecessary and it's NOT
// for the central directory, then we do the same thing. Or, if the
// Zip64 option is AsNecessary and it IS for the central directory,
// and the entry requires zip64, then emit the header.
if (_container.Zip64 == Zip64Option.Always ||
(_container.Zip64 == Zip64Option.AsNecessary &&
(!forCentralDirectory || _entryRequiresZip64.Value)))
{
// add extra field for zip64 here
// workitem 7924
int sz = 4 + (forCentralDirectory ? 28 : 16);
block = new byte[sz];
int i = 0;
if (_presumeZip64 || forCentralDirectory)
{
// HeaderId = always use zip64 extensions.
block[i++] = 0x01;
block[i++] = 0x00;
}
else
{
// HeaderId = dummy data now, maybe set to 0x0001 (ZIP64) later.
block[i++] = 0x99;
block[i++] = 0x99;
}
// DataSize
block[i++] = (byte)(sz - 4); // decimal 28 or 16 (workitem 7924)
block[i++] = 0x00;
// The actual metadata - we may or may not have real values yet...
// uncompressed size
Array.Copy(BitConverter.GetBytes(_UncompressedSize), 0, block, i, 8);
i += 8;
// compressed size
Array.Copy(BitConverter.GetBytes(_CompressedSize), 0, block, i, 8);
i += 8;
// workitem 7924 - only include this if the "extra" field is for
// use in the central directory. It is unnecessary and not useful
// for local header; makes WinZip choke.
if (forCentralDirectory)
{
// relative offset
Array.Copy(BitConverter.GetBytes(_RelativeOffsetOfLocalHeader), 0, block, i, 8);
i += 8;
// starting disk number
Array.Copy(BitConverter.GetBytes(0), 0, block, i, 4);
}
listOfBlocks.Add(block);
}
#if AESCRYPTO
if (Encryption == EncryptionAlgorithm.WinZipAes128 ||
Encryption == EncryptionAlgorithm.WinZipAes256)
{
block = new byte[4 + 7];
int i = 0;
// extra field for WinZip AES
// header id
block[i++] = 0x01;
block[i++] = 0x99;
// data size
block[i++] = 0x07;
block[i++] = 0x00;
// vendor number
block[i++] = 0x01; // AE-1 - means "Verify CRC"
block[i++] = 0x00;
// vendor id "AE"
block[i++] = 0x41;
block[i++] = 0x45;
// key strength
int keystrength = GetKeyStrengthInBits(Encryption);
if (keystrength == 128)
block[i] = 1;
else if (keystrength == 256)
block[i] = 3;
else
block[i] = 0xFF;
i++;
// actual compression method
block[i++] = (byte)(_CompressionMethod & 0x00FF);
block[i++] = (byte)(_CompressionMethod & 0xFF00);
listOfBlocks.Add(block);
}
#endif
if (_ntfsTimesAreSet && _emitNtfsTimes)
{
block = new byte[32 + 4];
// HeaderId 2 bytes 0x000a == NTFS times
// Datasize 2 bytes 32
// reserved 4 bytes ?? don't care
// timetag 2 bytes 0x0001 == NTFS time
// size 2 bytes 24 == 8 bytes each for ctime, mtime, atime
// mtime 8 bytes win32 ticks since win32epoch
// atime 8 bytes win32 ticks since win32epoch
// ctime 8 bytes win32 ticks since win32epoch
int i = 0;
// extra field for NTFS times
// header id
block[i++] = 0x0a;
block[i++] = 0x00;
// data size
block[i++] = 32;
block[i++] = 0;
i += 4; // reserved
// time tag
block[i++] = 0x01;
block[i++] = 0x00;
// data size (again)
block[i++] = 24;
block[i++] = 0;
Int64 z = _Mtime.ToFileTime();
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 8);
i += 8;
z = _Atime.ToFileTime();
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 8);
i += 8;
z = _Ctime.ToFileTime();
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 8);
i += 8;
listOfBlocks.Add(block);
}
if (_ntfsTimesAreSet && _emitUnixTimes)
{
int len = 5 + 4;
if (!forCentralDirectory) len += 8;
block = new byte[len];
// local form:
// --------------
// HeaderId 2 bytes 0x5455 == unix timestamp
// Datasize 2 bytes 13
// flags 1 byte 7 (low three bits all set)
// mtime 4 bytes seconds since unix epoch
// atime 4 bytes seconds since unix epoch
// ctime 4 bytes seconds since unix epoch
//
// central directory form:
//---------------------------------
// HeaderId 2 bytes 0x5455 == unix timestamp
// Datasize 2 bytes 5
// flags 1 byte 7 (low three bits all set)
// mtime 4 bytes seconds since unix epoch
//
int i = 0;
// extra field for "unix" times
// header id
block[i++] = 0x55;
block[i++] = 0x54;
// data size
block[i++] = unchecked((byte)(len - 4));
block[i++] = 0;
// flags
block[i++] = 0x07;
Int32 z = unchecked((int)((_Mtime - _unixEpoch).TotalSeconds));
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 4);
i += 4;
if (!forCentralDirectory)
{
z = unchecked((int)((_Atime - _unixEpoch).TotalSeconds));
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 4);
i += 4;
z = unchecked((int)((_Ctime - _unixEpoch).TotalSeconds));
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 4);
i += 4;
}
listOfBlocks.Add(block);
}
// inject other blocks here...
// concatenate any blocks we've got:
byte[] aggregateBlock = null;
if (listOfBlocks.Count > 0)
{
int totalLength = 0;
int i, current = 0;
for (i = 0; i < listOfBlocks.Count; i++)
totalLength += listOfBlocks[i].Length;
aggregateBlock = new byte[totalLength];
for (i = 0; i < listOfBlocks.Count; i++)
{
System.Array.Copy(listOfBlocks[i], 0, aggregateBlock, current, listOfBlocks[i].Length);
current += listOfBlocks[i].Length;
}
}
return aggregateBlock;
}
19
Source : ZipFile.Save.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private static byte[] GenZip64EndOfCentralDirectory(long StartOfCentralDirectory,
long EndOfCentralDirectory,
int entryCount,
uint numSegments)
{
const int bufferLength = 12 + 44 + 20;
byte[] bytes = new byte[bufferLength];
int i = 0;
// signature
byte[] sig = BitConverter.GetBytes(ZipConstants.Zip64EndOfCentralDirectoryRecordSignature);
Array.Copy(sig, 0, bytes, i, 4);
i+=4;
// There is a possibility to include "Extensible" data in the zip64
// end-of-central-dir record. I cannot figure out what it might be used to
// store, so the size of this record is always fixed. Maybe it is used for
// strong encryption data? That is for another day.
long DataSize = 44;
Array.Copy(BitConverter.GetBytes(DataSize), 0, bytes, i, 8);
i += 8;
// offset 12
// VersionMadeBy = 45;
bytes[i++] = 45;
bytes[i++] = 0x00;
// VersionNeededToExtract = 45;
bytes[i++] = 45;
bytes[i++] = 0x00;
// offset 16
// number of the disk, and the disk with the start of the central dir.
// (this may change later)
for (int j = 0; j < 8; j++)
bytes[i++] = 0x00;
// offset 24
long numberOfEntries = entryCount;
Array.Copy(BitConverter.GetBytes(numberOfEntries), 0, bytes, i, 8);
i += 8;
Array.Copy(BitConverter.GetBytes(numberOfEntries), 0, bytes, i, 8);
i += 8;
// offset 40
Int64 SizeofCentraldirectory = EndOfCentralDirectory - StartOfCentralDirectory;
Array.Copy(BitConverter.GetBytes(SizeofCentraldirectory), 0, bytes, i, 8);
i += 8;
Array.Copy(BitConverter.GetBytes(StartOfCentralDirectory), 0, bytes, i, 8);
i += 8;
// offset 56
// now, the locator
// signature
sig = BitConverter.GetBytes(ZipConstants.Zip64EndOfCentralDirectoryLocatorSignature);
Array.Copy(sig, 0, bytes, i, 4);
i+=4;
// offset 60
// number of the disk with the start of the zip64 eocd
// (this will change later) (it will?)
uint x2 = (numSegments==0)?0:(uint)(numSegments-1);
Array.Copy(BitConverter.GetBytes(x2), 0, bytes, i, 4);
i+=4;
// offset 64
// relative offset of the zip64 eocd
Array.Copy(BitConverter.GetBytes(EndOfCentralDirectory), 0, bytes, i, 8);
i += 8;
// offset 72
// total number of disks
// (this will change later)
Array.Copy(BitConverter.GetBytes(numSegments), 0, bytes, i, 4);
i+=4;
return bytes;
}
19
Source : MD5Core.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
internal static byte[] GetHashFinalBlock(byte[] input, int ibStart, int cbSize, ABCDStruct ABCD, Int64 len)
{
byte[] working = new byte[64];
byte[] length = BitConverter.GetBytes(len);
//Padding is a single bit 1, followed by the number of 0s required to make size congruent to 448 modulo 512. Step 1 of RFC 1321
//The CLR ensures that our buffer is 0-replacedigned, we don't need to explicitly set it. This is why it ends up being quicker to just
//use a temporary array rather then doing in-place replacedignment (5% for small inputs)
Array.Copy(input, ibStart, working, 0, cbSize);
working[cbSize] = 0x80;
//We have enough room to store the length in this chunk
if (cbSize < 56)
{
Array.Copy(length, 0, working, 56, 8);
GetHashBlock(working, ref ABCD, 0);
}
else //We need an aditional chunk to store the length
{
GetHashBlock(working, ref ABCD, 0);
//Create an entirely new chunk due to the 0-replacedigned trick mentioned above, to avoid an extra function call clearing the array
working = new byte[64];
Array.Copy(length, 0, working, 56, 8);
GetHashBlock(working, ref ABCD, 0);
}
byte[] output = new byte[16];
Array.Copy(BitConverter.GetBytes(ABCD.A), 0, output, 0, 4);
Array.Copy(BitConverter.GetBytes(ABCD.B), 0, output, 4, 4);
Array.Copy(BitConverter.GetBytes(ABCD.C), 0, output, 8, 4);
Array.Copy(BitConverter.GetBytes(ABCD.D), 0, output, 12, 4);
return output;
}
19
Source : SequentialGuidGenerator.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public Guid Create(SequentialGuidType guidType)
{
// We start with 16 bytes of cryptographically strong random data.
var randomBytes = new byte[10];
Rng.Locking(r => r.GetBytes(randomBytes));
// An alternate method: use a normally-created GUID to get our initial
// random data:
// byte[] randomBytes = Guid.NewGuid().ToByteArray();
// This is faster than using RNGCryptoServiceProvider, but I don't
// recommend it because the .NET Framework makes no guarantee of the
// randomness of GUID data, and future versions (or different
// implementations like Mono) might use a different method.
// Now we have the random basis for our GUID. Next, we need to
// create the six-byte block which will be our timestamp.
// We start with the number of milliseconds that have elapsed since
// DateTime.MinValue. This will form the timestamp. There's no use
// being more specific than milliseconds, since DateTime.Now has
// limited resolution.
// Using millisecond resolution for our 48-bit timestamp gives us
// about 5900 years before the timestamp overflows and cycles.
// Hopefully this should be sufficient for most purposes. :)
long timestamp = DateTime.UtcNow.Ticks / 10000L;
// Then get the bytes
byte[] timestampBytes = BitConverter.GetBytes(timestamp);
// Since we're converting from an Int64, we have to reverse on
// little-endian systems.
if (BitConverter.IsLittleEndian)
{
Array.Reverse(timestampBytes);
}
byte[] guidBytes = new byte[16];
switch (guidType)
{
case SequentialGuidType.Sequentialreplacedtring:
case SequentialGuidType.SequentialAsBinary:
// For string and byte-array version, we copy the timestamp first, followed
// by the random data.
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);
Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10);
// If formatting as a string, we have to compensate for the fact
// that .NET regards the Data1 and Data2 block as an Int32 and an Int16,
// respectively. That means that it switches the order on little-endian
// systems. So again, we have to reverse.
if (guidType == SequentialGuidType.Sequentialreplacedtring && BitConverter.IsLittleEndian)
{
Array.Reverse(guidBytes, 0, 4);
Array.Reverse(guidBytes, 4, 2);
}
break;
case SequentialGuidType.SequentialAtEnd:
// For sequential-at-the-end versions, we copy the random data first,
// followed by the timestamp.
Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
break;
}
return new Guid(guidBytes);
}
19
Source : Totp.cs
with MIT License
from Arch
with MIT License
from Arch
private static int ComputeTotp(HashAlgorithm hashAlgorithm, ulong timestepNumber, string modifier)
{
// # of 0's = length of pin
const int Mod = 1000000;
// See https://tools.ietf.org/html/rfc4226
// We can add an optional modifier
var timestepAsBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((long)timestepNumber));
var hash = hashAlgorithm.ComputeHash(ApplyModifier(timestepAsBytes, modifier));
// Generate DT string
var offset = hash[hash.Length - 1] & 0xf;
Debug.replacedert(offset + 4 < hash.Length);
var binaryCode = (hash[offset] & 0x7f) << 24
| (hash[offset + 1] & 0xff) << 16
| (hash[offset + 2] & 0xff) << 8
| (hash[offset + 3] & 0xff);
return binaryCode % Mod;
}
19
Source : SaveStatManager.cs
with MIT License
from Arefu
with MIT License
from Arefu
internal static void WriteSaveStatToSave(string SaveFile)
{
using (var SaveStatWriter = new BinaryWriter(File.Open(SaveFile, FileMode.Open, FileAccess.Write)))
{
SaveStatWriter.BaseStream.Position = 0x24;
// "SAVESTAT_GAMES_CAMPAIGN"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown1.Value));
// "SAVESTAT_GAMES_CAMPAIGN_NORMAL"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown2.Value));
// "SAVESTAT_GAMES_CAMPAIGN_REVERSE"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown3.Value));
// "SAVESTAT_GAMES_CHALLENGE"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown4.Value));
// "SAVESTAT_GAMES_MULTIPLAYER"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown5.Value));
// ""SAVESTAT_GAMES_MULTIPLAYER_1V1"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown6.Value));
// "SAVESTAT_GAMES_MULTIPLAYER_TAG"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown7.Value));
// "SAVESTAT_GAMES_MULTIPLAYER_RANKED"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown8.Value));
// "SAVESTAT_GAMES_MULTIPLAYER_FRIENDLY"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown9.Value));
// "SAVESTAT_GAMES_MULTIPLAYER_BATTLEPACK_ANY"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown10.Value));
// "SAVESTAT_GAMES_MULTIPLAYER_BATTLEPACK_1"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown11.Value));
// "SAVESTAT_GAMES_MULTIPLAYER_BATTLEPACK_2"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown12.Value));
// "SAVESTAT_GAMES_MULTIPLAYER_BATTLEPACK_3"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown13.Value));
// "SAVESTAT_WINS_CAMPAIGN"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown14.Value));
// "SAVESTAT_WINS_CAMPAIGN_NORMAL"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown15.Value));
// "SAVESTAT_WINS_CAMPAIGN_REVERSE"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown16.Value));
// "SAVESTAT_WINS_CHALLENGE"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown17.Value));
// "SAVESTAT_WINS_MULTIPLAYER"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown18.Value));
// "SAVESTAT_WINS_MULTIPLAYER_1V1"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown19.Value));
// "SAVESTAT_WINS_MULTIPLAYER_TAG"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown20.Value));
// "SAVESTAT_WINS_MULTIPLAYER_RANKED"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown21.Value));
// "SAVESTAT_WINS_MULTIPLAYER_FRIENDLY"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown22.Value));
// "SAVESTAT_WINS_MULTIPLAYER_BATTLEPACK_ANY"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown23.Value));
// "SAVESTAT_WINS_MULTIPLAYER_BATTLEPACK_1"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown24.Value));
// "SAVESTAT_WINS_MULTIPLAYER_BATTLEPACK_2"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown25.Value));
// "SAVESTAT_WINS_MULTIPLAYER_BATTLEPACK_3"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown26.Value));
// "SAVESTAT_WINS_MATCH"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown27.Value));
// "SAVESTAT_WINS_NONMATCH"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown28.Value));
// "SAVESTAT_SUMMONS_NORMAL"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown29.Value));
// "SAVESTAT_SUMMONS_TRIBUTE"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown30.Value));
// "SAVESTAT_SUMMONS_RITUAL"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown31.Value));
// "SAVESTAT_SUMMONS_FUSION"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown32.Value));
// "SAVESTAT_SUMMONS_XYZ"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown33.Value));
// "SAVESTAT_SUMMONS_SYNCHRO"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown34.Value));
// "SAVESTAT_SUMMONS_PENDULUM"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown35.Value));
// "SAVESTAT_DAMAGE_ANY"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown36.Value));
// "SAVESTAT_DAMAGE_BATTLE"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown37.Value));
// SAVESTAT_DAMAGE_DIRECT"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown38.Value));
// "SAVESTAT_DAMAGE_EFFECT"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown39.Value));
// "SAVESTAT_DAMAGE_REFLECT"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown40.Value));
// "SAVESTAT_CHAINS"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown41.Value));
// "SAVESTAT_DECKS_CREATED"
SaveStatWriter.Write(BitConverter.GetBytes((long) Form1.numericUpDown42.Value));
}
}
See More Examples