Here are the examples of the csharp api System.BitConverter.GetBytes(uint) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
924 Examples
19
Source : UiHelper.Textures.cs
with GNU Affero General Public License v3.0
from 0ceal0t
with GNU Affero General Public License v3.0
from 0ceal0t
private unsafe static string GetResolvedPath(string texPath) {
var pathBytes = Encoding.ASCII.GetBytes(texPath);
var bPath = stackalloc byte[pathBytes.Length + 1];
Marshal.Copy(pathBytes, 0, new IntPtr(bPath), pathBytes.Length);
var pPath = (char*)bPath;
var typeBytes = Encoding.ASCII.GetBytes("xet");
var bType = stackalloc byte[typeBytes.Length + 1];
Marshal.Copy(typeBytes, 0, new IntPtr(bType), typeBytes.Length);
var pResourceType = (char*)bType;
// TODO: might need to change this based on path
var categoryBytes = BitConverter.GetBytes((uint)6);
var bCategory = stackalloc byte[categoryBytes.Length + 1];
Marshal.Copy(categoryBytes, 0, new IntPtr(bCategory), categoryBytes.Length);
var pCategoryId = (uint*)bCategory;
Crc32.Init();
Crc32.Update(pathBytes);
var hashBytes = BitConverter.GetBytes(Crc32.Checksum);
var bHash = stackalloc byte[hashBytes.Length + 1];
Marshal.Copy(hashBytes, 0, new IntPtr(bHash), hashBytes.Length);
var pResourceHash = (uint*)bHash;
var resource = (TextureResourceHandle*) GetResourceSync(GetFileManager(), pCategoryId, pResourceType, pResourceHash, pPath, (void*)IntPtr.Zero);
var resolvedPath = resource->ResourceHandle.FileName.ToString();
resource->ResourceHandle.DecRef(); // not actually using this
PluginLog.Log($"RefCount {texPath} {resource->ResourceHandle.RefCount}");
return resolvedPath;
}
19
Source : RequestObject.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public bool Reply(string data)
{
byte[] buffer = Encoding.ASCII.GetBytes(data);
byte[] dataLen = BitConverter.GetBytes((uint)buffer.Length);
try
{
this.serverIoPipe.Write(dataLen, 0, 4);
this.serverIoPipe.Write(buffer, 0, buffer.Length);
}
catch (Exception e)
{
Log.Error("Replying request error: {0}", e.Message);
buffer = null;
dataLen = null;
return false;
}
buffer = null;
dataLen = null;
return true;
}
19
Source : CelesteNetTCPUDPConnection.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void WriteToken(uint token) {
if (UDP == null)
return;
if (UDP.Client.Connected && ReadUDPThread != null) {
UDP.Send(BitConverter.GetBytes(token), 4);
} else if (UDPRemoteEndPoint != null) {
UDP.Send(BitConverter.GetBytes(token), 4, UDPRemoteEndPoint);
}
}
19
Source : NTLM.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
private static byte[] MakeSignature(RC4 SealKey, byte[] SignKey, byte[] message, ref uint sequenceNum)
{
HMACT64 hmact = new HMACT64(SignKey);
byte[] bytes = BitConverter.GetBytes(sequenceNum++);
hmact.update(bytes);
hmact.update(message);
byte[] data = hmact.digest();
byte[] collection = SealKey.crypt(data, 0, 8);
List<byte> list = new List<byte> { 1, 0, 0, 0 };
list.AddRange(collection);
list.AddRange(bytes);
return list.ToArray();
}
19
Source : RdpPacket.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
public void WriteLittleEndian32(uint value)
{
base.Write(BitConverter.GetBytes(value), 0, 4);
}
19
Source : StringHandlingPackets.cs
with MIT License
from 499116344
with MIT License
from 499116344
public void Add(DateTime datetime)
{
var value = (uint) (datetime - DateTime.Parse("1970-1-1").ToLocalTime()).TotalSeconds;
var bytes = BitConverter.GetBytes(value);
Array.Reverse(bytes);
_stream.Write(bytes, 0, bytes.Length);
}
19
Source : StringHandlingPackets.cs
with MIT License
from 499116344
with MIT License
from 499116344
public void Add(uint item)
{
var bytes = BitConverter.GetBytes(item);
_stream.Write(bytes, 0, bytes.Length);
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, long v)
{
bw.Write(BitConverter.GetBytes((uint) v).Reverse().ToArray());
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, ulong v)
{
bw.Write(BitConverter.GetBytes((uint) v).Reverse().ToArray());
}
19
Source : ButtonIconSet.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static string ConvertUInt32ToUnicodeCharString(uint unicode)
{
byte[] bytes = System.BitConverter.GetBytes(unicode);
return Encoding.Unicode.GetString(bytes);
}
19
Source : P2PManager.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
void PackUInt32(UInt32 u, byte[] buf, ref int offset)
{
Buffer.BlockCopy(BitConverter.GetBytes(u), 0, buf, offset, sizeof(UInt32));
offset += sizeof(UInt32);
}
19
Source : P2PManager.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
void PackUint32(uint value, byte[] buf, ref int offset)
{
Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4);
offset = offset + 4;
}
19
Source : Extensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static void WritePackedDword(this BinaryWriter writer, uint value)
{
if (value <= 32767)
{
ushort networkValue = Convert.ToUInt16(value);
writer.Write(BitConverter.GetBytes(networkValue));
}
else
{
uint packedValue = (value << 16) | ((value >> 16) | 0x8000);
writer.Write(BitConverter.GetBytes(packedValue));
}
}
19
Source : NetworkSession.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private void DoRequestForRetransmission(uint rcvdSeq)
{
var desiredSeq = lastReceivedPacketSequence + 1;
List<uint> needSeq = new List<uint>();
needSeq.Add(desiredSeq);
uint bottom = desiredSeq + 1;
if (rcvdSeq < bottom || rcvdSeq - bottom > CryptoSystem.MaximumEffortLevel)
{
session.Terminate(SessionTerminationReason.AbnormalSequenceReceived);
return;
}
uint seqIdCount = 1;
for (uint a = bottom; a < rcvdSeq; a++)
{
if (!outOfOrderPackets.ContainsKey(a))
{
needSeq.Add(a);
seqIdCount++;
if (seqIdCount >= MaxNumNakSeqIds)
{
break;
}
}
}
ServerPacket reqPacket = new ServerPacket();
byte[] reqData = new byte[4 + (needSeq.Count * 4)];
MemoryStream msReqData = new MemoryStream(reqData, 0, reqData.Length, true, true);
msReqData.Write(BitConverter.GetBytes((uint)needSeq.Count), 0, 4);
needSeq.ForEach(k => msReqData.Write(BitConverter.GetBytes(k), 0, 4));
reqPacket.Data = msReqData;
reqPacket.Header.Flags = PacketHeaderFlags.RequestRetransmit;
EnqueueSend(reqPacket);
LastRequestForRetransmitTime = DateTime.UtcNow;
packetLog.DebugFormat("[{0}] Requested retransmit of {1}", session.LoggingIdentifier, needSeq.Select(k => k.ToString()).Aggregate((a, b) => a + ", " + b));
NetworkStatistics.S2C_RequestsForRetransmit_Aggregate_Increment();
}
19
Source : Serializer.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public static byte[] FromUInt32(uint data, DateTimeOffset? timestamp = null)
=> BitConverter.GetBytes(data).AppendTimestamp(timestamp);
19
Source : Extensions.cs
with MIT License
from adrenak
with MIT License
from adrenak
public static byte[] GetBytes(this uint value) {
return BitConverter.GetBytes(value);
}
19
Source : NumericExtensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static byte[] ToBytes(this uint n, bool bigEndian = true)
{
var bytes = BitConverter.GetBytes(n);
return GetBytesWithEndian(bytes, bigEndian);
}
19
Source : ThreadHijack.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public override IntPtr[] InjectAll(string[] dllPaths, IntPtr hProcess)
{
Exception exception;
this.ClearErrors();
try
{
if (hProcess.IsNull() || hProcess.Compare(-1L))
{
throw new ArgumentException("Invalid process handle.", "hProcess");
}
int processId = WinAPI.GetProcessId(hProcess);
if (processId == 0)
{
throw new ArgumentException("Provided handle doesn't have sufficient permissions to inject", "hProcess");
}
Process processById = Process.GetProcessById(processId);
if (processById.Threads.Count == 0)
{
throw new Exception("Target process has no targetable threads to hijack.");
}
ProcessThread thread = SelectOptimalThread(processById);
IntPtr ptr = WinAPI.OpenThread(0x1a, false, thread.Id);
if (ptr.IsNull() || ptr.Compare(-1L))
{
throw new Exception("Unable to obtain a handle for the remote thread.");
}
IntPtr zero = IntPtr.Zero;
IntPtr lpAddress = IntPtr.Zero;
IntPtr ptr4 = this.CreateMultiLoadStub(dllPaths, hProcess, out zero, 1);
IntPtr[] ptrArray = null;
if (!ptr4.IsNull())
{
if (WinAPI.SuspendThread(ptr) == uint.MaxValue)
{
throw new Exception("Unable to suspend the remote thread");
}
try
{
uint lpNumberOfBytesRead = 0;
WinAPI.CONTEXT pContext = new WinAPI.CONTEXT {
ContextFlags = 0x10001
};
if (!WinAPI.GetThreadContext(ptr, ref pContext))
{
throw new InvalidOperationException("Cannot get the remote thread's context");
}
byte[] array = REDIRECT_STUB;
IntPtr ptr5 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) array.Length, 0x3000, 0x40);
if (ptr5.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process.");
}
BitConverter.GetBytes(ptr4.Subtract(ptr5.Add(((long) 7L))).ToInt32()).CopyTo(array, 3);
BitConverter.GetBytes((uint) (pContext.Eip - ((uint) ptr5.Add(((long) array.Length)).ToInt32()))).CopyTo(array, (int) (array.Length - 4));
if (!(WinAPI.WriteProcessMemory(hProcess, ptr5, array, array.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == array.Length)))
{
throw new InvalidOperationException("Unable to write stub to the remote process.");
}
pContext.Eip = (uint) ptr5.ToInt32();
WinAPI.SetThreadContext(ptr, ref pContext);
}
catch (Exception exception1)
{
exception = exception1;
this.SetLastError(exception);
ptrArray = null;
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, ptr4, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, lpAddress, 0, 0x8000);
}
WinAPI.ResumeThread(ptr);
if (this.GetLastError() == null)
{
Thread.Sleep(100);
ptrArray = new IntPtr[dllPaths.Length];
byte[] buffer2 = WinAPI.ReadRemoteMemory(hProcess, zero, ((uint) dllPaths.Length) << 2);
if (buffer2 != null)
{
for (int i = 0; i < ptrArray.Length; i++)
{
ptrArray[i] = Win32Ptr.Create((long) BitConverter.ToInt32(buffer2, i << 2));
}
}
}
WinAPI.CloseHandle(ptr);
}
return ptrArray;
}
catch (Exception exception2)
{
exception = exception2;
this.SetLastError(exception);
return null;
}
}
19
Source : ManualMap.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public override bool Unload(IntPtr hModule, IntPtr hProcess)
{
this.ClearErrors();
if (hModule.IsNull())
{
throw new ArgumentNullException("hModule", "Invalid module handle");
}
if (hProcess.IsNull() || hProcess.Compare(-1L))
{
throw new ArgumentException("Invalid process handle.", "hProcess");
}
IntPtr zero = IntPtr.Zero;
uint lpNumberOfBytesRead = 0;
try
{
uint num2 = FindEntryPoint(hProcess, hModule);
if (num2 != 0)
{
byte[] array = (byte[]) DLLMAIN_STUB.Clone();
BitConverter.GetBytes(hModule.ToInt32()).CopyTo(array, 11);
BitConverter.GetBytes((uint) 0).CopyTo(array, 6);
BitConverter.GetBytes((uint) 0x3e8).CopyTo(array, 1);
zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) DLLMAIN_STUB.Length, 0x3000, 0x40);
if (zero.IsNull() || (!WinAPI.WriteProcessMemory(hProcess, zero, array, array.Length, out lpNumberOfBytesRead) || (lpNumberOfBytesRead != array.Length)))
{
throw new InvalidOperationException("Unable to write stub to the remote process.");
}
IntPtr hObject = WinAPI.CreateRemoteThread(hProcess, 0, 0, zero, (uint) hModule.Add(((long) num2)).ToInt32(), 0, 0);
if (WinAPI.WaitForSingleObject(hObject, 0x1388) == 0L)
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
WinAPI.CloseHandle(hObject);
return WinAPI.VirtualFreeEx(hProcess, hModule, 0, 0x8000);
}
return false;
}
return WinAPI.VirtualFreeEx(hProcess, hModule, 0, 0x8000);
}
catch (Exception exception)
{
this.SetLastError(exception);
return false;
}
}
19
Source : StandardInjectionMethod.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
protected virtual IntPtr CreateMultiLoadStub(string[] paths, IntPtr hProcess, out IntPtr pModuleBuffer, uint nullmodule = 0)
{
IntPtr ptr6;
pModuleBuffer = IntPtr.Zero;
IntPtr zero = IntPtr.Zero;
try
{
IntPtr moduleHandleA = WinAPI.GetModuleHandleA("kernel32.dll");
IntPtr procAddress = WinAPI.GetProcAddress(moduleHandleA, "LoadLibraryA");
IntPtr ptr = WinAPI.GetProcAddress(moduleHandleA, "GetModuleHandleA");
if (procAddress.IsNull() || ptr.IsNull())
{
throw new Exception("Unable to find necessary function entry points in the remote process");
}
pModuleBuffer = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, ((uint) paths.Length) << 2, 0x3000, 4);
IntPtr ptr5 = WinAPI.CreateRemotePointer(hProcess, Encoding.ASCII.GetBytes(string.Join("\0", paths) + "\0"), 4);
if (pModuleBuffer.IsNull() || ptr5.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process");
}
try
{
uint lpNumberOfBytesRead = 0;
byte[] array = new byte[paths.Length << 2];
for (int i = 0; i < (array.Length >> 2); i++)
{
BitConverter.GetBytes(nullmodule).CopyTo(array, (int) (i << 2));
}
WinAPI.WriteProcessMemory(hProcess, pModuleBuffer, array, array.Length, out lpNumberOfBytesRead);
byte[] buffer2 = (byte[]) MULTILOAD_STUB.Clone();
zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) buffer2.Length, 0x3000, 0x40);
if (zero.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process");
}
BitConverter.GetBytes(ptr5.ToInt32()).CopyTo(buffer2, 7);
BitConverter.GetBytes(paths.Length).CopyTo(buffer2, 15);
BitConverter.GetBytes(pModuleBuffer.ToInt32()).CopyTo(buffer2, 0x18);
BitConverter.GetBytes(ptr.Subtract(zero.Add(((long) 0x38L))).ToInt32()).CopyTo(buffer2, 0x34);
BitConverter.GetBytes(procAddress.Subtract(zero.Add(((long) 0x45L))).ToInt32()).CopyTo(buffer2, 0x41);
if (!(WinAPI.WriteProcessMemory(hProcess, zero, buffer2, buffer2.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == buffer2.Length)))
{
throw new Exception("Error creating the remote function stub.");
}
ptr6 = zero;
}
finally
{
WinAPI.VirtualFreeEx(hProcess, pModuleBuffer, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, ptr5, 0, 0x8000);
if (!zero.IsNull())
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
}
pModuleBuffer = IntPtr.Zero;
}
}
catch (Exception exception)
{
this.SetLastError(exception);
ptr6 = IntPtr.Zero;
}
return ptr6;
}
19
Source : ProcessExtensions.cs
with GNU General Public License v3.0
from aglab2
with GNU General Public License v3.0
from aglab2
public static float ToFloatBits(this uint i)
{
return BitConverter.ToSingle(BitConverter.GetBytes(i), 0);
}
19
Source : BigEndianBinaryReader.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public override float ReadSingle()
{
byte[] byteBuffer = BitConverter.GetBytes(ReadUInt32());
return BitConverter.ToSingle(byteBuffer, 0);
}
19
Source : Utils.cs
with Apache License 2.0
from ajuna-network
with Apache License 2.0
from ajuna-network
public static byte[] Value2Bytes(object value, bool littleEndian = true)
{
byte[] result;
switch (value)
{
case ushort s:
result = BitConverter.GetBytes(s);
break;
case uint s:
result = BitConverter.GetBytes(s);
break;
case ulong s:
result = BitConverter.GetBytes(s);
break;
default:
throw new Exception("Unhandled byte size for this method!");
}
if (!littleEndian) Array.Reverse(result);
return result;
}
19
Source : Utils.cs
with Apache License 2.0
from ajuna-network
with Apache License 2.0
from ajuna-network
internal static byte[] KeyTypeToBytes(string keyType, string parameter)
{
switch (keyType)
{
case "u16":
return BitConverter.GetBytes(ushort.Parse(parameter));
case "u32":
return BitConverter.GetBytes(uint.Parse(parameter));
case "u64":
return BitConverter.GetBytes(ulong.Parse(parameter));
case "T::Hash":
var hash = new Hash();
hash.Create(parameter);
return hash.Bytes;
case "T::AccountId":
var accountId = new AccountId();
accountId.Create(parameter);
return accountId.Bytes;
case "Vec<u8>":
var vecU8 = Utils.SizePrefixedByteArray(Utils.HexToByteArray(parameter).ToList());
return vecU8;
case "T::replacedetId":
var replacedetId = new replacedetId();
replacedetId.Create(uint.Parse(parameter));
return replacedetId.Bytes;
default:
throw new Exception($"Unimplemented item function key 'item.Function.Key1' = {keyType}!");
}
}
19
Source : U32.cs
with Apache License 2.0
from ajuna-network
with Apache License 2.0
from ajuna-network
public void Create(uint value)
{
Bytes = BitConverter.GetBytes(value);
Value = value;
}
19
Source : BitStream.cs
with MIT License
from Alexander-Scott
with MIT License
from Alexander-Scott
public void WriteUInt32(uint value)
{
WriteBytes(BitConverter.GetBytes(value), 32);
}
19
Source : BitStream.cs
with MIT License
from Alexander-Scott
with MIT License
from Alexander-Scott
public void WriteUInt24(UInt24 value)
{
WriteBytes(BitConverter.GetBytes((uint) value), 24);
}
19
Source : PngEncoder.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private static void WriteBigEndian(BinaryWriter w, uint value)
{
var bytes = BitConverter.GetBytes(value);
w.Write(bytes[3]);
w.Write(bytes[2]);
w.Write(bytes[1]);
w.Write(bytes[0]);
}
19
Source : I360Render.cs
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
private static byte[] CalculateCRCBytes_PNG( uint crc )
{
var result = BitConverter.GetBytes( crc );
if( BitConverter.IsLittleEndian )
Array.Reverse( result );
return result;
}
19
Source : ThemingService.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public Color GetThemedColorValue(ref Guid colorCategory, string colorName, bool foreground)
{
Type vsUIShell5 = typeof(IVsUIShell5);
if (vsUIShell5 == null)
throw new InvalidOperationException();
IVsUIShell5 vs5 = GetService<IVsUIShell5>(typeof(SVsUIShell));
MethodInfo method = vsUIShell5.GetMethod("GetThemedColor");
uint clr = vs5.GetThemedColor(ref colorCategory, colorName, foreground ? (uint)1 : 0);
// TODO: Use bitshifting
byte[] colorComponents = BitConverter.GetBytes(clr);
return System.Drawing.Color.FromArgb(colorComponents[3], colorComponents[0], colorComponents[1], colorComponents[2]);
}
19
Source : LocationService.cs
with GNU Lesser General Public License v3.0
from andisturber
with GNU Lesser General Public License v3.0
from andisturber
public void UpdateLocation(Location location)
{
if (Devices.Count == 0)
{
PrintMessage($"修改失败! 未发现任何设备。");
return;
}
iDevice.idevice_set_debug_level(1);
var Longitude = location.Longitude.ToString();
var Lareplacedude = location.Lareplacedude.ToString();
PrintMessage($"尝试修改位置。");
PrintMessage($"经度:{location.Longitude}");
PrintMessage($"纬度:{location.Lareplacedude}");
var size = BitConverter.GetBytes(0u);
Array.Reverse(size);
Devices.ForEach(itm =>
{
PrintMessage($"开始修改设备 {itm.Name} {itm.Version}");
var num = 0u;
iDevice.idevice_new(out var device, itm.UDID);
lockdown.lockdownd_client_new_with_handshake(device, out var client, "com.alpha.jailout").ThrowOnError();//com.alpha.jailout
lockdown.lockdownd_start_service(client, "com.apple.dt.simulatelocation", out var service2).ThrowOnError();//com.apple.dt.simulatelocation
var se = service.service_client_new(device, service2, out var client2);
// 先置空
se = service.service_send(client2, size, 4u, ref num);
num = 0u;
var bytesLocation = Encoding.ASCII.GetBytes(Lareplacedude);
size = BitConverter.GetBytes((uint)Lareplacedude.Length);
Array.Reverse(size);
se = service.service_send(client2, size, 4u, ref num);
se = service.service_send(client2, bytesLocation, (uint)bytesLocation.Length, ref num);
bytesLocation = Encoding.ASCII.GetBytes(Longitude);
size = BitConverter.GetBytes((uint)Longitude.Length);
Array.Reverse(size);
se = service.service_send(client2, size, 4u, ref num);
se = service.service_send(client2, bytesLocation, (uint)bytesLocation.Length, ref num);
//device.Dispose();
//client.Dispose();
PrintMessage($"设备 {itm.Name} {itm.Version} 位置修改完成。");
});
}
19
Source : Extensions.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public static ModbusObject[] ToModbusRegister(this uint 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 : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private void SetKeepAlive()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return;
bool isEnabled = keepAlive.TotalMilliseconds > 0;
uint interval = keepAlive.TotalMilliseconds > uint.MaxValue ? uint.MaxValue : (uint)keepAlive.TotalMilliseconds;
int uintSize = sizeof(uint);
byte[] config = new byte[uintSize * 3];
Array.Copy(BitConverter.GetBytes(isEnabled ? 1U : 0U), 0, config, 0, uintSize);
Array.Copy(BitConverter.GetBytes(interval), 0, config, uintSize * 1, uintSize);
Array.Copy(BitConverter.GetBytes(interval), 0, config, uintSize * 2, uintSize);
tcpClient?.Client?.IOControl(IOControlCode.KeepAliveValues, config, null);
}
19
Source : DataBuffer.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public void SetUInt32(int index, uint 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 AddUInt32(uint value)
{
byte[] blob = BitConverter.GetBytes(value);
InternalSwap(blob);
AddBytes(blob);
}
19
Source : Register.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public static List<Register> Create(uint value, ushort address, bool isInput = false)
{
if (address + 1 > 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 : Printer.cs
with MIT License
from andycb
with MIT License
from andycb
public async Task StoreFileAsync(string filePath, string fileName)
{
this.ValidatePrinterReady();
var modelBytes = File.ReadAllBytes(filePath);
// Start a transfer
this.streamWriter.WriteLine(string.Format(CultureInfo.InvariantCulture, "~{0} {1} 0:/user/{2}", MachineCommands.BeginWriteToSdCard, modelBytes.Count(), fileName));
await this.WaitForPrinterAck().ConfigureAwait(false);
var crcAlg = new Crc32Algorithm(!BitConverter.IsLittleEndian);
var count = 0;
int offset = 0;
var printerStream = this.printerConnection.GetStream();
while (offset < modelBytes.Length)
{
uint crc;
byte[] packet = new byte[packetSizeBytes];
var dataSize = 0u;
if (offset + packetSizeBytes < modelBytes.Length)
{
packet = modelBytes.Skip(offset).Take(packetSizeBytes).ToArray();
var crcBytes = BitConverter.ToUInt32(crcAlg.ComputeHash(packet));
crc = GetBigEndian(crcBytes);
dataSize = packetSizeBytes;
}
else
{
// Every packet needs to be the same size, so zero pad the last one if we need to.
var actualLength = modelBytes.Length - offset;
var data = modelBytes.Skip(offset).Take(actualLength).ToArray();
// The CRC is for the un-padded data.
var crcBytes = BitConverter.ToUInt32(crcAlg.ComputeHash(data));
crc = GetBigEndian(crcBytes);
Array.Copy(data, 0, packet, 0, actualLength);
Array.Fill<byte>(packet, 0x0, actualLength, packetSizeBytes - actualLength);
dataSize = (uint)actualLength;
}
var packetToSend = new List<byte>();
// Always start each packet with four bytes
packetToSend.AddRange(this.fileTransferPrefixBytes);
// Add the count of this packet, the size of the data it in (not counting padding) and the CRC.
packetToSend.AddRange(BitConverter.GetBytes(GetBigEndian((uint)count)));
packetToSend.AddRange(BitConverter.GetBytes(GetBigEndian(dataSize)));
packetToSend.AddRange(BitConverter.GetBytes(crc));
// Finally add thr actual data
packetToSend.AddRange(packet);
// Send the data
printerStream.Write(packetToSend.ToArray());
printerStream.Flush();
offset += packetSizeBytes;
++count;
}
// Tell the printer that we have finished sending the file.
this.streamWriter.WriteLine(string.Format(CultureInfo.InvariantCulture, "~{0}", MachineCommands.EndWriteToSdCard));
await this.WaitForPrinterAck();
}
19
Source : StreamUtils.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public static void WriteUInt32(Stream stream, uint i)
{
byte[] bytes = Convert(BitConverter.GetBytes(i));
stream.Write(bytes, 0, bytes.Length);
}
19
Source : SmartHomeProtocolEncoder.cs
with Apache License 2.0
from anthturner
with Apache License 2.0
from anthturner
internal static byte[] Encrypt(string data)
{
var encryptedMessage = Encrypt(Encoding.ASCII.GetBytes(data));
var lengthBytes = BitConverter.GetBytes((UInt32)encryptedMessage.Length);
if (BitConverter.IsLittleEndian) // this value needs to be in big-endian
lengthBytes = lengthBytes.Reverse().ToArray();
return lengthBytes.Concat(encryptedMessage).ToArray();
}
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 uint ReadUInt32Reverse()
{
return this.ReadReverse<uint>(BitConverter.GetBytes(this.ReadUInt32()));
}
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(uint value)
{
this.WriteReverse(BitConverter.GetBytes(value));
}
19
Source : EncryptionHandler.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private MemoryStream EncryptPackageAgile(byte[] package, ExcelEncryption encryption)
{
var xml= "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n";
xml += "<encryption xmlns=\"http://schemas.microsoft.com/office/2006/encryption\" xmlns:p=\"http://schemas.microsoft.com/office/2006/keyEncryptor/preplacedword\" xmlns:c=\"http://schemas.microsoft.com/office/2006/keyEncryptor/certificate\">";
xml += "<keyData saltSize=\"16\" blockSize=\"16\" keyBits=\"256\" hashSize=\"64\" cipherAlgorithm=\"AES\" cipherChaining=\"ChainingModeCBC\" hashAlgorithm=\"SHA512\" saltValue=\"\"/>";
xml += "<dataIntegrity encryptedHmacKey=\"\" encryptedHmacValue=\"\"/>";
xml += "<keyEncryptors>";
xml += "<keyEncryptor uri=\"http://schemas.microsoft.com/office/2006/keyEncryptor/preplacedword\">";
xml += "<p:encryptedKey spinCount=\"100000\" saltSize=\"16\" blockSize=\"16\" keyBits=\"256\" hashSize=\"64\" cipherAlgorithm=\"AES\" cipherChaining=\"ChainingModeCBC\" hashAlgorithm=\"SHA512\" saltValue=\"\" encryptedVerifierHashInput=\"\" encryptedVerifierHashValue=\"\" encryptedKeyValue=\"\" />";
xml += "</keyEncryptor></keyEncryptors></encryption>";
var encryptionInfo = new EncryptionInfoAgile();
encryptionInfo.ReadFromXml(xml);
var encr = encryptionInfo.KeyEncryptors[0];
var rnd = RandomNumberGenerator.Create();
var s = new byte[16];
rnd.GetBytes(s);
encryptionInfo.KeyData.SaltValue = s;
rnd.GetBytes(s);
encr.SaltValue = s;
encr.KeyValue = new byte[encr.KeyBits / 8];
rnd.GetBytes(encr.KeyValue);
//Get the preplacedword key.
var hashProvider = GetHashProvider(encryptionInfo.KeyEncryptors[0]);
var baseHash = GetPreplacedwordHash(hashProvider, encr.SaltValue, encryption.Preplacedword, encr.SpinCount, encr.HashSize);
var hashFinal = GetFinalHash(hashProvider, BlockKey_KeyValue, baseHash);
hashFinal = FixHashSize(hashFinal, encr.KeyBits / 8);
var encrData = EncryptDataAgile(package, encryptionInfo, hashProvider);
/**** Data Integrity ****/
var saltHMAC=new byte[64];
rnd.GetBytes(saltHMAC);
SetHMAC(encryptionInfo,hashProvider,saltHMAC, encrData);
/**** Verifier ****/
encr.VerifierHashInput = new byte[16];
rnd.GetBytes(encr.VerifierHashInput);
encr.VerifierHash = hashProvider.ComputeHash(encr.VerifierHashInput);
var VerifierInputKey = GetFinalHash(hashProvider, BlockKey_HashInput, baseHash);
var VerifierHashKey = GetFinalHash(hashProvider, BlockKey_HashValue, baseHash);
var KeyValueKey = GetFinalHash(hashProvider, BlockKey_KeyValue, baseHash);
var ms = new MemoryStream();
EncryptAgileFromKey(encr, VerifierInputKey, encr.VerifierHashInput, 0, encr.VerifierHashInput.Length, encr.SaltValue, ms);
encr.EncryptedVerifierHashInput = ms.ToArray();
ms = new MemoryStream();
EncryptAgileFromKey(encr, VerifierHashKey, encr.VerifierHash, 0, encr.VerifierHash.Length, encr.SaltValue, ms);
encr.EncryptedVerifierHash = ms.ToArray();
ms = new MemoryStream();
EncryptAgileFromKey(encr, KeyValueKey, encr.KeyValue, 0, encr.KeyValue.Length, encr.SaltValue, ms);
encr.EncryptedKeyValue = ms.ToArray();
xml = encryptionInfo.Xml.OuterXml;
var byXml = Encoding.UTF8.GetBytes(xml);
ms = new MemoryStream();
ms.Write(BitConverter.GetBytes((ushort)4), 0, 2); //Major Version
ms.Write(BitConverter.GetBytes((ushort)4), 0, 2); //Minor Version
ms.Write(BitConverter.GetBytes((uint)0x40), 0, 4); //Reserved
ms.Write(byXml,0,byXml.Length);
var doc = new CompoundDoreplacedent();
//Add the dataspace streams
CreateDataSpaces(doc);
//EncryptionInfo...
doc.Storage.DataStreams.Add("EncryptionInfo", ms.ToArray());
//...and the encrypted package
doc.Storage.DataStreams.Add("EncryptedPackage", encrData);
ms = new MemoryStream();
doc.Save(ms);
//ms.Write(e,0,e.Length);
return ms;
}
19
Source : EncryptionHandler.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private MemoryStream DecryptAgile(EncryptionInfoAgile encryptionInfo, string preplacedword, long size, byte[] encryptedData, byte[] data)
{
MemoryStream doc = new MemoryStream();
if (encryptionInfo.KeyData.CipherAlgorithm == eCipherAlgorithm.AES)
{
var encr = encryptionInfo.KeyEncryptors[0];
var hashProvider = GetHashProvider(encr);
var hashProviderDataKey = GetHashProvider(encryptionInfo.KeyData);
var baseHash = GetPreplacedwordHash(hashProvider, encr.SaltValue, preplacedword, encr.SpinCount, encr.HashSize);
//Get the keys for the verifiers and the key value
var valInputKey = GetFinalHash(hashProvider, BlockKey_HashInput, baseHash);
var valHashKey = GetFinalHash(hashProvider, BlockKey_HashValue, baseHash);
var valKeySizeKey = GetFinalHash(hashProvider, BlockKey_KeyValue, baseHash);
//Decrypt
encr.VerifierHashInput = DecryptAgileFromKey(encr, valInputKey, encr.EncryptedVerifierHashInput, encr.SaltSize, encr.SaltValue);
encr.VerifierHash = DecryptAgileFromKey(encr, valHashKey, encr.EncryptedVerifierHash, encr.HashSize, encr.SaltValue);
encr.KeyValue = DecryptAgileFromKey(encr, valKeySizeKey, encr.EncryptedKeyValue, encryptionInfo.KeyData.KeyBits / 8, encr.SaltValue);
if (IsPreplacedwordValid(hashProvider, encr))
{
var ivhmac = GetFinalHash(hashProviderDataKey, BlockKey_HmacKey, encryptionInfo.KeyData.SaltValue);
var key = DecryptAgileFromKey(encryptionInfo.KeyData, encr.KeyValue, encryptionInfo.DataIntegrity.EncryptedHmacKey, encryptionInfo.KeyData.HashSize, ivhmac);
ivhmac = GetFinalHash(hashProviderDataKey, BlockKey_HmacValue, encryptionInfo.KeyData.SaltValue);
var value = DecryptAgileFromKey(encryptionInfo.KeyData, encr.KeyValue, encryptionInfo.DataIntegrity.EncryptedHmacValue, encryptionInfo.KeyData.HashSize, ivhmac);
var hmca = GetHmacProvider(encryptionInfo.KeyData, key);
var v2 = hmca.ComputeHash(data);
for (int i = 0; i < v2.Length; i++)
{
if (value[i] != v2[i])
{
throw (new Exception("Dataintegrity key mismatch"));
}
}
int pos = 0;
uint segment = 0;
while (pos < size)
{
var segmentSize = (int)(size - pos > 4096 ? 4096 : size - pos);
var bufferSize = (int)(encryptedData.Length - pos > 4096 ? 4096 : encryptedData.Length - pos);
var ivTmp = new byte[4 + encryptionInfo.KeyData.SaltSize];
Array.Copy(encryptionInfo.KeyData.SaltValue, 0, ivTmp, 0, encryptionInfo.KeyData.SaltSize);
Array.Copy(BitConverter.GetBytes(segment), 0, ivTmp, encryptionInfo.KeyData.SaltSize, 4);
var iv = hashProviderDataKey.ComputeHash(ivTmp);
var buffer = new byte[bufferSize];
Array.Copy(encryptedData, pos, buffer, 0, bufferSize);
var b = DecryptAgileFromKey(encryptionInfo.KeyData, encr.KeyValue, buffer, segmentSize, iv);
doc.Write(b, 0, b.Length);
pos += segmentSize;
segment++;
}
doc.Flush();
return doc;
}
else
{
throw (new SecurityException("Invalid preplacedword"));
}
}
return null;
}
19
Source : ZipFile.Save.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public static bool WriteCentralDirectoryStructure(Stream s,
ICollection<ZipEntry> entries,
uint numSegments,
Zip64Option zip64,
String comment,
ZipContainer container)
{
var zss = s as ZipSegmentedStream;
if (zss != null)
zss.ContiguousWrite = true;
// write to a memory stream in order to keep the
// CDR contiguous
Int64 aLength = 0;
using (var ms = new MemoryStream())
{
foreach (ZipEntry e in entries)
{
if (e.IncludedInMostRecentSave)
{
// this writes a ZipDirEntry corresponding to the ZipEntry
e.WriteCentralDirectoryEntry(ms);
}
}
var a = ms.ToArray();
s.Write(a, 0, a.Length);
aLength = a.Length;
}
// We need to keep track of the start and
// Finish of the Central Directory Structure.
// Cannot always use WriteStream.Length or Position; some streams do
// not support these. (eg, ASP.NET Response.OutputStream) In those
// cases we have a CountingStream.
// Also, we cannot just set Start as s.Position bfore the write, and Finish
// as s.Position after the write. In a split zip, the write may actually
// flip to the next segment. In that case, Start will be zero. But we
// don't know that til after we know the size of the thing to write. So the
// answer is to compute the directory, then ask the ZipSegmentedStream which
// segment that directory would fall in, it it were written. Then, include
// that data into the directory, and finally, write the directory to the
// output stream.
var output = s as CountingStream;
long Finish = (output != null) ? output.ComputedPosition : s.Position; // BytesWritten
long Start = Finish - aLength;
// need to know which segment the EOCD record starts in
UInt32 startSegment = (zss != null)
? zss.CurrentSegment
: 0;
Int64 SizeOfCentralDirectory = Finish - Start;
int countOfEntries = CountEntries(entries);
bool needZip64CentralDirectory =
zip64 == Zip64Option.Always ||
countOfEntries >= 0xFFFF ||
SizeOfCentralDirectory > 0xFFFFFFFF ||
Start > 0xFFFFFFFF;
byte[] a2 = null;
// emit ZIP64 extensions as required
if (needZip64CentralDirectory)
{
if (zip64 == Zip64Option.Never)
{
#if NETCF || Core
throw new ZipException("The archive requires a ZIP64 Central Directory. Consider enabling ZIP64 extensions.");
#else
System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(1);
if (sf.GetMethod().DeclaringType == typeof(ZipFile))
throw new ZipException("The archive requires a ZIP64 Central Directory. Consider setting the ZipFile.UseZip64WhenSaving property.");
else
throw new ZipException("The archive requires a ZIP64 Central Directory. Consider setting the ZipOutputStream.EnableZip64 property.");
#endif
}
var a = GenZip64EndOfCentralDirectory(Start, Finish, countOfEntries, numSegments);
a2 = GenCentralDirectoryFooter(Start, Finish, zip64, countOfEntries, comment, container);
if (startSegment != 0)
{
UInt32 thisSegment = zss.ComputeSegment(a.Length + a2.Length);
int i = 16;
// number of this disk
Array.Copy(BitConverter.GetBytes(thisSegment), 0, a, i, 4);
i += 4;
// number of the disk with the start of the central directory
//Array.Copy(BitConverter.GetBytes(startSegment), 0, a, i, 4);
Array.Copy(BitConverter.GetBytes(thisSegment), 0, a, i, 4);
i = 60;
// offset 60
// number of the disk with the start of the zip64 eocd
Array.Copy(BitConverter.GetBytes(thisSegment), 0, a, i, 4);
i += 4;
i += 8;
// offset 72
// total number of disks
Array.Copy(BitConverter.GetBytes(thisSegment), 0, a, i, 4);
}
s.Write(a, 0, a.Length);
}
else
a2 = GenCentralDirectoryFooter(Start, Finish, zip64, countOfEntries, comment, container);
// now, the regular footer
if (startSegment != 0)
{
// The replacedumption is the central directory is never split across
// segment boundaries.
UInt16 thisSegment = (UInt16) zss.ComputeSegment(a2.Length);
int i = 4;
// number of this disk
Array.Copy(BitConverter.GetBytes(thisSegment), 0, a2, i, 2);
i += 2;
// number of the disk with the start of the central directory
//Array.Copy(BitConverter.GetBytes((UInt16)startSegment), 0, a2, i, 2);
Array.Copy(BitConverter.GetBytes(thisSegment), 0, a2, i, 2);
i += 2;
}
s.Write(a2, 0, a2.Length);
// reset the contiguous write property if necessary
if (zss != null)
zss.ContiguousWrite = false;
return needZip64CentralDirectory;
}
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 : ExcelVBASignature.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private byte[] GetContentHash(ExcelVbaProject proj)
{
//MS-OVBA 2.4.2
var enc = System.Text.Encoding.GetEncoding(proj.CodePage);
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write(enc.GetBytes(proj.Name));
bw.Write(enc.GetBytes(proj.Constants));
foreach (var reference in proj.References)
{
if (reference.ReferenceRecordID == 0x0D)
{
bw.Write((byte)0x7B);
}
if (reference.ReferenceRecordID == 0x0E)
{
//var r = (ExcelVbaReferenceProject)reference;
//BinaryWriter bwTemp = new BinaryWriter(new MemoryStream());
//bwTemp.Write((uint)r.Libid.Length);
//bwTemp.Write(enc.GetBytes(r.Libid));
//bwTemp.Write((uint)r.LibIdRelative.Length);
//bwTemp.Write(enc.GetBytes(r.LibIdRelative));
//bwTemp.Write(r.MajorVersion);
//bwTemp.Write(r.MinorVersion);
foreach (byte b in BitConverter.GetBytes((uint)reference.Libid.Length)) //Length will never be an UInt with 4 bytes that aren't 0 (> 0x00FFFFFF), so no need for the rest of the properties.
{
if (b != 0)
{
bw.Write(b);
}
else
{
break;
}
}
}
}
foreach (var module in proj.Modules)
{
var lines = module.Code.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
if (!line.StartsWith("attribute", StringComparison.OrdinalIgnoreCase))
{
bw.Write(enc.GetBytes(line));
}
}
}
var buffer = (bw.BaseStream as MemoryStream).ToArray();
var hp = System.Security.Cryptography.MD5.Create();
return hp.ComputeHash(buffer);
}
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 : ExtensionMethods.cs
with MIT License
from araghon007
with MIT License
from araghon007
private static byte[] UInt32ToBytes(uint value)
{
return BitConverter.GetBytes(value);
}
19
Source : UsbBotMini.cs
with MIT License
from architdate
with MIT License
from architdate
private int SendInternal(byte[] buffer)
{
if (writer == null)
throw new Exception("USB writer is null, you may have disconnected the device during previous function");
uint pack = (uint)buffer.Length + 2;
var ec = writer.Write(BitConverter.GetBytes(pack), 2000, out _);
if (ec != ErrorCode.None)
{
Disconnect();
throw new Exception(UsbDevice.LastErrorString);
}
ec = writer.Write(buffer, 2000, out var l);
if (ec != ErrorCode.None)
{
Disconnect();
throw new Exception(UsbDevice.LastErrorString);
}
return l;
}
19
Source : NTRAPIFramework.cs
with MIT License
from architdate
with MIT License
from architdate
private void SendPacket(uint type, uint cmd, IReadOnlyList<uint>? args, uint dataLen)
{
_currentSeq += 1000;
var buf = new byte[84];
var t = 12;
BitConverter.GetBytes(0x12345678).CopyTo(buf, 0);
BitConverter.GetBytes(_currentSeq).CopyTo(buf, 4);
BitConverter.GetBytes(type).CopyTo(buf, 8);
BitConverter.GetBytes(cmd).CopyTo(buf, 12);
for (var i = 0; i < 16; i++)
{
t += 4;
uint arg = 0;
if (args != null)
arg = args[i];
BitConverter.GetBytes(arg).CopyTo(buf, t);
}
BitConverter.GetBytes(dataLen).CopyTo(buf, t + 4);
var stream = _netStream ?? throw new ArgumentNullException(nameof(_netStream));
stream.Write(buf, 0, buf.Length);
}
See More Examples