/// <summary> /// Initializes a new instance of the <see cref="AbstractIPAddressRange"/> class. /// </summary> /// <param name="head">the range head (lowest valued <see cref="IPAddress" />)</param> /// <param name="tail">the range tail (highest valued <see cref="IPAddress" />)</param> protected AbstractIPAddressRange([NotNull] IPAddress head, [NotNull] IPAddress tail) { #region defense if (head == null) { throw new ArgumentNullException(nameof(head)); } if (tail == null) { throw new ArgumentNullException(nameof(tail)); } if (!IPAddressUtilities.ValidAddressFamilies.Contains(head.AddressFamily)) { throw new ArgumentException($"{nameof(head)} must have an address family equal to {string.Join(", ", IPAddressUtilities.ValidAddressFamilies)}", nameof(head)); } if (!IPAddressUtilities.ValidAddressFamilies.Contains(tail.AddressFamily)) { throw new ArgumentException($"{nameof(tail)} must have an address family equal to {string.Join(", ", IPAddressUtilities.ValidAddressFamilies)}", nameof(tail)); } if (head.AddressFamily != tail.AddressFamily) { throw new InvalidOperationException($"{nameof(head)} and {nameof(tail)} must have matching address families"); } if (!tail.IsGreaterThanOrEqualTo(head)) { throw new InvalidOperationException($"{nameof(tail)} must be greater or equal to {nameof(head)}"); } #endregion // end: defense this.Head = head; this.Tail = tail; this.Length = CalculateLength(); BigInteger CalculateLength() { // convert big endian (network byte order) difference result to a 0x00 prefixed byte array for converting to an unsigned BigInteger var differenceBytes = ByteArrayUtils.SubtractUnsignedBigEndian(tail.GetAddressBytes(), head.GetAddressBytes()); var differenceBytesLength = differenceBytes.Length; var unsignedLittleEndianBytes = new byte[differenceBytesLength + 1]; // one greater so trailing byte is always 0x00 for (var i = 0; i < differenceBytesLength; i++) { unsignedLittleEndianBytes[differenceBytesLength - 1 - i] = differenceBytes[i]; } return(new BigInteger(unsignedLittleEndianBytes) + 1); // a rare but valid use of BigInteger; } }
/// <summary> /// Gets the http headers from a list of CoAP options. The method iterates /// over the list looking for a translation of each option in the predefined /// mapping. This process ignores the proxy-uri and the content-type because /// they are managed differently. If a mapping is present, the content of the /// option is mapped to a string accordingly to its original format and set /// as the content of the header. /// </summary> /// <param name="optionList"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public static NameValueCollection GetHttpHeaders(IEnumerable <Option> optionList) { if (optionList == null) { throw ThrowHelper.ArgumentNull("optionList"); } NameValueCollection headers = new NameValueCollection(); foreach (Option opt in optionList) { // skip content-type because it should be translated while handling // the payload; skip proxy-uri because it has to be translated in a // different way if (opt.Type == OptionType.ContentType || opt.Type == OptionType.ProxyUri) { continue; } string headerName; if (!_Coap2HttpHeader.TryGetValue(opt.Type, out headerName)) { continue; } // format the value string headerValue = null; OptionFormat format = Option.GetFormatByType(opt.Type); if (format == OptionFormat.Integer) { headerValue = opt.IntValue.ToString(); } else if (format == OptionFormat.String) { headerValue = opt.StringValue; } else if (format == OptionFormat.Opaque) { headerValue = ByteArrayUtils.ToHexString(opt.RawValue); } else { continue; } // custom handling for max-age // format: cache-control: max-age=60 if (opt.Type == OptionType.MaxAge) { headerValue = "max-age=" + headerValue; } headers[headerName] = headerValue; } return(headers); }
public override void SyncMovementHistory(RpcArgs args) { var bytes = args.GetNext <Byte[]>(); List <MovementHistoryItem> historyFrames = (List <MovementHistoryItem>)ByteArrayUtils.ByteArrayToObject(bytes); if (IsLocalOwner) { AuthoritativeMovementHistory.AddRange(historyFrames); } }
public void Sha384_ShouldProduceValidHash() { var sourceData = "Hello crazy world"; var sourceDataBinary = Encoding.UTF8.GetBytes(sourceData); var resultHash = _crypto.Sha384(sourceDataBinary); var resultHashString = ByteArrayUtils.ByteArrayToHexString(resultHash); Assert.AreEqual(resultHashString, "00d025cd5118e8b21b7b01142e59d37cbeac7db6e75a3ae41795f07bbb4f8dfd0bce48f81a0b0b3df50c8b6e05c37eea"); }
public void TestDecodeScriptHash() { var targetAddress = "2N8bXfrWTzqZoV89dosge2JxvE38VnHurqD"; var temp = targetAddress.Base58CheckDecode().Skip(1).ToArray(); byte OP_HASH160 = 0xa9; byte OP_EQUAL = 0x87; var outputKeyScript = ByteArrayUtils.ConcatBytes(new byte[] { OP_HASH160, 0x14 }, ByteArrayUtils.ConcatBytes(temp, new byte[] { OP_EQUAL })); var hex = Base16.Encode(outputKeyScript).ToLower(); }
public void Sha512_ShouldProduceValidHash() { var sourceData = "Hello crazy world"; var sourceDataBinary = Encoding.UTF8.GetBytes(sourceData); var resultHash = _crypto.Sha512(sourceDataBinary); var resultHashString = ByteArrayUtils.ByteArrayToHexString(resultHash); Assert.AreEqual(resultHashString, "9f9ddccd74997c8fe237d5fb20b92b57503f17a7d26c5a7dac50fe51c4f78f85a83dc9db9f0ddc02e46434ff2c645feae646102e01dbb65833189a8ba1e3e5df"); }
public override void SyncInputs(RpcArgs args) { var bytes = args.GetNext <Byte[]>(); List <InputFrame> networkInputFrames = (List <InputFrame>)ByteArrayUtils.ByteArrayToObject(bytes); if (networkObject.IsServer) { FramesToPlay.AddRange(networkInputFrames); } }
protected override string DeriveAddress(PhantasmaKeys keys) { ECPoint pKey = ECCurve.Secp256k1.G * keys.PrivateKey; var publicKey = pKey.EncodePoint(true); var bytes = ByteArrayUtils.ConcatBytes(new byte[] { 0 }, publicKey.SHA256().RIPEMD160()); return(bytes.Base58CheckEncode()); }
public void Sha256_ShouldProduceValidHash() { var sourceData = "Hello crazy world"; var sourceDataBinary = Encoding.UTF8.GetBytes(sourceData); var resultHash = _crypto.Sha256(sourceDataBinary); var resultHashString = ByteArrayUtils.ByteArrayToHexString(resultHash); Assert.AreEqual(resultHashString, "2907d7ba4e806c96a8ab89b03be1745b5beb5568a109af9287acd71707e79f2d"); }
public PhantasmaKeys(byte[] privateKey) { Throw.If(privateKey.Length != PrivateKeyLength, $"privateKey should have length {PrivateKeyLength}"); this.PrivateKey = new byte[PrivateKeyLength]; ByteArrayUtils.CopyBytes(privateKey, 0, PrivateKey, 0, PrivateKeyLength); this.PublicKey = Ed25519.PublicKeyFromSeed(privateKey); this.Address = Address.FromKey(this); }
public void SubtractUnsignedLittleEndian_SignedOperation_Throws_InvalidOperationException_Test() { // Arrange var left = new byte[] { 0x00 }; var right = new byte[] { 0x00, 0x0F }; // Act // Assert Assert.Throws <InvalidOperationException>(() => ByteArrayUtils.SubtractUnsignedLittleEndian(left, right)); }
public string GetOutput(byte[] bytes) { if (bytes == null) { return(null); } var bytesReversed = ByteArrayUtils.ReverseBytes3210(bytes); return(ByteArrayUtils.ByteArrayAsInt32(bytesReversed)); }
public static Address FromInterop(byte platformID, byte[] publicKey) { Throw.If(publicKey == null || publicKey.Length != 33, "public key is invalid"); Throw.If(platformID < 1, "invalid platform id"); var bytes = new byte[LengthInBytes]; bytes[0] = (byte)(AddressKind.Interop + platformID - 1); ByteArrayUtils.CopyBytes(publicKey, 0, bytes, 1, publicKey.Length); return(new Address(bytes)); }
public string GetOutput(byte[] bytes) { if (bytes == null) { return(null); } var bytesNormalized = ByteArrayUtils.NormalizeTo2Bytes(bytes); return(ByteArrayUtils.ByteArrayAsUInt16(bytesNormalized)); }
public string GetOutput(byte[] bytes) { if (bytes == null) { return(null); } var bytesReversed = ByteArrayUtils.ReverseBytes2301(bytes); return(ByteArrayUtils.ByteArrayAsFloat(bytesReversed)); }
/// <summary> /// Finds the observe relation by token. /// </summary> public ObserveRelation GetObserveRelation(Byte[] token) { foreach (ObserveRelation relation in _relations) { if (ByteArrayUtils.Equals(token, relation.Exchange.Request.Token)) { return(relation); } } return(null); }
public string ToWIF() { byte[] data = new byte[34]; data[0] = 0x80; ByteArrayUtils.CopyBytes(PrivateKey, 0, data, 1, 32); data[33] = 0x01; string wif = data.Base58CheckEncode(); Array.Clear(data, 0, data.Length); return(wif); }
public static Address EncodeAddress(string addressText) { Throw.If(!IsValidAddress(addressText), "invalid ethereum address"); var input = addressText.Substring(2); var bytes = Base16.Decode(input); var pubKey = new byte[33]; ByteArrayUtils.CopyBytes(bytes, 0, pubKey, 0, bytes.Length); return(Cryptography.Address.FromInterop(EthereumID, pubKey)); }
public KeyPair(byte[] privateKey) { Throw.If(privateKey.Length != PrivateKeyLength, $"privateKey should have length {PrivateKeyLength}"); this.PrivateKey = new byte[PrivateKeyLength]; ByteArrayUtils.CopyBytes(privateKey, 0, PrivateKey, 0, PrivateKeyLength); var publicKey = Ed25519.PublicKeyFromSeed(privateKey); this.Address = new Address(publicKey); }
public static Address EncodeAddress(string addressText) { Throw.If(!IsValidAddress(addressText), "invalid neo address"); var scriptHash = addressText.Base58CheckDecode(); var pubKey = new byte[33]; ByteArrayUtils.CopyBytes(scriptHash, 0, pubKey, 0, scriptHash.Length); return(Cryptography.Address.FromInterop(NeoID, pubKey)); }
public static KeyPair FromWIF(string wif) { Throw.If(wif == null, "WIF required"); byte[] data = wif.Base58CheckDecode(); Throw.If(data.Length != 34 || data[0] != 0x80 || data[33] != 0x01, "Invalid WIF format"); byte[] privateKey = new byte[32]; ByteArrayUtils.CopyBytes(data, 1, privateKey, 0, privateKey.Length); Array.Clear(data, 0, data.Length); return(new KeyPair(privateKey)); }
private static NetCrypto.ECPoint ECPointDecode(byte[] pubKey, ECDsaCurve curve) { ECCurve usedCurve = ECC.ECCurve.Secp256r1; switch (curve) { case ECDsaCurve.Secp256r1: // default break; case ECDsaCurve.Secp256k1: usedCurve = ECC.ECCurve.Secp256k1; break; } ; byte[] bytes; if (pubKey.Length == 32) { pubKey = ByteArrayUtils.ConcatBytes(new byte[] { 2 }, pubKey.Skip(1).ToArray()); } if (pubKey.Length == 33 && (pubKey[0] == 0x02 || pubKey[0] == 0x03)) { try { bytes = ECC.ECPoint.DecodePoint(pubKey, usedCurve).EncodePoint(false).Skip(1).ToArray(); } catch { throw new ArgumentException(); } } else if (pubKey.Length == 65 && pubKey[0] == 0x04) { bytes = pubKey.Skip(1).ToArray(); } else if (pubKey.Length != 64) { throw new ArgumentException(); } else { bytes = pubKey; } return(new NetCrypto.ECPoint { X = bytes.Take(32).ToArray(), Y = bytes.Skip(32).ToArray() }); }
public void CreateByteArray_Test(int length, byte element) { // Arrange // Act var result = ByteArrayUtils.CreateByteArray(length, element); // Assert Assert.IsType <byte[]>(result); Assert.Equal(length, result.Length); Assert.All(result, b => b.Equals(element)); }
void FixedUpdate() { currentFrame++; IsLocalOwner = networkObject.MyPlayerId == networkObject.inputOwnerId; //find the input listener that corresponds with this guy if (inputListener == null) { inputListener = FindObjectsOfType <InputListener>() .FirstOrDefault(x => x.networkObject.Owner.NetworkId == this.networkObject.inputOwnerId); } //Server sets position on the network if (!networkObject.IsServer && !IsLocalOwner) { transform.position = networkObject.position; } //Authoritative movement / client side prediction if (networkObject.IsServer || IsLocalOwner) { if (inputListener != null && inputListener.FramesToPlay.Count() > 0) { var frame = inputListener.FramesToPlay[0]; PerformMovement(frame); LocalMovementHistory.Add(GetMovementHistoryItem(frame)); inputListener.FramesToPlay.RemoveAt(0); } } if (IsLocalOwner) { PerformMovementReconciliation(); } if (networkObject.IsServer) { networkObject.position = transform.position; if (currentFrame % FrameSyncRate == 0) { var bytes = ByteArrayUtils.ObjectToByteArray(LocalMovementHistory); networkObject.SendRpc(RPC_SYNC_MOVEMENT_HISTORY, Receivers.All, new object[] { bytes }); LocalMovementHistory.Clear(); } } //hack to allow you to teleport on local client only if (Input.GetKeyDown("x")) { var amount = UnityEngine.Random.Range(-10, -1); transform.Translate(new Vector3(UnityEngine.Random.Range(-5, -1), 0, UnityEngine.Random.Range(1, 5))); } }
public static byte[] FromHumanKey(string key, bool forceSep = false) { if (string.IsNullOrEmpty(key)) { return(new byte[0]); } if (key.Contains(".")) { var temp = key.Split('.'); byte[] result = new byte[0]; foreach (var entry in temp) { var sub = FromHumanKey(entry, true); result = ByteArrayUtils.ConcatBytes(result, sub); } } try { var address = Address.FromText(key); return(address.PublicKey); } catch { } if (key.StartsWith("0x")) { return(Base16.Decode(key.Substring(0))); } if (key.StartsWith("[") && key.EndsWith("[")) { key = key.Substring(1, key.Length - 2); var num = BigInteger.Parse(key); var result = num.ToByteArray(); result = ByteArrayUtils.ConcatBytes(new byte[] { (byte)'<' }, result); result = ByteArrayUtils.ConcatBytes(result, new byte[] { (byte)'>' }); } { var result = global::System.Text.Encoding.ASCII.GetBytes(key); if (forceSep) { result = ByteArrayUtils.ConcatBytes(new byte[] { (byte)'{' }, result); result = ByteArrayUtils.ConcatBytes(result, new byte[] { (byte)'}' }); } return(result); } }
public byte[] GetFrameData(DateTime time) { byte[] jpgBuffer = null; try { //parse header int pos = -1; if (!_timePosDictionary.TryGetValue(time, out pos)) { return(null); } //Read Frame Header: int linelimit = 0; //content Length string contentLengthString = ByteArrayUtils.GetPrefixedLine( _buffer, ContentLengthPrefix, pos, 400, Encoding.ASCII, out linelimit); //Hash code //string hashString = ByteArrayUtils.GetPrefixedLine( // _buffer, ContentHashPrefix, linelimit, 400, Encoding.ASCII, out linelimit); //string privatehashString = ByteArrayUtils.GetPrefixedLine( // _buffer, ContentPrivateHashPrefix, linelimit, 400, Encoding.ASCII, out linelimit); //use linelimit as start point to copy the jpeg data int contentLength = int.Parse(contentLengthString); //This should work always, but its possible that the bytes 0x00 and 0x10 could be different sometimes. //keep an eye out for weird behaviour. See http://www.garykessler.net/library/file_sigs.html // // Gerrr Mark // //byte[] jpegHeaderpattern = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46 }; byte?[] jpegHeaderpattern = new byte?[] { 0xFF, null, 0xFF, null }; int datastart = ByteArrayUtils.IndexOf(_buffer, jpegHeaderpattern, linelimit, 400); if (datastart == -1) { DebugMessageLogger.LogEvent("Search for jpeg header failed; MultipartVideoDecoder.GetAllFrames()"); } //return bytes jpgBuffer = new byte[contentLength]; Array.Copy(_buffer, datastart, jpgBuffer, 0, contentLength); } catch (Exception ee) { DebugMessageLogger.LogError(ee); } return(jpgBuffer); }
private byte[] Concat(byte[] v, byte p, byte[] providedData) { byte[] res = new byte[v.Length + 1 + (providedData == null ? 0 : providedData.Length)]; ByteArrayUtils.CopyBytes(v, 0, res, 0, v.Length); res[v.Length] = p; if (providedData != null) { ByteArrayUtils.CopyBytes(providedData, 0, res, v.Length + 1, providedData.Length); } return(res); }
public void DefaultMacAddress_Test() { // Arrange var expected = Enumerable.Repeat((byte)0xFF, 6) .ToArray(); // Act var defaultMacAddress = MacAddress.DefaultMacAddress; // Assert Assert.NotNull(defaultMacAddress); Assert.Equal(0, ByteArrayUtils.CompareUnsignedBigEndian(expected, defaultMacAddress.GetAddressBytes())); }
private void Instantiate(byte[] seed, byte[] personalizationString) { reseedCounter = 1; var seedMaterial = personalizationString == null ? seed : ByteArrayUtils.ConcatBytes(seed, personalizationString); for (int i = 0; i < OutlenBytes; ++i) { key[i] = 0; v[i] = 0x01; } Update(seedMaterial); }
/// <summary> /// Continuation of <see cref="ProcessClient"/> /// </summary> /// <param name="data">List of bytes read from the connection</param> /// <param name="client">the client that it was read from</param> public void ProcessData(List <byte> data, TcpClient client) { WraperHeader wh = ByteArrayUtils.FromByteArray <WraperHeader>(data.ToArray()); if (!CheckRequest(wh)) { return; } Request req = RequestFactory.Factory(wh); req.Client = client; Runner.Start(req); }