// Use this for initialization void Start() { editorUserS.selection_menu_displayed = true; // Hex[] keys = editorHexManagerS.hex_dict.Keys.toArray();; Hex[] keys = new Hex[editorHexManagerS.hex_dict.Keys.Count]; editorHexManagerS.hex_dict.Keys.CopyTo(keys, 0); int size = keys.Length; float interval = (Mathf.PI * 2)/size; for(int i = 0; i < size; ++i) { float x = Mathf.Cos(interval*i + (Mathf.PI/2))*radial_distance + transform.position.x; float z = ((Mathf.Sin(interval*i + (Mathf.PI/2))*radial_distance)/1.16F) + transform.position.z; GameObject new_hex = (GameObject) Instantiate(editorHexManagerS.hex_dict[keys[i]], new Vector3(x, 5 + (.01F * i) + .01F, z), Quaternion.identity); editorHexS new_hex_script = (editorHexS) new_hex.AddComponent("editorHexS"); new_hex_script.hex_type = keys[i]; new_hex_script.menu_item = true; new_hex_script.menu_item_num = i; new_hex.transform.parent = transform; } }
public void Create_World_And_Hexes() { var race = new Race { Name = "Default Race" }; var nation = new Nation { Name = "Default Nation", Race = race }; var user = new User { Email = "*****@*****.**", FirstName = "Jamie", LastName = "Fraser", OpenId = "http://jamief00.myopenid.com/" }; var world = new World { Height = 100, Width = 100, Name = "Default World" }; var game = new Game { Name = "Default Game", Started = DateTime.Now, GameWorld = world}; var gameSession = new GameSession { EnteredGame = DateTime.Now, Nation = nation, Game = game, User = user }; using (var tran = _dataContext.WorldRepository.Session.BeginTransaction()) { _dataContext.RaceRepository.Save(race); _dataContext.NationRepository.Save(nation); _dataContext.UserRepository.Save(user); _dataContext.GameRepository.Save(game); _dataContext.WorldRepository.Save(world); _dataContext.GameSessionRepository.Save(gameSession); for (var y = 1; y <= world.Width; y++) { for (var x = 1; x <= world.Height; x++) { var hex = new Hex { World = world, HexType = HexType.Grass, X = x, Y = y }; _dataContext.HexRepository.Save(hex); } } tran.Commit(); } }
public Piece(PieceType type, Player owner) { Type = type; Owner = owner; Hex = null; CanMove = true; }
public virtual void AddHex(Hex child) { if (Hexes == null) Hexes = new List<Hex>(); child.World = this; Hexes.Add(child); }
public LocationPoint(Hex attachingHex) { attachedHex = new List<Hex>(); edges = new List<Edge>(); attachedHex.Add(attachingHex); Harbor = SeaHarbor.NotHarbor; }
public static int distance(Hex h1, Hex h2) { return (int)(Math.Abs(h1.axialCoordinates.X - h2.axialCoordinates.X) + Math.Abs(h1.axialCoordinates.Y - h2.axialCoordinates.Y) + Math.Abs(h1.axialCoordinates.X + h1.axialCoordinates.Y - h2.axialCoordinates.X - h2.axialCoordinates.Y)) / 2; }
public Entity ReplaceTilePosition(Hex newPosition) { var componentPool = GetComponentPool(ComponentIds.TilePosition); var component = (TilePositionComponent)(componentPool.Count > 0 ? componentPool.Pop() : new TilePositionComponent()); component.position = newPosition; ReplaceComponent(ComponentIds.TilePosition, component); return this; }
public static float GetDistance(Hex a, Hex b) { Cube ca = a.ToCube(); Cube cb = b.ToCube(); return Cube.GetDistance(ca, cb); }
public static List<Hex> GetConnectedSeas(MapCM map, int playerID, Hex h, int moveLimit, bool is_possible_to_attack_enemy) { List<Hex> res = new List<Hex>(); res.Add(h); _GetConnectedSeas(map, playerID, h, moveLimit, res, is_possible_to_attack_enemy); return res; }
static void CodeDevice(string portName, string deviceName, Hex code, string[] args) { ErrorCode error; int[] pins; switch (deviceName) { case "pic18f": pins = GetPins(args, 2, 4); if (pins == null) return; error = ProgrammerFactory.ProgramPic(portName, code, deviceName, pins[0], pins[1], pins[2], pins[3]); break; case "cc25": pins = GetPins(args, 2, 3); if (pins == null) return; error = ProgrammerFactory.ProgramCC2530(portName, code, deviceName, pins[0], pins[1], pins[2]); break; default: Console.WriteLine("ERROR Device not supported."); ShowHelp(); return; } if (error != ErrorCode.NoError) Console.WriteLine("ERROR " + error.ToString()); }
public void Deactivate() { gameObject.SetActive(false); habitat = null; active = false; }
public override bool Add(Hex h) { if (!base.Add(h)) return false; ColorTable.Add(h, Color.Black); return true; }
public static MapObject GetMapObject(int start, MapObjectType objType, byte[] bytes, Hex[] hexes, out int newStart) { switch (objType) { //case MapObjectType.Item: // break; case MapObjectType.Critter: return new Critter(start, bytes, hexes, criNames, itemsProtoNames, out newStart); case MapObjectType.Scenery: return new Scenery(start, bytes, hexes, sceNames, itemsProtoNames, out newStart); case MapObjectType.Wall: return new Wall(start, bytes, hexes, wallNames, itemsProtoNames, out newStart); //case MapObjectType.Tiles: // break; case MapObjectType.Misc: return new Misc(start, bytes, hexes, miscNames, itemsProtoNames, out newStart); //case MapObjectType.Interface: // break; //case MapObjectType.Invent: // break; //case MapObjectType.Head: // break; //case MapObjectType.Backgrnd: // break; //case MapObjectType.Skilldex: // break; //default: // break; } newStart = start + 88; return null; }
public static List<Hex> findPath(Hex start, Hex goal) { Dictionary<Hex,int> distances = new Dictionary<Hex,int> (); Dictionary<Hex,Hex> previous = new Dictionary<Hex,Hex> (); List<Hex> queue = new List<Hex> { start }; distances [start] = 0; while (queue.Count > 0) { queue.Sort ((a, b) => (distances[a] + Hex.Distance (a, goal)) - (distances[b] + Hex.Distance (b, goal))); Hex current = queue [0]; queue.RemoveAt (0); if (current == goal) { List<Hex> path = new List<Hex> {goal}; while (previous.ContainsKey (path [path.Count - 1])) { path.Add (previous [path [path.Count - 1]]); } path.Reverse (); return path; } for (int i = 0; i < 6; i++) { Hex neighbor = Hex.Neighbor (current, i); if (!distances.ContainsKey (neighbor) || distances [current] + 1 < distances [neighbor]) { distances [neighbor] = distances [current] + 1; previous [neighbor] = current; queue.Add (neighbor); } } } throw new UnityException (); }
public void Activate(Critter newCritter, Hex newHab) { critter = newCritter; habitat = newHab; warnControl = FindObjectOfType<WarningsController>(); }
public void SetHex(GraphicCampo graphicCampo, Hex hex) { m_hex = hex; m_graphicCampo = graphicCampo; q = hex.q; r = hex.r; }
public override Unit PlayCardOnHex(Card card, Hex hex, string id) { CardHistory.Add(card); GuiControl.AddCardToHistory(card); // TODO Clean up this method to better handle multiple card types. if(typeof(EntityCard).IsAssignableFrom(card.GetType())) { EntityCard eCard = (EntityCard) card; GameObject go = (GameObject) Instantiate(UnitPrefab, Vector3.zero, Quaternion.identity); Unit unit = go.GetComponent<Unit>(); unit.Id = id; unit.FromCard(eCard); unit.Hex = hex; unit.transform.position = hex.transform.position; hex.Unit = unit; Units.Add(unit); unit.Team = MyTurn() ? Team.ME : Team.ENEMY; if(MyTurn() && ThisPlayer.Hand.Count != 0) { // TODO Find a better way to sort this ThisPlayer.PlayCard(); } card.OnPlay(new StateObject(Units, hex, null, MyTurn() ? ThisPlayer : EnemyPlayer, MyTurn() ? EnemyPlayer : ThisPlayer)); return unit; } else { if(MyTurn() && ThisPlayer.Hand.Count != 0) { // TODO Find a better way to sort this ThisPlayer.PlayCard(); } card.OnPlay(new StateObject(Units, hex, null, MyTurn() ? ThisPlayer : EnemyPlayer, MyTurn() ? EnemyPlayer : ThisPlayer)); return null; } }
public MoveNavy() : base() { } //JSON Constructor public MoveNavy(Hex from, Hex to, int count) : base() { this.from = from; this.to = to; this.count = count; }
/*public void PathFinding(Hex start) { Queue<Hex> frontier = new Queue<Hex>(); frontier.Enqueue(start); Dictionary<Hex, bool> visitado = new Dictionary<Hex, bool>(); foreach (Hex hex in m_hexagons) { visitado[hex] = false; } visitado[start] = true; while (frontier.Count != 0) { Hex current = frontier.Peek(); frontier.Dequeue(); foreach (Hex hex in current.vizinhos) { if (visitado[hex] == false) { frontier.Enqueue(hex); visitado[hex] = true; Debug.Log(hex); } } } }*/ public void PathFinding(Hex start, Hex destino) { Queue<Hex> frontier = new Queue<Hex>(); frontier.Enqueue(start); Dictionary<Hex, Hex> came_from = new Dictionary<Hex, Hex>(); Hex hexnulo = new Hex(100, 100); foreach (Hex hex in m_hexagons) { came_from[hex] = hexnulo; } //came_from[start] = new Hex(100, 100); while (frontier.Count != 0) { Hex current = frontier.Peek(); frontier.Dequeue(); foreach (Hex hex in current.vizinhos) { if (came_from[hex] == hexnulo) { frontier.Enqueue(hex); came_from[hex] = current; } } } Hex atual = destino; List<Hex> path = new List<Hex>(); path.Add(atual); while (atual != start) { atual = came_from[atual]; path.Add(atual); } path.Reverse(); foreach (Hex hex in path) { At(hex.q, hex.r).estaVazio = false; } }
public HexVisual(Point2D point, Hex hex) : base(point) { _Hex = hex; Init(); InitHex(); }
/// <summary> /// Calculates the hex value. /// </summary> /// <returns> /// The hex value. /// </returns> /// <param name='hex'> /// Hex. /// </param> int CalculateHexValue(Hex hex) { if(hex.Unit != null) { if(hex.Unit.Team == player.Team || hex.Unit.Team == 0) { return int.MinValue; } else { return int.MaxValue - hex.Unit.Attack; } } else { Dictionary<Flag, int> flags; if(isAggressive) { flags = getEnemyOrNeutralFlagValues(); } else { flags = getFriendlyFlagValues(); } Flag flag = null; foreach(Flag f in flags.Keys) { if(flag == null) flag = f; else { if(flags[f] > flags[flag]) { flag = f; } } } return flags[flag] - Mathf.FloorToInt(hex.Distance(flag.Hex)); } }
public static void EqualHex(String name, Hex a, Hex b) { if (!(a.q == b.q && a.s == b.s && a.r == b.r)) { Tests.Complain(name); } }
float y_offset = 1.622f; //1.89f; #endregion Fields #region Methods // Finds the most efficient path between two hexes, using the cost of the edges between the edges as the evaluator public List<Hex> AStarFindPath(Hex start, Hex finish, int maximum_cost_allowed, Faction faction) { // Reset hex search scores resetCellSearchScores(); List<Hex> closedSet = new List<Hex>(); List<Hex> openSet = new List<Hex>(); openSet.Add(start); start.came_from = null; start.g_score = 0; // Cost of best known path start.f_score = start.g_score + estimatedCost(start.coordinate, finish.coordinate); // Estimated cost of path from start to finish // Keep going until openset is empty while (openSet.Count > 0) { openSet.Sort(); Hex current = openSet[0]; // Check if we found the goal if (current == finish && current.g_score <= maximum_cost_allowed) { return constructPath(current, start); } openSet.Remove(current); closedSet.Add(current); foreach (Edge neighbourEdge in current.neighbours) { int tentative_g_score = current.g_score + neighbourEdge.GetCost(faction); // Check if have exceeded our allowed movement if (current.g_score >= maximum_cost_allowed || (closedSet.Contains(neighbourEdge.destination) && tentative_g_score >= neighbourEdge.destination.g_score)) { continue; } if (!openSet.Contains(neighbourEdge.destination) || tentative_g_score < neighbourEdge.destination.g_score) { neighbourEdge.destination.came_from = current; neighbourEdge.destination.g_score = tentative_g_score; neighbourEdge.destination.f_score = neighbourEdge.destination.g_score + estimatedCost(neighbourEdge.destination.coordinate, finish.coordinate); if (!openSet.Contains(neighbourEdge.destination)) { openSet.Add(neighbourEdge.destination); neighbourEdge.destination.came_from = current; } } } } // Return failure Debug.Log("Failed to find path between " + start.coordinate + " and " + finish.coordinate); return new List<Hex>(); }
public void Activate(Hex hab) { gameObject.SetActive(true); InfoPanel.SetCurrentState(InfoPanel.panelState.GROWTH); active = true; Populate(hab); }
public StateObject(List<Unit> units, Hex mainhex, Hex secondaryHex, Player caster, Player opponent) { Units = units; MainHex = mainhex; SecondaryHex = secondaryHex; Caster = caster; Opponent = opponent; }
public void MoveNetworkUnit(Unit unit, Hex hex) { System.Object[] args = new System.Object[3]; args[0] = unit.Id.ToString(); args[1] = Mathf.FloorToInt(hex.GridPosition.x); args[2] = Mathf.FloorToInt(hex.GridPosition.y); NetworkPhoton.RPC("ReceiveNetworkUnitMove", PhotonTargets.All, args); }
public static Hex Add( Hex h, Hex a ) { int x = h.x + a.x; int y = h.y + a.y; int z = h.z + a.z; return new Hex( x, y, z ); }
public MoveToHexTask(MobileMapItem mobileMapItem, Hex target) : base(mobileMapItem) { _mobileMapItem = mobileMapItem; _target = target; _pathFinding = new PathFinding(mobileMapItem.World); RecalculatePath(); }
public void Activate() { clickedHex = null; MapController.hexSelected = null; currentState = state.ACTIVE; toggle.SetButtonState(true); }
private int[] cost = new int[3]; // The cost of traversing this edge. Some hexes are slower to move through (Swamps). #endregion Fields #region Constructors // Units don't allow enemy units to traverse next to the unit (area of control). public Edge(Hex destination_hex, Hex source_hex, int movementCost) { destination = destination_hex; source = source_hex; cost[0] = movementCost; cost[1] = movementCost; cost[2] = movementCost; }
public void Teardown() { hex = null; }
public override void PerformTest() { byte[] resBuf = new byte[digest.GetDigestSize()]; for (int i = 0; i < input.Length - 1; i++) { byte[] m = toByteArray(input[i]); vectorTest(digest, i, resBuf, m, Hex.Decode(results[i])); } byte[] lastV = toByteArray(input[input.Length - 1]); byte[] lastDigest = Hex.Decode(results[input.Length - 1]); vectorTest(digest, input.Length - 1, resBuf, lastV, Hex.Decode(results[input.Length - 1])); // // clone test // digest.BlockUpdate(lastV, 0, lastV.Length / 2); // clone the Digest IDigest d = cloneDigest(digest); digest.BlockUpdate(lastV, lastV.Length / 2, lastV.Length - lastV.Length / 2); digest.DoFinal(resBuf, 0); if (!AreEqual(lastDigest, resBuf)) { Fail("failing clone vector test", results[results.Length - 1], Hex.ToHexString(resBuf)); } d.BlockUpdate(lastV, lastV.Length / 2, lastV.Length - lastV.Length / 2); d.DoFinal(resBuf, 0); if (!AreEqual(lastDigest, resBuf)) { Fail("failing second clone vector test", results[results.Length - 1], Hex.ToHexString(resBuf)); } }
// Create new test hex public static Hex CreateTestHex() { Hex newHex = new Hex(TileUTests.CreateTestTileData(), Vector3Int.zero); return(newHex); }
public Ball(Hex hex) { this.hex = hex; this.carriedBy = null; }
private BlockResult?GetBlock(Client client, int num) { Block?block = client.GetBlockByNumber((UInt64)num); if (block == null) { return(null); } var header = block.Header; var transactions = block.Transactions; int inputsCount = transactions.Select(tx => tx.Inputs.Length).Aggregate(0, (acc, cur) => acc + cur); int outputsCount = transactions.Select(tx => tx.Outputs.Length).Aggregate(0, (acc, cur) => acc + cur); ulong number = Hex.HexToUInt64(header.Number); int transactionsCount = transactions.Length; string timestamp = $"{ Hex.HexToUInt64(header.Timestamp) }"; // Reward string CalcluateReward() { string blockHash = header.Hash; BlockEconomicState?economicState = client.GetBlockEconomicState(blockHash); if (economicState != null) { MinerReward reward = economicState.MinerReward; return(Hex.HexToUInt64(reward.Primary).ToString()); } else { EpochInfo epochInfo = EpochInfo.Parse(Hex.HexToUInt64(block.Header.Epoch)); try { ulong primaryReward = PrimaryReward(client, number, epochInfo.Number); return(primaryReward.ToString()); } catch { return(""); } } } // Miner Address string prefix = IsMainnet() ? "ckb" : "ckt"; string cellbaseWitness = block.Transactions[0].Witnesses[0]; Script script = CellbaseWitness.Parse(cellbaseWitness); string minerAddress = Ckb.Address.Address.GenerateAddress(script, prefix); BlockResult result = new() { Number = number.ToString(), BlockHash = header.Hash, TransactionsCount = $"{transactionsCount}", Timestamp = timestamp, LiveCellChanges = $"{outputsCount - inputsCount}", Reward = CalcluateReward(), MinerHash = minerAddress }; return(result); }
public void TestDecode() { Assert.Throws <NotImplementedException>(() => Hex.Decode("")); }
public SslDiagDialog(IServiceProvider provider, ServerManager server) : base(provider) { InitializeComponent(); // from https://www.ibm.com/support/knowledgecenter/SSLTBW_2.1.0/com.ibm.zos.v2r1.ikya100/sigalg.htm var wellKnownSignatureAlgorithms = new Dictionary <string, bool> { { "1.2.840.113549.1.1.5", false }, // sha1RSA, not secure { "1.2.840.113549.1.1.14", true }, // sha224RSA, secure { "1.2.840.113549.1.1.11", true }, // sha256RSA, secure { "1.2.840.113549.1.1.12", true }, // sha384RSA, secure { "1.2.840.113549.1.1.13", true }, // sha512RSA, secure { "1.2.840.10040.4.3", false }, // sha1DSA, not secure { "1.2.840.10045.4.1", false }, // sha1ECDSA, not secure { "1.2.840.10045.4.3.1", true }, // sha224ECDSA, secure { "1.2.840.10045.4.3.2", true }, // sha256ECDSA, secure { "1.2.840.10045.4.3.3", true }, // sha384ECDSA, secure { "1.2.840.10045.4.3.4", true }, // sha512ECDSA, secure }; var container = new CompositeDisposable(); FormClosed += (sender, args) => container.Dispose(); container.Add( Observable.FromEventPattern <EventArgs>(btnGenerate, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { txtResult.Clear(); try { Warn("IMPORTANT: This report might contain confidential information. Mask such before sharing to others."); Warn("-----"); Debug($"System Time: {DateTime.Now}"); Debug($"Processor Architecture: {Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")}"); Debug($"OS: {Environment.OSVersion}"); Debug($"Server Type: {server.Mode.AsString(EnumFormat.Description)}"); Debug(string.Empty); Debug($"SERVER SSL PROTOCOLS{Environment.NewLine}"); bool ssl10Enabled = GetProtocol("PCT 1.0"); Debug($"PCT 1.0: {ssl10Enabled}"); if (ssl10Enabled) { Warn("PCT 1.0 is not secure. Please disable it."); } bool ssl20Enabled = GetProtocol("SSL 2.0"); Debug($"SSL 2.0: {ssl20Enabled}"); if (ssl20Enabled) { Warn("SSL 2.0 is not secure. Please disable it."); } bool ssl30Enabled = GetProtocol("SSL 3.0"); Debug($"SSL 3.0: {ssl30Enabled}"); if (ssl30Enabled) { Warn("SSL 3.0 is not secure. Please disable it."); } Debug($"TLS 1.0: {GetProtocol("TLS 1.0")}"); Debug($"TLS 1.1: {GetProtocol("TLS 1.1")}"); Debug($"TLS 1.2: {GetProtocol("TLS 1.2")}"); Debug($"SChannel EventLogging: {GetEventLogging()} (hex)"); Warn($"To tune TLS related settings, try out IIS Crypto from https://www.nartac.com/Products/IISCrypto/."); Debug("-----"); foreach (Site site in server.Sites) { Debug($"[W3SVC/{site.Id}]"); Debug($"ServerComment : {site.Name}"); Debug($"ServerAutoStart: {site.ServerAutoStart}"); Debug($"ServerState : {site.State}"); Debug(string.Empty); foreach (Binding binding in site.Bindings) { Info($"BINDING: {binding.Protocol} {binding}"); if (binding.Protocol == "https") { if (binding.CertificateHash == null) { // SNI mapping missing. Debug($"SSL Flags: {binding.SslFlags}"); if (binding.SslFlags == SslFlags.Sni) { Error( $"Cannot find {binding.Host}:{binding.EndPoint.Port} combination for this SNI binding."); } else { var querySslCertificateInfo = Microsoft.Web.Administration.NativeMethods.QuerySslCertificateInfo( binding.EndPoint); Error( querySslCertificateInfo == null ? $"Cannot find {binding.EndPoint} combination for this IP based binding." : $"Cannot find certificate with thumpprint {querySslCertificateInfo.Hash} in store {querySslCertificateInfo.StoreName}."); } Debug(string.Empty); continue; } var hashString = Hex.ToHexString(binding.CertificateHash); Debug($"SSLCertHash: {hashString}"); if (site.Server.SupportsSni) { Debug($"SSL Flags: {binding.SslFlags}"); } Debug("Testing EndPoint: 127.0.0.1"); var personal = new X509Store(binding.CertificateStoreName, StoreLocation.LocalMachine); try { personal.Open(OpenFlags.MaxAllowed); var selectedItem = personal.Certificates.Find(X509FindType.FindByThumbprint, hashString, false); if (selectedItem.Count == 0) { Error($"Cannot find certificate with thumbprint {hashString} in store {binding.CertificateStoreName}."); } else { var cert = selectedItem[0]; Debug($"#CertName: {cert.FriendlyName}"); Debug($"#Version: {cert.Version}"); if (cert.HasPrivateKey) { if (PublicNativeMethods.IsProcessElevated) { var newHandle = IntPtr.Zero; int newCount = 0; var shouldRelease = false; if (NativeMethods.CryptAcquireCertificatePrivateKey( cert.Handle, 0, IntPtr.Zero, ref newHandle, ref newCount, ref shouldRelease)) { Debug( "#You have a private key that corresponds to this certificate."); } else { Error("#You have a private key that corresponds to this certificate but CryptAcquireCertificatePrivateKey failed."); Rollbar.RollbarLocator.RollbarInstance.Error( "CryptAcquireCertificatePrivateKey failed"); } if (shouldRelease) { NativeMethods.CloseHandle(newHandle); } } else { Warn("It seems that you have a private key that corresponds to this certificate. Please run Jexus Manager as administrator and SSL Diag can report in more details."); } } else { Error( "#You don't have a private key that corresponds to this certificate."); } var key = cert.PublicKey.Key; var signatureAlgorithm = cert.SignatureAlgorithm; Debug($"#Signature Algorithm: {signatureAlgorithm.FriendlyName}"); if (wellKnownSignatureAlgorithms.ContainsKey(signatureAlgorithm.Value)) { if (!wellKnownSignatureAlgorithms[signatureAlgorithm.Value]) { Warn("Modern web browsers require signature algorithm to be secure. This signature algorithm is not secure, and might trigger warnings and/or errors."); } } else { Warn("This certificate uses a not-well-known signature algorithm, which might not be supported by all web browsers and servers."); } Debug($"#Key Exchange Algorithm: {key.KeyExchangeAlgorithm} Key Size: {key.KeySize}"); Debug($"#Subject: {cert.Subject}"); Debug($"#Issuer: {cert.Issuer}"); Debug($"#Validity: From {cert.NotBefore:G} To {cert.NotAfter:G}"); var now = DateTime.UtcNow; if (now < cert.NotBefore) { Warn("This certificate is not yet valid."); } if (cert.NotAfter < now) { Error("This certificate is already expired."); } Debug($"#Serial Number: {cert.SerialNumber}"); Debug($"DS Mapper Usage: {(binding.UseDsMapper ? "Enabled" : "Disabled")}"); Debug($"Archived: {cert.Archived}"); var hasSAN = false; foreach (var extension in cert.Extensions) { if (extension.Oid.Value == "2.5.29.15") { Debug($"#Key Usage: {((X509KeyUsageExtension)extension).KeyUsages}"); continue; } if (extension.Oid.Value == "2.5.29.37") { var usages = ((X509EnhancedKeyUsageExtension)extension).EnhancedKeyUsages; var enhancedKeyUsage = usages.Cast <Oid>().Select(usage => $"{usage.FriendlyName} ({usage.Value})") .Combine(","); Debug($"#Enhanced Key Usage: {enhancedKeyUsage}"); continue; } if (extension.Oid.Value == "2.5.29.17") { var name = extension.Format(true).TrimEnd(); Debug($"#Subject Alternative Name: {name}"); hasSAN = true; continue; } if (extension.Oid.FriendlyName == "Basic Constraints") { var ext = (X509BasicConstraintsExtension)extension; Debug( $"#Basic Constraints: Subject Type={(ext.CertificateAuthority ? "CA" : "End Entity")}, Path Length Constraint={(ext.HasPathLengthConstraint ? ext.PathLengthConstraint.ToString() : "None")}"); } } if (!hasSAN) { Warn("Modern web browsers require Subject Alternative Name extension to present. This certificate does not have SAN extension, so might trigger warnings and/or errors."); } X509Chain chain = X509Chain.Create(); chain.ChainPolicy = new X509ChainPolicy { RevocationMode = X509RevocationMode.Online }; bool valid = chain.Build(cert); if (valid) { Debug("Certificate verified."); } else { Error("Certificate validation failed."); } foreach (var item in chain.ChainStatus) { Warn(item.StatusInformation); } } personal.Close(); } catch (CryptographicException ex) { Error($"Problems detected on certificate store {binding.CertificateStoreName}."); if (ex.HResult != Microsoft.Web.Administration.NativeMethods.NonExistingStore) { throw; } Error($"Invalid certificate store {binding.CertificateStoreName}."); } } Debug(string.Empty); } } } catch (CryptographicException ex) { Debug(ex.ToString()); Rollbar.RollbarLocator.RollbarInstance.Error(ex, custom: new Dictionary <string, object> { { "hResult", ex.HResult } }); } catch (Exception ex) { Debug(ex.ToString()); Rollbar.RollbarLocator.RollbarInstance.Error(ex); } })); container.Add( Observable.FromEventPattern <EventArgs>(btnSave, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { var fileName = DialogHelper.ShowSaveFileDialog(null, "Text Files|*.txt|All Files|*.*", null); if (string.IsNullOrEmpty(fileName)) { return; } File.WriteAllText(fileName, txtResult.Text); })); container.Add( Observable.FromEventPattern <EventArgs>(btnVerify, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { txtResult.Clear(); })); }
public ITestResult doTest( string algorithm, byte[] input, byte[] output) { KeyParameter key; IBufferedCipher inCipher, outCipher; CipherStream cIn, cOut; MemoryStream bIn, bOut; // IvParameterSpec spec = new IvParameterSpec(); byte[] spec = Hex.Decode("1234567890abcdef"); try { key = new DesParameters(Hex.Decode("0123456789abcdef")); inCipher = CipherUtilities.GetCipher(algorithm); outCipher = CipherUtilities.GetCipher(algorithm); if (algorithm.StartsWith("DES/ECB")) { outCipher.Init(true, key); } else { outCipher.Init(true, new ParametersWithIV(key, spec)); } } catch (Exception e) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed initialisation - " + e.ToString(), e)); } try { if (algorithm.StartsWith("DES/ECB")) { inCipher.Init(false, key); } else { inCipher.Init(false, new ParametersWithIV(key, spec)); } } catch (Exception e) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed initialisation - " + e.ToString(), e)); } // // encryption pass // bOut = new MemoryStream(); cOut = new CipherStream(bOut, null, outCipher); try { for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); } catch (IOException e) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - " + e.ToString())); } byte[] bytes = bOut.ToArray(); if (!Arrays.AreEqual(bytes, output)) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes))); } // // decryption pass // bIn = new MemoryStream(bytes, false); cIn = new CipherStream(bIn, inCipher, null); try { BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { bytes[i] = dIn.ReadByte(); } int remaining = bytes.Length - input.Length / 2; byte[] extra = dIn.ReadBytes(remaining); if (extra.Length < remaining) { throw new EndOfStreamException(); } extra.CopyTo(bytes, input.Length / 2); } catch (Exception e) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - " + e.ToString())); } if (!Arrays.AreEqual(bytes, input)) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes))); } return(new SimpleTestResult(true, Name + ": " + algorithm + " Okay")); }
public static void WriteHexAttribute(this XmlWriter a_writer, string a_name, uint a_byte) { a_writer.WriteAttributeString(a_name, Hex.UIntToHex(a_byte)); }
public void init(WorldMap w, Hex h) { base.init(w, h, 3); }
/// <summary> /// Used to set the characters current position. Should only be used to teleport a character or to place them at the start of the game. /// </summary> /// <param name="target">Hex where the character should now be located.</param> public void SetCurrentHex(Hex target) { transform.position = target.GetWorldPosition(); location = target; Invoke("LateStart", .1f); }
public void InteractWithHex(Hex _hex) { if (activeHex == null) { return; } if (activeHex == _hex) { activeHex.ChangeColor(); activeHex.HideAvalibleHicesForMove(); activeHex = null; return; } if (activeHex.unit == null) { activeHex.ChangeColor(); activeHex = null; return; } activeHex.HideAvalibleHicesForMove(); activeHex.ChangeColor(); unitMoveResponse = activeHex.MoveUnitTo(_hex); if (unitMoveResponse == Hex.UnitMoveResponse.Attack) { Move theBestMoveForAttack = new Move(null, int.MaxValue); Move tmpMove = theBestMoveForAttack; foreach (Move adjcell in _hex.unit.GetAvalibleMoves(_hex, 1).moveList.moves) { tmpMove = activeHex.unit.avalibleHices.FindByHex(adjcell.hex); if (tmpMove != null) { if (tmpMove.price < theBestMoveForAttack.price) { theBestMoveForAttack = tmpMove; } } } foreach (Move adjcell in _hex.unit.avalibleEnemyHices.moves) { if (adjcell.hex == activeHex) { theBestMoveForAttack.hex = null; theBestMoveForAttack.price = 0; break; } } if (theBestMoveForAttack.hex != null) { unitMoveResponse = activeHex.MoveUnitTo(theBestMoveForAttack.hex); activeHex = theBestMoveForAttack.hex; } else { Debug.Log("Alredy in position"); } Debug.Log("Can attack"); activeHex.unit.AttackUnit(_hex.unit); } if (unitMoveResponse == Hex.UnitMoveResponse.CantMove) { Debug.Log("Cant move unit!"); } activeHex = null; }
private void doTest( string alg, int strength, byte[] input, byte[] output) { KeyParameter key = null; CipherKeyGenerator keyGen; SecureRandom rand; IBufferedCipher inCipher = null; IBufferedCipher outCipher = null; CipherStream cIn; CipherStream cOut; MemoryStream bIn; MemoryStream bOut; rand = new FixedSecureRandom(); try { keyGen = GeneratorUtilities.GetKeyGenerator(alg); keyGen.Init(new KeyGenerationParameters(rand, strength)); key = new DesEdeParameters(keyGen.GenerateKey()); inCipher = CipherUtilities.GetCipher(alg + "/ECB/PKCS7Padding"); outCipher = CipherUtilities.GetCipher(alg + "/ECB/PKCS7Padding"); outCipher.Init(true, new ParametersWithRandom(key, rand)); } catch (Exception e) { Fail(alg + " failed initialisation - " + e.ToString()); } try { inCipher.Init(false, key); } catch (Exception e) { Fail(alg + " failed initialisation - " + e.ToString()); } // // encryption pass // bOut = new MemoryStream(); cOut = new CipherStream(bOut, null, outCipher); try { for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); } catch (IOException e) { Fail(alg + " failed encryption - " + e.ToString()); } byte[] bytes = bOut.ToArray(); if (!Arrays.AreEqual(bytes, output)) { Fail(alg + " failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes)); } // // decryption pass // bIn = new MemoryStream(bytes, false); cIn = new CipherStream(bIn, inCipher, null); try { // DataInputStream dIn = new DataInputStream(cIn); BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { bytes[i] = (byte)dIn.ReadByte(); } // dIn.readFully(bytes, input.Length / 2, bytes.Length - input.Length / 2); int remaining = bytes.Length - input.Length / 2; byte[] rest = dIn.ReadBytes(remaining); if (rest.Length != remaining) { throw new Exception("IO problem with BinaryReader"); } rest.CopyTo(bytes, input.Length / 2); } catch (Exception e) { Fail(alg + " failed encryption - " + e.ToString()); } if (!Arrays.AreEqual(bytes, input)) { Fail(alg + " failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } // TODO Put back in // // // // keyspec test // // // try // { // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(alg); // DESedeKeySpec keySpec = (DESedeKeySpec)keyFactory.getKeySpec((SecretKey)key, DESedeKeySpec.class); // // if (!equalArray(key.getEncoded(), keySpec.getKey(), 16)) // { // Fail(alg + " KeySpec does not match key."); // } // } // catch (Exception e) // { // Fail(alg + " failed keyspec - " + e.ToString()); // } }
public void TestEncode() { string encoded = Hex.Encode(new byte[] { 0, 1, 2, 3, 4 }); Assert.Equal("0001020304", encoded); }
/// <summary>Creates and returns a string representation of the public key blob.</summary> /// <returns>A hexadecimal version of the public key blob.</returns> // Token: 0x06002650 RID: 9808 RVA: 0x0008ABA1 File Offset: 0x00088DA1 public override string ToString() { return(Hex.EncodeHexString(this.PublicKey)); }
public static void WriteHexElement(this XmlWriter a_writer, string a_name, uint a_byte) { a_writer.WriteElementString(a_name, Hex.UIntToHex(a_byte)); }
public OrganelleTemplate(OrganelleDefinition definition, Hex location, int rotation) { Definition = definition; Position = location; Orientation = rotation; }
private static BigInteger FromHex(string hex) { return(new BigInteger(1, Hex.Decode(hex))); }
public void droppedOnHex(Hex hex) { carriedBy = null; this.hex = hex; }
public static byte[] Decrypt(string privateKey, string encryptedData) { return(Decrypt(Hex.Decode(privateKey), Hex.Decode(encryptedData))); }
/** * Read a Key Pair */ private object ReadPrivateKey(PemObject pemObject) { // // extract the key // Debug.Assert(pemObject.Type.EndsWith("PRIVATE KEY")); string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim(); byte[] keyBytes = pemObject.Content; IDictionary fields = Platform.CreateHashtable(); foreach (PemHeader header in pemObject.Headers) { fields[header.Name] = header.Value; } string procType = (string)fields["Proc-Type"]; if (procType == "4,ENCRYPTED") { if (pFinder == null) { throw new PasswordException("No password finder specified, but a password is required"); } char[] password = pFinder.GetPassword(); if (password == null) { throw new PasswordException("Password is null, but a password is required"); } string dekInfo = (string)fields["DEK-Info"]; string[] tknz = dekInfo.Split(','); string dekAlgName = tknz[0].Trim(); byte[] iv = Hex.Decode(tknz[1].Trim()); keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv); } try { AsymmetricKeyParameter pubSpec, privSpec; Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(keyBytes); switch (type) { case "RSA": { if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq); pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); privSpec = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); break; } case "DSA": { if (seq.Count != 6) { throw new PemException("malformed sequence in DSA private key"); } // TODO Create an ASN1 object somewhere for this? //DerInteger v = (DerInteger)seq[0]; DerInteger p = (DerInteger)seq[1]; DerInteger q = (DerInteger)seq[2]; DerInteger g = (DerInteger)seq[3]; DerInteger y = (DerInteger)seq[4]; DerInteger x = (DerInteger)seq[5]; DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value); privSpec = new DsaPrivateKeyParameters(x.Value, parameters); pubSpec = new DsaPublicKeyParameters(y.Value, parameters); break; } case "EC": { ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(seq); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object()); // TODO Are the keys returned here ECDSA, as Java version forces? privSpec = PrivateKeyFactory.CreateKey(privInfo); DerBitString pubKey = pKey.GetPublicKey(); if (pubKey != null) { SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes()); // TODO Are the keys returned here ECDSA, as Java version forces? pubSpec = PublicKeyFactory.CreateKey(pubInfo); } else { pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey( (ECPrivateKeyParameters)privSpec); } break; } case "ENCRYPTED": { char[] password = pFinder.GetPassword(); if (password == null) { throw new PasswordException("Password is null, but a password is required"); } return(PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq))); } case "": { return(PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq))); } default: throw new ArgumentException("Unknown key type: " + type, "type"); } return(new AsymmetricCipherKeyPair(pubSpec, privSpec)); } catch (IOException e) { throw e; } catch (Exception e) { throw new PemException( "problem creating " + type + " private key: " + e.ToString()); } }
//public static X509Certificate MakeRootCert(string filePath, IDictionary subjectNames) //{ // AsymmetricCipherKeyPair keypair = SM2CryptoServiceProvider.Instance.ecc_key_pair_generator.GenerateKeyPair(); // ECPublicKeyParameters pubKey = (ECPublicKeyParameters)keypair.Public; //CA公钥 // ECPrivateKeyParameters priKey = (ECPrivateKeyParameters)keypair.Private; //CA私钥 // X509Name issuerDN = new X509Name(GetDictionaryKeys(subjectNames), subjectNames); // X509Name subjectDN = issuerDN; //自签证书,两者一样 // SM2X509V3CertificateGenerator sm2CertGen = new SM2X509V3CertificateGenerator(); // //X509V3CertificateGenerator sm2CertGen = new X509V3CertificateGenerator(); // sm2CertGen.SetSerialNumber(new BigInteger(128, new Random())); //128位 // sm2CertGen.SetIssuerDN(issuerDN); // sm2CertGen.SetNotBefore(DateTime.UtcNow.AddDays(-1)); // sm2CertGen.SetNotAfter(DateTime.UtcNow.AddDays(365 * 10)); // sm2CertGen.SetSubjectDN(subjectDN); // sm2CertGen.SetPublicKey(pubKey); //公钥 // sm2CertGen.SetSignatureAlgorithm("SM3WITHSM2"); // sm2CertGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); // sm2CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); // sm2CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pubKey)); // sm2CertGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(6)); // Org.BouncyCastle.X509.X509Certificate sm2Cert = sm2CertGen.Generate(keypair); // sm2Cert.CheckValidity(); // sm2Cert.Verify(pubKey); // return sm2Cert; //} public static String Encrypt(string publicKey, string data) { return(Encrypt(Hex.Decode(publicKey), Encoding.UTF8.GetBytes(data))); }
public override IPermission CreatePermission() { if (base.m_unrestricted) { return(new PublisherIdentityPermission(PermissionState.Unrestricted)); } if (this.m_x509cert != null) { return(new PublisherIdentityPermission(new System.Security.Cryptography.X509Certificates.X509Certificate(Hex.DecodeHexString(this.m_x509cert)))); } if (this.m_certFile != null) { return(new PublisherIdentityPermission(System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(this.m_certFile))); } if (this.m_signedFile != null) { return(new PublisherIdentityPermission(System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile(this.m_signedFile))); } return(new PublisherIdentityPermission(PermissionState.None)); }
public void TestECDsa239BitBinary() { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363").ToByteArrayUnsigned(); SecureRandom k = FixedSecureRandom.From(kData); // EllipticCurve curve = new EllipticCurve( // new ECFieldF2m(239, // m // new int[] { 36 }), // k // new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a // new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECCurve curve = new F2mCurve( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, // ECPointUtil.DecodePoint(curve, Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.ValueOf(4)); //4); // h ECPrivateKeyParameters sKey = new ECPrivateKeyParameters( "ECDSA", new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d parameters); ECPublicKeyParameters vKey = new ECPublicKeyParameters( "ECDSA", // ECPointUtil.DecodePoint(curve, Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q curve.DecodePoint(Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q parameters); ISigner sgr = SignerUtilities.GetSigner("ECDSA"); // KeyFactory f = KeyFactory.getInstance("ECDSA"); // AsymmetricKeyParameter sKey = f.generatePrivate(priKeySpec); // AsymmetricKeyParameter vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.Init(true, new ParametersWithRandom(sKey, k)); sgr.BlockUpdate(message, 0, message.Length); byte[] sigBytes = sgr.GenerateSignature(); sgr.Init(false, vKey); sgr.BlockUpdate(message, 0, message.Length); if (!sgr.VerifySignature(sigBytes)) { Fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } }
public void Setup() { hex = CreateTestHex(); }
public void TestECDsa239BitPrime() { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655").ToByteArrayUnsigned(); SecureRandom k = FixedSecureRandom.From(kData); // EllipticCurve curve = new EllipticCurve( // new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q // new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a // new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters spec = new ECDomainParameters( curve, // ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n BigInteger.One); //1); // h ECPrivateKeyParameters sKey = new ECPrivateKeyParameters( "ECDSA", new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeyParameters vKey = new ECPublicKeyParameters( "ECDSA", // ECPointUtil.DecodePoint(curve, Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); ISigner sgr = SignerUtilities.GetSigner("ECDSA"); // KeyFactory f = KeyFactory.getInstance("ECDSA"); // AsymmetricKeyParameter sKey = f.generatePrivate(priKey); // AsymmetricKeyParameter vKey = f.generatePublic(pubKey); sgr.Init(true, new ParametersWithRandom(sKey, k)); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.BlockUpdate(message, 0, message.Length); byte[] sigBytes = sgr.GenerateSignature(); sgr.Init(false, vKey); sgr.BlockUpdate(message, 0, message.Length); if (!sgr.VerifySignature(sigBytes)) { Fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } }
public void WriteObject( object obj, string algorithm, char[] password, SecureRandom random) { if (obj == null) { throw new ArgumentNullException("obj"); } if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (password == null) { throw new ArgumentNullException("password"); } if (random == null) { throw new ArgumentNullException("random"); } if (obj is AsymmetricCipherKeyPair) { WriteObject(((AsymmetricCipherKeyPair)obj).Private, algorithm, password, random); return; } string type = null; byte[] keyData = null; if (obj is AsymmetricKeyParameter) { AsymmetricKeyParameter akp = (AsymmetricKeyParameter)obj; if (akp.IsPrivate) { string keyType; keyData = EncodePrivateKey(akp, out keyType); type = keyType + " PRIVATE KEY"; } } if (type == null || keyData == null) { // TODO Support other types? throw new ArgumentException("Object type not supported: " + obj.GetType().FullName, "obj"); } string dekAlgName = algorithm.ToUpper(CultureInfo.InvariantCulture); // Note: For backward compatibility if (dekAlgName == "DESEDE") { dekAlgName = "DES-EDE3-CBC"; } int ivLength = dekAlgName.StartsWith("AES-") ? 16 : 8; byte[] iv = new byte[ivLength]; random.NextBytes(iv); byte[] encData = PemUtilities.Crypt(true, keyData, password, dekAlgName, iv); byte[] hexIV = Hex.Encode(iv); WritePemBlock(type, encData, "Proc-Type: 4,ENCRYPTED", "DEK-Info: " + dekAlgName + "," + Encoding.ASCII.GetString(hexIV, 0, hexIV.Length)); }
// Token: 0x0600264A RID: 9802 RVA: 0x0008AAE7 File Offset: 0x00088CE7 internal StrongNamePublicKeyBlob(string publicKey) { this.PublicKey = Hex.DecodeHexString(publicKey); }
public static string ValueToString(Asn1Encodable value) { StringBuilder vBuf = new StringBuilder(); if (value is IAsn1String && !(value is DerUniversalString)) { string v = ((IAsn1String)value).GetString(); if (v.Length > 0 && v[0] == '#') { vBuf.Append('\\'); } vBuf.Append(v); } else { try { vBuf.Append('#'); vBuf.Append(Hex.ToHexString(value.ToAsn1Object().GetEncoded(Asn1Encodable.Der))); } catch (IOException e) { throw new ArgumentException("Other value has no encoded form", e); } } int end = vBuf.Length; int index = 0; if (vBuf.Length >= 2 && vBuf[0] == '\\' && vBuf[1] == '#') { index += 2; } while (index != end) { switch (vBuf[index]) { case ',': case '"': case '\\': case '+': case '=': case '<': case '>': case ';': { vBuf.Insert(index, "\\"); index += 2; ++end; break; } default: { ++index; break; } } } int start = 0; if (vBuf.Length > 0) { while (vBuf.Length > start && vBuf[start] == ' ') { vBuf.Insert(start, "\\"); start += 2; } } int endBuf = vBuf.Length - 1; while (endBuf >= 0 && vBuf[endBuf] == ' ') { vBuf.Insert(endBuf, "\\"); endBuf--; } return(vBuf.ToString()); }
public void PanToHex(Hex hex) { // TODO: move camera to hex }