public Model.PhraseState State(CryptoRandom rand) { CryptoRandom r = rand; int val; PhraseState w = new PhraseState(); Phrase phrase = _automat.phrase; int max = AppSettings.GetSound() ? 3 : 2; val = r.Next(1, max); switch(val) { case 0: w.Rus(); break; case 1: w.Eng(); break; case 2: w.Sound(); break; } w.Text(phrase.EPhrase, phrase.RPhrase); if (_automat.phrase.PhraseId != -1) w.ButtonState(); else w.WithoutButtonState(); return w; }
public void Reader(string filePath) { var lineCount = 0; CryptoRandom rng = new CryptoRandom(); HeightGen format = new HeightGen(); using (var reader = File.OpenText(filePath)) { while (reader.ReadLine() != null) { lineCount++; } } int phrase = rng.Next(lineCount); string[] values = File.ReadAllText(filePath).Split(new string[] { Environment.NewLine }, StringSplitOptions.None); string outputString = values[phrase]; if (VarStorage.Globals.percentDelta != "") { outputString = outputString.Replace("mainName", VarStorage.Globals.mainName).Replace("otherName", VarStorage.Globals.otherName).Replace("mainSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainSize))).Replace("otherSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherSize))).Replace("mainFinalSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainFinalSize))).Replace("otherFinalSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherFinalSize))).Replace("changeDelta", format.totalHeight(Convert.ToInt32(VarStorage.Globals.changeDelta))).Replace("percentDelta", Convert.ToString(VarStorage.Globals.percentDelta) + "%").Replace("mainCompSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainCompSize))).Replace("otherCompSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherCompSize))); } else { outputString = outputString.Replace("mainName", VarStorage.Globals.mainName).Replace("otherName", VarStorage.Globals.otherName).Replace("mainSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainSize))).Replace("otherSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherSize))).Replace("mainFinalSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainFinalSize))).Replace("otherFinalSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherFinalSize))).Replace("(changeDelta)", format.totalHeight(Convert.ToInt32(VarStorage.Globals.changeDelta))).Replace("percentDelta", "").Replace("mainCompSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.mainCompSize))).Replace("otherCompSize", format.totalHeight(Convert.ToInt32(VarStorage.Globals.otherCompSize))); } VarStorage.Globals.textLine1 = outputString; }
public void Next() { var random = new CryptoRandom(); int next = -1; Assert.DoesNotThrow(() => next = random.Next()); Assert.That(next, Is.GreaterThanOrEqualTo(0)); }
public Model.WordState State(CryptoRandom rand) { CryptoRandom r = rand; int val; WordState w = new WordState(); Word word = _automat.word; int max = AppSettings.GetSound() ? 3 : 2; val = r.Next(0, max); switch(val) { case 0: w.Rus(); break; case 1: w.Eng(); break; case 2: w.Sound(); break; } w.Text(word.EWord, word.Transcription, word.EPhrase, word.RWord, word.RPhrase); if (_automat.word.WordId != -1) w.ButtonState(); else w.WithoutButtonState(); return w; }
public void ctor_NullSeqLength() { //Have to use alternate instance because we are testing //the ctor. CryptoRandom crnd; crnd = new CryptoRandom(Rijndael.Create(), new byte[16]); //Will succeed crnd = new CryptoRandom(Rijndael.Create(), new byte[15]); //Will succeed }
public void CryptoRandom_NeutralParity() { byte[] random = new byte[2048]; var rng = new CryptoRandom(); rng.NextBytes(random); AssertNeutralParity(random); }
public void Next_minvalue_maxvalue() { var random = new CryptoRandom(); int next = 0; Assert.DoesNotThrow(() => next = random.Next(20, 100)); Assert.That(next, Is.GreaterThanOrEqualTo(20)); Assert.That(next, Is.LessThan(100)); next = 0; Assert.DoesNotThrow(() => next = random.Next(-40, -20)); Assert.That(next, Is.GreaterThanOrEqualTo(-40)); Assert.That(next, Is.LessThan(-20)); }
public void Next_maxvalue() { var random = new CryptoRandom(); int next = -1; Assert.DoesNotThrow(() => next = random.Next(1000)); Assert.That(next, Is.GreaterThanOrEqualTo(0)); Assert.That(next, Is.LessThan(1000)); next = -1; Assert.DoesNotThrow(() => next = random.Next(500)); Assert.That(next, Is.GreaterThanOrEqualTo(0)); Assert.That(next, Is.LessThan(500)); }
public void Sample() { var random = new CryptoRandom(); double next = -1.0; Assert.DoesNotThrow(() => next = random.NextDouble()); Assert.That(next, Is.GreaterThanOrEqualTo(0.0)); Assert.That(next, Is.LessThanOrEqualTo(1.0)); next = -1.0; Assert.DoesNotThrow(() => next = random.NextDouble()); Assert.That(next, Is.GreaterThanOrEqualTo(0.0)); Assert.That(next, Is.LessThanOrEqualTo(1.0)); }
public IEnumerable<char> Generate(int numericBase, CharsetGenerator charsetGenerator) { numericBase = charsetGenerator.NumericSystemLimiter(numericBase); List<char> result = new List<char>(numericBase); List<char> buffer = new List<char>(numericBase); buffer.AddRange(charsetGenerator.AvailableCharacters); CryptoRandom rnd = new CryptoRandom(); while (buffer.Count > 0) { byte index = rnd.Next((byte)(buffer.Count)); result.Add(buffer[index]); buffer.RemoveAt(index); } return result; }
public static string IdNumber(int maxAge = 100, int minAge = 18) { var random = new CryptoRandom(); int year = random.Next(DateTime.Today.Year - maxAge, DateTime.Today.Year - minAge); int month = random.Next(1, 12); int day = random.Next(1, DateTime.DaysInMonth(year, month)); int gender = random.Next(1, 9999); // If < 5000 Then Female. If >= 5000 Then Male int countryId = 0; // 0 = South Africa, 1 = Other int secondLastDigit = random.Next(0, 9); int controlDigit = 0; var dateAndGender = string.Format("{0}{1}{2}{3}", year.ToString().Substring(2, 2), month.ToString().PadLeft(2, '0'), day.ToString().PadLeft(2, '0'), gender.ToString().PadLeft(4, '0')); string idNumber = dateAndGender + countryId + secondLastDigit; controlDigit = GetControlDigit(idNumber); idNumber = idNumber + controlDigit; return idNumber; }
static void Main(string[] args) { string[] noun = { "She", "He", "It", "The cat", "The mongoose", "The orange", "The trampoline", "Musicians", "Programmers", "The shake" }; string[] verb = { "ate", "barbequed", "chirped", "collided", "sang", "spoke", "cartwheeled", "dined", "watched", "directed" }; string[] where = { "With the monkeys", "on the porch", "under the moon", "after the storm", "before the prince, over the lake", "in the gazebo", "between the lines", "during the festival", "with them all." }; CryptoRandom rng = new CryptoRandom(); int nouns = rng.Next(1, 11); StringBuilder sentence = new StringBuilder(); sentence.Append(noun[nouns - 1]+" "); int verbs = rng.Next(1, 11); sentence.Append(verb[verbs - 1] + " "); int wheres = rng.Next(1, 11); sentence.Append(where[wheres - 1] + " "); Console.Write(sentence); }
static void Main(string[] args) { StreamReader reader = new StreamReader("..\\..\\SentenceParts.txt"); StringBuilder words = new StringBuilder(); StringBuilder sentence = new StringBuilder(); using (reader) { string line = reader.ReadLine(); words.Append(line); while (line != null) { line = reader.ReadLine(); words.Append(line); } string all = words.ToString(); string[] allWords =all.Split(','); string[] nouns = new string[10]; string[] verbs = new string[2]; string[] phrases = new string[3]; for (int i = 0; i < nouns.Length; i++) { nouns[i] = allWords[i]; } for (int n = 0; n<verbs.Length; n++) { verbs[n] = allWords[n + 10]; } for(int p= 0; p<phrases.Length; p++) { phrases[p] = allWords[p + 12]; } CryptoRandom randomNum = new CryptoRandom(); int noun = randomNum.Next(1, 11); int verb = randomNum.Next(1, 3); int phrase = randomNum.Next(1, 4); sentence.Append(nouns[noun-1] + " "); sentence.Append(verbs[verb-1] + " "); sentence.Append(phrases[phrase-1]); Console.WriteLine(sentence); } }
static void Main(string[] args) { bool play = true; while (play == true) { string line = ""; //create variable to store text read from file StreamReader reader = new StreamReader("nouns.txt"); //declare StreamReader and file name to be read using (reader) { //read line from file(if necessary add while loop line = reader.ReadLine(); //and additional ReadLine to continue while } //line is not null) CryptoRandom randnum = new CryptoRandom(); //random number generator int noun = randnum.Next(1, 11); //set number variable for noun int verb = randnum.Next(1, 11); //set number variable for verb int phrase = randnum.Next(1, 11); //set number variable for prepositional phrase string[] nounList = line.Split(','); //split text from line along commas and store in array string[] verbList = { "ate", "barbecued", "chirped", "collided", "sang", //create array with list of 10 verbs "spoke", "cartwheeled", "dined", "watched", "directed" }; string[] phraseList = {"with the monkeys", "on the porch", "under the moon", "after the storm", "before the prince", "over the lake", "in the gazebo", "between the lines", "during the festival", "with them all"}; //create array with list of 10 phrases StringBuilder sentence = new StringBuilder(); //create new stringbuilder to make the sentence sentence.Append(nounList[noun - 1] + " "); //add chosen noun # to sentence (subtract 1 for index) sentence.Append(verbList[verb - 1] + " "); //add chosen verb # to sentence sentence.Append(phraseList[phrase - 1]); //add chosen phrase # to sentence Console.WriteLine(sentence); //print out the sentence StreamWriter writer = new StreamWriter("FunnySentence.txt"); using (writer) //establish Streamwriter and name of file to write to { writer.WriteLine(sentence); //write result to the file } Console.WriteLine("Would you like to play again? Please enter \"yes\" or \"no\":"); string answer = Console.ReadLine(); //ask user if they want to play again answer.ToLower(); //convert answer to lower case if needed if (answer == "yes") { continue; //run program again if user says they want to play again } else break; //exit the program if the user doesn't say yes } }
public async Task TriviaAsync(IMessageChannel channel, Guild dbGuild) { if (dbGuild.Trivia.ElementCount == 0) { throw new FriendlyException("There are no trivia questions yet!"); } int roll = CryptoRandom.Next(dbGuild.Trivia.ElementCount); var element = dbGuild.Trivia.GetElement(roll); var answer = element.Value.AsString.ToLower(); Predicate <IUserMessage> correctResponse = y => y.Content.ToLower() == answer; if (!answer.Any(char.IsDigit)) { correctResponse = y => y.Content.SimilarTo(element.Value.AsString, 5, 10, 20); } await channel.SendAsync("__**TRIVIA:**__ " + element.Name); var response = await _interactiveService.WaitForMessage(channel, correctResponse); if (response != null) { var user = response.Author as IGuildUser; var winnings = CryptoRandom.NextDecimal(Config.MinTriviaPayout, Config.MaxTriviaPayout); await _userRepo.EditCashAsync(user, dbGuild, await _userRepo.GetUserAsync(user), winnings); await channel.SendAsync($"{user.Boldify()}, Congrats! You just won {winnings.USD()} for correctly answering \"{element.Value.AsString}\"."); } else { await channel.SendAsync($"NOBODY got the right answer for the trivia question! Alright, I'll sauce it to you guys, but next time " + $"you are on your own. The right answer is: \"{element.Value.AsString}\"."); } }
/// <summary> /// Creates a serialized and protected security token. /// </summary> /// <param name="token">The token.</param> /// <returns> /// A security token in serialized form /// </returns> /// <exception cref="System.InvalidOperationException">Invalid token type.</exception> public virtual async Task <string> CreateSecurityTokenAsync(Token token) { string tokenResult; if (token.Type == Constants.TokenTypes.AccessToken) { if (token.Client.AccessTokenType == AccessTokenType.Jwt) { _logger.LogVerbose("Creating JWT access token"); tokenResult = await _signingService.SignTokenAsync(token); } else { _logger.LogVerbose("Creating reference access token"); var handle = CryptoRandom.CreateUniqueId(); await _tokenHandles.StoreAsync(handle, token); tokenResult = handle; } } else if (token.Type == Constants.TokenTypes.IdentityToken) { _logger.LogVerbose("Creating JWT identity token"); tokenResult = await _signingService.SignTokenAsync(token); } else { throw new InvalidOperationException("Invalid token type."); } await _events.RaiseTokenIssuedEventAsync(token, tokenResult); return(tokenResult); }
public void Can_decrypt_ack_eip8_message() { Hex hex = "01ea0451958701280a56482929d3b0757da8f7fbe5286784beead59d95089c217c9b917788989470" + "b0e330cc6e4fb383c0340ed85fab836ec9fb8a49672712aeabbdfd1e837c1ff4cace34311cd7f4de" + "05d59279e3524ab26ef753a0095637ac88f2b499b9914b5f64e143eae548a1066e14cd2f4bd7f814" + "c4652f11b254f8a2d0191e2f5546fae6055694aed14d906df79ad3b407d94692694e259191cde171" + "ad542fc588fa2b7333313d82a9f887332f1dfc36cea03f831cb9a23fea05b33deb999e85489e645f" + "6aab1872475d488d7bd6c7c120caf28dbfc5d6833888155ed69d34dbdc39c1f299be1057810f34fb" + "e754d021bfca14dc989753d61c413d261934e1a9c67ee060a25eefb54e81a4d14baff922180c395d" + "3f998d70f46f6b58306f969627ae364497e73fc27f6d17ae45a413d322cb8814276be6ddd13b885b" + "201b943213656cde498fa0e9ddc8e0b8f8a53824fbd82254f3e2c17e8eaea009c38b4aa0a3f306e8" + "797db43c25d68e86f262e564086f59a2fc60511c42abfb3057c247a8a8fe4fb3ccbadde17514b7ac" + "8000cdb6a912778426260c47f38919a91f25f4b5ffb455d6aaaf150f7e5529c100ce62d6d92826a7" + "1778d809bdf60232ae21ce8a437eca8223f45ac37f6487452ce626f549b3b5fdee26afd2072e4bc7" + "5833c2464c805246155289f4"; byte[] allBytes = hex; byte[] sizeBytes = allBytes.Slice(0, 2); int size = sizeBytes.ToInt32(); ICryptoRandom cryptoRandom = new CryptoRandom(); EciesCipher cipher = new EciesCipher(cryptoRandom); byte[] deciphered = cipher.Decrypt(NetTestVectors.StaticKeyA, allBytes.Slice(2, size), sizeBytes); AckEip8Message ackMessage = _messageSerializationService.Deserialize <AckEip8Message>(deciphered); Assert.AreEqual(ackMessage.EphemeralPublicKey, NetTestVectors.EphemeralKeyB.PublicKey); Assert.AreEqual(ackMessage.Nonce, NetTestVectors.NonceB); Assert.AreEqual(ackMessage.Version, 4); byte[] data = _messageSerializationService.Serialize(ackMessage); Array.Resize(ref data, deciphered.Length); // TODO: check 102 Assert.AreEqual(deciphered.Slice(0, 102), data.Slice(0, 102), "serialization"); }
public LoadSequence(CryptoRandom random, int nCount, int nImageCount, RefreshManager refresh) { // When using load limit (count < image count), load item indexes in such // a way that balances the number of items per label. if (nCount < nImageCount) { Dictionary <int, List <DbItem> > rgItemsByLabel = refresh.GetItemsByLabel(); List <int> rgLabel = rgItemsByLabel.Where(p => p.Value.Count > 0).Select(p => p.Key).ToList(); for (int i = 0; i < nCount; i++) { int nLabelIdx = random.Next(rgLabel.Count); int nLabel = rgLabel[nLabelIdx]; List <DbItem> rgItems = rgItemsByLabel[nLabel]; int nItemIdx = random.Next(rgItems.Count); DbItem item = rgItems[nItemIdx]; m_rgLoadSequence.Add(item.Index); rgLabel.Remove(nLabel); if (rgLabel.Count == 0) { rgLabel = rgItemsByLabel.Where(p => p.Value.Count > 0).Select(p => p.Key).ToList(); } } refresh.Reset(); } // Otherwise just load all item indexes. else { for (int i = 0; i < nCount; i++) { m_rgLoadSequence.Add(i); } } }
public UserModel AutoProvisionUser(string provider, string userId, List <Claim> claims) { var allowedClaims = new List <Claim>(); foreach (var current in claims) { if (current.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name") { allowedClaims.Add(new Claim("name", current.Value)); } else if (JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.ContainsKey(current.Type)) { allowedClaims.Add(new Claim(JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap[current.Type], current.Type)); } else { allowedClaims.Add(current); } } var uniqueId = CryptoRandom.CreateUniqueId(32); var claim = allowedClaims.FirstOrDefault(c => c.Type == "name"); var str = (claim != null ? claim.Value : null) ?? uniqueId; var user = new UserModel { SubjectId = uniqueId, Username = str, ProviderName = provider, ProviderSubjectId = userId, Claims = allowedClaims }; _users.Add(user); return(user); }
static async Task AuthorizeUrl() { try { var codeVerifier = CryptoRandom.CreateUniqueId(32); var stateVerifier = CryptoRandom.CreateUniqueId(32); var nonceVerifier = CryptoRandom.CreateUniqueId(32); // discover endpoints from metadata var client = new HttpClient(); var disco = await client.GetDiscoveryDocumentAsync("https://localhost:44303/"); if (disco.IsError) { Console.WriteLine(disco.Error); return; } var ru = new RequestUrl("https://localhost:44303/connect/authorize"); var authorizeUrl = ru.CreateAuthorizeUrl(clientId: "d84d0a966e0b470facebd7a6dfa8b6b1", responseType: "code", scope: "openid profile offline_access awesomecareapi", redirectUri: "https://localhost:44372/signin-oidc", responseMode: "form_post", codeChallengeMethod: OidcConstants.CodeChallengeMethods.Sha256, codeChallenge: codeVerifier.ToSha256(), state: stateVerifier.ToSha256(), nonce: nonceVerifier.ToSha256() ); } catch (Exception ex) { throw; } }
public PlatformModel(HttpRequest request, IUrlHelper url, Platform platform = null) { if (platform == null) { PlatformId = CryptoRandom.CreateUniqueId(8); } else { Id = platform.Id; AccessTokenUrl = platform.AccessTokenUrl; AuthorizeUrl = platform.AuthorizeUrl; Issuer = platform.Issuer; JwkSetUrl = platform.JwkSetUrl; Name = platform.Name; PlatformId = platform.PlatformId; ClientId = platform.ClientId; PrivateKey = platform.PrivateKey; } DeepLinkingLaunchUrl = url.Page("/Tool", null, new { platformId = PlatformId }, request.Scheme); LaunchUrl = url.Page("/Tool", null, new { platformId = PlatformId }, request.Scheme); LoginUrl = url.Page("/OidcLogin", null, null, request.Scheme); }
public async Task Enslave(IGuildUser userToEnslave, [Own][Remainder] Weapon weapon) { var user = await _userRepo.GetUserAsync(userToEnslave); if (userToEnslave.Id == Context.User.Id) { ReplyError("Hey good buddies, look at that retard, trying to enslave himself."); } else if (Context.DbUser.SlaveOf != 0) { ReplyError("You cannot enslave someone if you are a slave."); } else if (user.SlaveOf != 0) { ReplyError("This user is already a slave."); } else if (user.Health > Config.MaxEnslaveHealth) { ReplyError($"The user must be under {Config.MaxEnslaveHealth} health to enslave."); } if (weapon.Accuracy >= CryptoRandom.Roll()) { await _userRepo.ModifyAsync(user, x => x.SlaveOf = Context.User.Id); await ReplyAsync($"You have successfully enslaved {userToEnslave.Boldify()}. {Config.SlaveCollection.ToString("P")} of all cash earned by all your slaves will go straight to you when you use `{Context.DbGuild.Prefix}Collect`."); await userToEnslave.TryDMAsync($"AH SHIT N***A! Looks like {Context.User.Boldify()} got you enslaved. The only way out is `{Context.DbGuild.Prefix}suicide`."); } else { await ReplyAsync("YOU GOT SLAMMED RIGHT IN THE C**T BY A N***A! :joy: :joy: :joy: Only took him 10 seconds to get you to the ground LMFAO."); await userToEnslave.TryDMAsync($"{Context.User.Boldify()} tried to enslave you but accidentally got pregnant and now he can't move :joy: :joy: :joy:."); } _cooldownService.TryAdd(new CommandCooldown(Context.User.Id, Context.Guild.Id, "Enslave", Config.EnslaveCooldown)); }
private EffectInteger GetEffectToDown(EffectInteger runeEffect) { var effectToImprove = GetEffectToImprove(runeEffect); // recherche de jet exotique var exoticEffect = ItemEffects.Where(x => IsExotic(x) && x != effectToImprove).RandomElementOrDefault(); if (exoticEffect != null) { return(exoticEffect); } // recherche de jet overmax var overmaxEffect = ItemEffects.Where(x => IsOverMax(x, runeEffect) && x != effectToImprove).RandomElementOrDefault(); if (overmaxEffect != null) { return(overmaxEffect); } var rand = new CryptoRandom(); foreach (var effect in ItemEffects.ShuffleLinq().Where(x => x != effectToImprove)) { if (EffectManager.Instance.GetEffectPower(effect) - EffectManager.Instance.GetEffectPower(runeEffect) < MAX_STAT_POWER) { continue; } if (rand.NextDouble() <= EffectManager.Instance.GetEffectPower(runeEffect) / Math.Abs(EffectManager.Instance.GetEffectBasePower(effect))) { return(effect); } } return(ItemEffects.FirstOrDefault(x => x != effectToImprove)); }
public async static Task <LoginResult> AuthenticateAsync(OidcSettings settings) { var taskCompletion = new TaskCompletionSource <LoginResult>(); var nonce = CryptoRandom.CreateUniqueId(32); var verifier = CryptoRandom.CreateUniqueId(32); var config = await LoadOpenIdConnectConfigurationAsync(settings); var login = new LoginWebView(settings.RedirectUri); login.Completed += async(o, e) => { if (e == null) { taskCompletion.TrySetCanceled(); } else { try { var result = await ValidateResponseAsync(e, settings, config, nonce, verifier); taskCompletion.SetResult(result); } catch (Exception ex) { taskCompletion.SetException(ex); } } }; login.WindowStartupLocation = WindowStartupLocation.CenterScreen; login.ShowDialog(CreateUrl(settings, config, nonce, verifier)); return(await taskCompletion.Task); }
protected override bool Process(Player player, RealmTime time, string args) { Random rand = new Random(); int diceNumber = 100; int output = -1; double percent = 0; try { diceNumber = Convert.ToInt32(args); } catch { diceNumber = 100; } if (diceNumber > 0) { output = CryptoRandom.Next(0, diceNumber); } else if (diceNumber < 0) { output = CryptoRandom.Next(diceNumber, 0); player.Manager.Chat.ChatBot(player.Owner, "I'm not sure if a negative-sided die makes sense, but I'll give it a try."); } else // if diceNumber IS zero { player.Manager.Chat.ChatBot(player.Owner, string.Format("Silly {0}! There's no such thing as a die without sides!", player.Client.Account.Name)); return(true); } double prePercent = (int)((output / (double)diceNumber) * 10000); for (int e = 1337; (prePercent % 10 == 0) && (prePercent <= 100); e++) //added to remove trailing zeros in the percentage { prePercent = prePercent / 10; } percent = prePercent / 100; player.Manager.Chat.ChatBot(player.Owner, string.Format("{0} rolled {1} out of {2}. ({3}%)", player.Name, output.ToString(), diceNumber, percent.ToString())); return(true); }
/// <summary> /// Create the claims to be used in the back-channel logout token. /// </summary> /// <param name="request"></param> /// <returns>The claims to include in the token.</returns> protected Task <IEnumerable <Claim> > CreateClaimsForTokenAsync(BackChannelLogoutRequest request) { if (request.SessionIdRequired && request.SessionId == null) { throw new ArgumentException("Client requires SessionId", nameof(request.SessionId)); } var json = "{\"" + OidcConstants.Events.BackChannelLogout + "\":{} }"; var claims = new List <Claim> { new Claim(JwtClaimTypes.Subject, request.SubjectId), new Claim(JwtClaimTypes.Audience, request.ClientId), new Claim(JwtClaimTypes.JwtId, CryptoRandom.CreateUniqueId(16, CryptoRandom.OutputFormat.Hex)), new Claim(JwtClaimTypes.Events, json, IdentityServerConstants.ClaimValueTypes.Json) }; if (request.SessionId != null) { claims.Add(new Claim(JwtClaimTypes.SessionId, request.SessionId)); } return(Task.FromResult(claims.AsEnumerable())); }
byte[] GetCookieToken() { var cookieName = options.AuthenticationOptions.CookieOptions.Prefix + TokenName; var cookie = context.Request.Cookies[cookieName]; if (cookie != null) { try { var protectedCookieBytes = Base64Url.Decode(cookie); var tokenBytes = options.DataProtector.Unprotect(protectedCookieBytes, CookieEntropy); return(tokenBytes); } catch (Exception ex) { // if there's an exception we fall thru the catch block to reissue a new cookie Logger.WarnFormat("Problem unprotecting cookie; Issuing new cookie. Error message: {0}", ex.Message); } } var bytes = CryptoRandom.CreateRandomKey(16); var protectedTokenBytes = options.DataProtector.Protect(bytes, CookieEntropy); var token = Base64Url.Encode(protectedTokenBytes); var secure = context.Request.Scheme == Uri.UriSchemeHttps; var path = context.Request.Environment.GetIdentityServerBasePath().CleanUrlPath(); context.Response.Cookies.Append(cookieName, token, new Microsoft.Owin.CookieOptions { HttpOnly = true, Secure = secure, Path = path }); return(bytes); }
/// <summary> /// Returns a new provider and JWK for signing pop tokens. Can be pre-called and passed to the login flow to diminish the visible time this is generating a key to users. /// </summary> /// <returns>The provider for pop token async.</returns> public static Task <RsaSecurityKey> CreateProviderForPopTokenAsync() { return(Task.Run(() => { var rsa = RSA.Create(); if (rsa.KeySize < 2048) { rsa.Dispose(); rsa = new RSACryptoServiceProvider(2048); } RsaSecurityKey key = null; if (rsa is RSACryptoServiceProvider) { key = new RsaSecurityKey(rsa); } else { key = new RsaSecurityKey(rsa); } key.Rsa.ExportParameters(false); key.KeyId = CryptoRandom.CreateUniqueId(); return key; })); }
public void CryptoRandom_ZeroLengthInput() { var rng = new CryptoRandom(); // While this will do nothing, it's not something that throws. rng.NextBytes(Array.Empty<byte>()); rng.NextBytes(Array.Empty<byte>(), 0, 0); bool isThrown = false; try { rng.NextBytes(Array.Empty<byte>(), 0, 123); } catch (ArgumentException) { isThrown = true; } Assert.IsTrue(isThrown); isThrown = false; try { rng.NextBytes(Array.Empty<byte>(), 123, 0); } catch (ArgumentException) { isThrown = true; } Assert.IsTrue(isThrown); }
private async Task <string> CreateCodeAsync(ValidatedAuthorizeRequest request) { var code = new AuthorizationCode { Client = request.Client, Subject = request.Subject, SessionId = request.SessionId, IsOpenId = request.IsOpenIdRequest, RequestedScopes = request.ValidatedScopes.GrantedScopes, RedirectUri = request.RedirectUri, Nonce = request.Nonce, WasConsentShown = request.WasConsentShown, }; // store id token and access token and return authorization code var id = CryptoRandom.CreateUniqueId(); await _authorizationCodes.StoreAsync(id, code); await RaiseCodeIssuedEventAsync(id, code); return(id); }
public static IIdentityServerBuilder AddSigningCredential(this IIdentityServerBuilder builder) { // create random RS256 key builder.AddDeveloperSigningCredential(); // use an RSA-based certificate with RS256 var cert = new X509Certificate2("./keys/identityserver.test.rsa.p12", "changeit"); builder.AddSigningCredential(cert, "RS256"); // ...and PS256 builder.AddSigningCredential(cert, "PS256"); // or manually extract ECDSA key from certificate (directly using the certificate is not support by Microsoft right now) var ecCert = new X509Certificate2("./keys/identityserver.test.ecdsa.p12", "changeit"); var key = new ECDsaSecurityKey(ecCert.GetECDsaPrivateKey()) { KeyId = CryptoRandom.CreateUniqueId(16) }; return(builder.AddSigningCredential( key, IdentityServerConstants.ECDsaSigningAlgorithm.ES256)); }
public void Can_decrypt_auth_eip8_message() { Hex hex = "01b304ab7578555167be8154d5cc456f567d5ba302662433674222360f08d5f1534499d3678b513b" + "0fca474f3a514b18e75683032eb63fccb16c156dc6eb2c0b1593f0d84ac74f6e475f1b8d56116b84" + "9634a8c458705bf83a626ea0384d4d7341aae591fae42ce6bd5c850bfe0b999a694a49bbbaf3ef6c" + "da61110601d3b4c02ab6c30437257a6e0117792631a4b47c1d52fc0f8f89caadeb7d02770bf999cc" + "147d2df3b62e1ffb2c9d8c125a3984865356266bca11ce7d3a688663a51d82defaa8aad69da39ab6" + "d5470e81ec5f2a7a47fb865ff7cca21516f9299a07b1bc63ba56c7a1a892112841ca44b6e0034dee" + "70c9adabc15d76a54f443593fafdc3b27af8059703f88928e199cb122362a4b35f62386da7caad09" + "c001edaeb5f8a06d2b26fb6cb93c52a9fca51853b68193916982358fe1e5369e249875bb8d0d0ec3" + "6f917bc5e1eafd5896d46bd61ff23f1a863a8a8dcd54c7b109b771c8e61ec9c8908c733c0263440e" + "2aa067241aaa433f0bb053c7b31a838504b148f570c0ad62837129e547678c5190341e4f1693956c" + "3bf7678318e2d5b5340c9e488eefea198576344afbdf66db5f51204a6961a63ce072c8926c"; byte[] allBytes = hex; byte[] sizeBytes = allBytes.Slice(0, 2); int size = sizeBytes.ToInt32(); ICryptoRandom cryptoRandom = new CryptoRandom(); EciesCipher cipher = new EciesCipher(cryptoRandom); byte[] deciphered = cipher.Decrypt(NetTestVectors.StaticKeyB, allBytes.Slice(2, size), sizeBytes); AuthEip8Message authMessage = _messageSerializationService.Deserialize <AuthEip8Message>(deciphered); Assert.AreEqual(authMessage.PublicKey, NetTestVectors.StaticKeyA.PublicKey); Assert.AreEqual(authMessage.Nonce, NetTestVectors.NonceA); Assert.AreEqual(authMessage.Version, 4); Assert.NotNull(authMessage.Signature); byte[] data = _messageSerializationService.Serialize(authMessage); Array.Resize(ref data, deciphered.Length); //TODO: check 169 Assert.AreEqual(deciphered.Slice(0, 169), data.Slice(0, 169), "serialization"); }
public void Challenge22_Crack_an_MT19937_seed() { int unixTimestamp; uint seed; uint currentRandomNumber; using (var crnd = RandomNumberGenerator.Create()) { unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; unixTimestamp += CryptoRandom.GetInt(crnd, 40, 1000); var rng = new MT19937(); seed = (uint)unixTimestamp; rng.SeedMt(seed); unixTimestamp += CryptoRandom.GetInt(crnd, 40, 1000); currentRandomNumber = rng.ExtractNumber(); } // check every possible second from the last twenty-four hours uint foundSeed = 0; for (int i = unixTimestamp; i > (unixTimestamp - 86400); --i) { var rng = new MT19937(); rng.SeedMt((uint)i); if (rng.ExtractNumber() == currentRandomNumber) { foundSeed = (uint)i; break; } } Assert.Equal(seed, foundSeed); }
/// <summary> /// Creates a session identifier for the signin context and issues the session id cookie. /// </summary> /// <param name="principal"></param> /// <param name="properties"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// principal /// or /// properties /// </exception> public virtual async Task CreateSessionIdAsync(ClaimsPrincipal principal, AuthenticationProperties properties) { if (principal == null) { throw new ArgumentNullException(nameof(principal)); } if (properties == null) { throw new ArgumentNullException(nameof(properties)); } var currentSubjectId = (await GetUserAsync())?.GetSubjectId(); var newSubjectId = principal.GetSubjectId(); if (!properties.Items.ContainsKey(SessionIdKey) || currentSubjectId != newSubjectId) { properties.Items[SessionIdKey] = CryptoRandom.CreateUniqueId(16); } IssueSessionIdCookie(properties.Items[SessionIdKey]); Principal = principal; Properties = properties; }
// This method picks a wire from the list to be the correct wire to cut. private void PickCorrectWire() { // Uses a random number generator to pick a wire by ID (integer). int chosenWireNum = CryptoRandom.Between(1, AllWires.Count); foreach (WireProperties wireProp in ReColoredWires) { if (wireProp.wireID == chosenWireNum) { wireProp.correctWire = true; if (modeManager.gameMode == ModeManager.GameMode.Practice) { wireProp.wireOBJ.GetComponent <Renderer>().material.SetFloat("_Outline", 0.1f); } correctColorPanel.material.color = wireProp.wireColor; break; } else { wireProp.correctWire = false; } } }
private async Task <Token> CreateAccessTokenAsync(TokenCreationRequest request) { var claims = new List <Claim>(); claims.AddRange(await _claimsService.GetAccessTokenClaimsAsync( request.Subject, request.Resources, request.ValidatedRequest).ConfigureAwait(false)); if (request.ValidatedRequest.Client.IncludeJwtId) { claims.Add(new Claim(JwtClaimTypes.JwtId, CryptoRandom.CreateUniqueId(16))); } var issuer = _configurationProvider.DefaultClientAuthority; var token = new Token(OidcConstants.TokenTypes.AccessToken) { CreationTime = DateTimeOffset.Now.UtcDateTime, Audiences = { string.Format(AccessTokenAudience, issuer) }, Issuer = issuer, Lifetime = request.ValidatedRequest.AccessTokenLifetime, Claims = claims, ClientId = request.ValidatedRequest.Client.ClientId, AccessTokenType = request.ValidatedRequest.AccessTokenType }; foreach (var api in request.Resources.ApiResources) { if (!string.IsNullOrEmpty(api.Name)) { token.Audiences.Add(api.Name); } } return(token); }
public string Write(TMessage message) { ClearOverflow(); if (message == null) { throw new ArgumentNullException("message"); } var id = CryptoRandom.CreateUniqueId(); var name = GetCookieName(id); var data = Protect(message); ctx.Response.Cookies.Append( name, data, new Microsoft.Owin.CookieOptions { HttpOnly = true, Secure = Secure, Path = CookiePath }); return(id); }
/// <summary> /// calculates the amount of exp to give to the client /// </summary> public int GetEXP(GameClient Client, GameClient TargetClient, RoleplayBot Bot = null) { CryptoRandom Random = new CryptoRandom(); int LevelDifference = Math.Abs(Client.GetRoleplay().Level - TargetClient.GetRoleplay().Level); int Amount; int Bonus; if (LevelDifference > 8) { Amount = 0; Bonus = 0; } else { if (TargetClient.GetRoleplay().Level > Client.GetRoleplay().Level) { Bonus = (10 * (LevelDifference + 1)) + LevelDifference * 2; } else if (TargetClient.GetRoleplay().Level == Client.GetRoleplay().Level) { Bonus = (10 * 2) + 3; } else if (TargetClient.GetRoleplay().Level < Client.GetRoleplay().Level) { Bonus = 10; } else { Bonus = 2 * LevelDifference; } Amount = Random.Next(10, 10 + (LevelDifference + 5)); } return(Amount + Bonus + 15); }
/// <summary> /// Executes this type of combat /// </summary> public void Execute(GameClient Client, GameClient TargetClient, bool HitClosest = false) { if (!CanCombat(Client, TargetClient)) { return; } #region Variables RoomUser RoomUser = Client.GetRoomUser(); RoomUser TargetRoomUser = TargetClient.GetRoomUser(); int Damage = GetDamage(Client, TargetClient); Weapon Weapon = Client.GetRoleplay().EquippedWeapon; Point ClientPos = RoomUser.Coordinate; Point TargetClientPos = TargetRoomUser.Coordinate; #endregion #region Ammo Check if (Client.GetRoleplay().GunShots >= Weapon.ClipSize) { Weapon.Reload(Client, TargetClient); Client.GetRoleplay().CooldownManager.CreateCooldown("reload", 1000, Weapon.ReloadTime); return; } #endregion #region Distance Check double Distance = RoleplayManager.GetDistanceBetweenPoints2D(ClientPos, TargetClientPos); if (Distance > Weapon.Range) { RoleplayManager.Shout(Client, "*Tenta acertar o tiro em " + TargetClient.GetHabbo().Username + ", mas erra o alvo*", 4); Client.GetRoleplay().GunShots++; if (Client.GetRoleplay().Game == null) { Client.GetRoleplay().Bullets--; } return; } #endregion #region Target Death Procedure if (TargetClient.GetRoleplay().CurHealth - Damage <= 0) { Client.GetRoleplay().ClearWebSocketDialogue(); string Text = Weapon.FiringText.Split(':')[1]; string GunName = Weapon.PublicName; RoleplayManager.Shout(Client, FormatFiringText(Text, GunName, TargetClient.GetHabbo().Username, Damage, Weapon.Energy), 6); lock (PlusEnvironment.GetGame().GetClientManager().GetClients) { foreach (var client in PlusEnvironment.GetGame().GetClientManager().GetClients.ToList()) { if (client == null || client.GetHabbo() == null) { continue; } client.SendMessage(new RoomNotificationComposer("staff_notice", "message", "[Notícia Urgente] " + Client.GetHabbo().Username + " matou com tiros o cidadão " + TargetClient.GetHabbo().Username + ", tome cuidado pelas ruas!")); } } if (Client.GetRoleplay().LastKilled != TargetClient.GetHabbo().Id&& TargetClient.GetRoleplay().Game == null) { PlusEnvironment.GetGame().GetQuestManager().ProgressUserQuest(Client, QuestType.KILL_USER); PlusEnvironment.GetGame().GetAchievementManager().ProgressAchievement(Client, "ACH_Kills", 1); PlusEnvironment.GetGame().GetAchievementManager().ProgressAchievement(TargetClient, "ACH_Death", 1); #region Player Stats Client.GetRoleplay().LastKilled = TargetClient.GetHabbo().Id; Client.GetRoleplay().Kills++; Client.GetRoleplay().GunKills++; if (GroupManager.HasJobCommand(TargetClient, "guide") && TargetClient.GetRoleplay().IsWorking) { TargetClient.GetRoleplay().CopDeaths++; } else { TargetClient.GetRoleplay().Deaths++; } if (!Client.GetRoleplay().WantedFor.Contains("cometer assassinato")) { Client.GetRoleplay().WantedFor = Client.GetRoleplay().WantedFor + "cometer assassinato, "; } #endregion #region Exp Calculator CryptoRandom Random = new CryptoRandom(); int Multiplier = 1; int Chance = Random.Next(1, 101); if (Chance <= 16) { if (Chance <= 8) { Multiplier = 3; } else { Multiplier = 2; } } LevelManager.AddLevelEXP(Client, GetEXP(Client, TargetClient) * Multiplier); #endregion #region Gang Stats Group Gang = GroupManager.GetGang(Client.GetRoleplay().GangId); Group TarGetGang = GroupManager.GetGang(TargetClient.GetRoleplay().GangId); using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { if (Gang != null) { if (Gang.Id > 1000) { int ScoreIncrease = Random.Next(1, 11); Gang.GangKills++; Gang.GangScore += ScoreIncrease; dbClient.RunQuery("UPDATE `rp_gangs` SET `gang_kills` = '" + Gang.GangKills + "', `gang_score` = '" + Gang.GangScore + "' WHERE `id` = '" + Gang.Id + "'"); } } if (TarGetGang != null) { if (TarGetGang.Id > 1000) { TarGetGang.GangDeaths++; dbClient.RunQuery("UPDATE `rp_gangs` SET `gang_deaths` = '" + TarGetGang.GangDeaths + "' WHERE `id` = '" + TarGetGang.Id + "'"); } } } #endregion BountyManager.CheckBounty(Client, TargetClient.GetHabbo().Id); if ((TargetClient.GetRoleplay().CurHealth - Damage) <= 0) { TargetClient.GetRoleplay().CurHealth = 0; } } } #endregion #region Target Damage Procedure (Did not die) else { string Text = Weapon.FiringText.Split(':')[0]; string GunName = Weapon.PublicName; Client.GetRoleplay().OpenUsersDialogue(TargetClient); TargetClient.GetRoleplay().OpenUsersDialogue(Client); PlusEnvironment.GetGame().GetQuestManager().ProgressUserQuest(Client, QuestType.SHOOT_USER); RoleplayManager.Shout(Client, FormatFiringText(Text, GunName, TargetClient.GetHabbo().Username, Damage, Weapon.Energy), 6); } #endregion TargetClient.GetRoleplay().CurHealth -= Damage; if (Client.GetRoleplay().Game == null) { Client.GetRoleplay().Bullets--; } if (Client.GetRoleplay().Game == null) { Client.GetRoleplay().CurEnergy -= Weapon.Energy; } Client.GetRoleplay().GunShots++; if (!Client.GetRoleplay().WantedFor.Contains("tentativa de assaltSo + tentativa/assassinato")) { Client.GetRoleplay().WantedFor = Client.GetRoleplay().WantedFor + "tentativa de assalto + tentativa/assassinato "; } }
public void EtM_CTR_Sanity() { var rnd = new CryptoRandom(); const int plaintextOffset = 16; for (int i = 0; i < 2000; ++i) { var plaintext = new byte[rnd.Next(plaintextOffset + plaintextOffset, 50 * 1024)]; var plaintextSegment = new ArraySegment<byte>(array: plaintext, offset: plaintextOffset /* some non-zero offset */, count: plaintext.Length - plaintextOffset - plaintextOffset); rnd.NextBytes(plaintext); var masterkey = new byte[rnd.Next(0, 64)]; rnd.NextBytes(masterkey); var salt = new byte[rnd.Next(0, 64)]; rnd.NextBytes(salt); var saltSegment = new ArraySegment<byte>(salt); var ciphertext = EtM_CTR.Encrypt(masterkey, plaintextSegment, saltSegment); var ciphertext_with_padding = new byte[ciphertext.Length + plaintextOffset + plaintextOffset]; Utils.BlockCopy(ciphertext, 0, ciphertext_with_padding, plaintextOffset, ciphertext.Length); var ciphertextSegment = new ArraySegment<byte>(array: ciphertext_with_padding, offset: plaintextOffset, count: ciphertext.Length); var decryptedtext = EtM_CTR.Decrypt(masterkey, ciphertextSegment, saltSegment); Assert.IsTrue(Utils.ConstantTimeEqual(new ArraySegment<byte>(decryptedtext), plaintextSegment)); Assert.IsTrue(EtM_CTR.Authenticate(masterkey, ciphertextSegment, saltSegment)); }//for }//EtM_CTR_Sanity()
public void ChangeSize() { //Create a random number gen and height gen CryptoRandom rnd = new CryptoRandom(); HeightGen conv = new HeightGen(); //set values on the first turn only. if (firstTurn == true) { VarStorage.Globals.player1Height = Convert.ToDouble(txtStartP1.Text); VarStorage.Globals.player2Height = Convert.ToDouble(txtStartP2.Text); firstTurn = false; } //Checks who's turn it is, then sets global variables. if (p1Turn == true) { VarStorage.Globals.mainName = txtP1Name.Text; VarStorage.Globals.otherName = txtP2Name.Text; VarStorage.Globals.mainSize = VarStorage.Globals.player1Height; VarStorage.Globals.otherSize = VarStorage.Globals.player2Height; } else { VarStorage.Globals.mainName = txtP2Name.Text; VarStorage.Globals.otherName = txtP1Name.Text; VarStorage.Globals.mainSize = VarStorage.Globals.player2Height; VarStorage.Globals.otherSize = VarStorage.Globals.player1Height; } //Rolls to see which change to make, then executes said change. int rNumber = rnd.Next(100) + 1; ChangeHandler theChange = new ChangeHandler(); if (rNumber >= 1 && rNumber <= 10) { VarStorage.Globals.rollType = 1; theChange.Changing(); } else if (rNumber >= 11 && rNumber <= 50) { VarStorage.Globals.rollType = 2; theChange.Changing(); } else if (rNumber >=51 && rNumber <= 60) { VarStorage.Globals.rollType = 3; theChange.Changing(); } else { VarStorage.Globals.rollType = 4; theChange.Changing(); } //Checks the turn and then sets the main height variables. if (p1Turn == true) { VarStorage.Globals.player1Height = VarStorage.Globals.mainFinalSize; VarStorage.Globals.player2Height = VarStorage.Globals.otherFinalSize; } else { VarStorage.Globals.player1Height = VarStorage.Globals.otherFinalSize; VarStorage.Globals.player2Height = VarStorage.Globals.mainFinalSize; } //Creates the text that is displayed in the main textbox. txtDisplay.Text += VarStorage.Globals.textLine1; txtDisplay.Text += Environment.NewLine; txtDisplay.Text += Environment.NewLine; //Finds closest object sizes. List<int> objects = new List<int> { 304800, 762000, 1828800, 7493000}; int relativeSize = Convert.ToInt32(VarStorage.Globals.mainFinalSize); string compObject = ""; /* if (VarStorage.Globals.player1Height >= VarStorage.Globals.player2Height) { relativeSize = Convert.ToInt32(VarStorage.Globals.player1Height * 12); } else { relativeSize = Convert.ToInt32(VarStorage.Globals.player2Height * 12); } */ double closest = objects.Aggregate((x, y) => Math.Abs(x - relativeSize) < Math.Abs(y - relativeSize) ? x : y); if (closest == 304800) { compObject = "Rabbit"; } else if (closest == 762000) { compObject = "Wolf"; } else if (closest == 1828800) { compObject = "SUV"; } //Creates text for the comparison textbox. VarStorage.Globals.textLine2 = VarStorage.Globals.mainName + " now appears " + conv.totalHeight(Convert.ToInt32(VarStorage.Globals.mainCompSize)) + " to the " + conv.totalHeight(Convert.ToInt32((VarStorage.Globals.otherFinalSize))) + " tall " + VarStorage.Globals.otherName; VarStorage.Globals.textLine3 = VarStorage.Globals.otherName + " looks to be " + conv.totalHeight(Convert.ToInt32(VarStorage.Globals.otherCompSize)) + " tall to " + VarStorage.Globals.mainName + "."; txtRecap.Text = VarStorage.Globals.textLine2; txtRecap.Text += Environment.NewLine; txtRecap.Text += VarStorage.Globals.textLine3; txtRecap.Text += Environment.NewLine; txtRecap.Text += "To " + VarStorage.Globals.mainName + ", the " + compObject + " looks to be " + conv.totalHeight(Convert.ToInt32((closest * 1828800) / Convert.ToInt32(VarStorage.Globals.mainFinalSize))); //Creates the VMS link. double p1in = VarStorage.Globals.player1Height; string p1HeightRounded = p1in.ToString("0"); double p2in = VarStorage.Globals.player2Height; string p2HeightRounded = p2in.ToString("0"); txtBFLink.Text = "http://vms.bigfurs.com/?chars=" + compObject + "+" + txtP1Name.Text + "[" + p1HeightRounded+ "um]+" + txtP2Name.Text + "[" + p2HeightRounded + "um]"; txtDisplay.SelectionStart = txtDisplay.Text.Length; //Set the current caret position at the end txtDisplay.ScrollToCaret(); //Now scroll it automatically //Set the Height text fields. txtSize1.Text = conv.totalHeight(Convert.ToInt32(VarStorage.Globals.player1Height)); txtSize2.Text = conv.totalHeight(Convert.ToInt32(VarStorage.Globals.player2Height)); }
void CreateTurretsRandom() { Debug.Log("Creating Turrets for " + this.gameObject.name); // Make sure there are rig points on this ship from XML. if (attributes.rigPointType == null) { Debug.LogError("Points are Null"); return; } if ( attributes.rigPointType.Length < 1) { Debug.LogError("Points are Empty"); return; } // Make sure Rig Points and Rig Sizes array have proper amount of rigs. List<string> properAmount = new List<string>(); for (int ndx = 0; ndx < attributes.rigPointType.Length; ++ndx) { if (!String.IsNullOrEmpty(attributes.rigPointType[ndx])) properAmount.Add(attributes.rigPointType[ndx]); else break; } attributes.rigPointType = properAmount.ToArray(); properAmount.Clear(); for (int ndx = 0; ndx < attributes.rigPointSize.Length; ++ndx) { if (!String.IsNullOrEmpty(attributes.rigPointSize[ndx])) properAmount.Add(attributes.rigPointSize[ndx]); else break; } attributes.rigPointSize = properAmount.ToArray(); int rigPoints = attributes.rigPointType.Length; //Debug.Log("Start Position: " + transform.position); //PopulateRigPoints(); if (rigPoints != RigPointsCount) { // Also add InGame to InXML amounts for debugging for modding. Debug.LogError(this.name + " Ship rig points != XML Rig points for ship. Please make sure you have the correct amount of rig point types in your XML file for this ship. Ship will stop being rigged for weapons now. " + rigPoints + " / " + RigPointsCount); return; } //Debug.Log("Starting Loop for Random turrets"); int rpcount = 0; CryptoRandom rng = new CryptoRandom(); foreach (Transform rp in RigPoints) { if (rpcount > 3) break; // Holds all the possible types for this rig point string possibleTypes = attributes.rigPointType[rpcount]; List<string> typeArray = new List<string>(possibleTypes.Split('|')); int typesPossible = typeArray.Count; // // string debugadd = ""; // // for (int ndx = 0; ndx <= typesPossible; ndx++) // { // debugadd += typeArray[ndx]; // } // // // Possible Tpes // Debug.LogWarning(debugadd); // debugadd = ""; // Holds all the possible Sizes for this rigpoint. string possibleSizes = attributes.rigPointSize[rpcount]; string[] sizeArray = possibleSizes.Split('|'); int sizesPossible = sizeArray.Length; // // // PossibleSizes // for (int ndx = 0; ndx <= sizesPossible; ndx++) // { // debugadd += sizeArray[ndx]; // } // Debug.LogWarning(debugadd); //Debug.LogWarning(sizesPossible.ToString() + " " + typesPossible.ToString()); bool selectingWeapon = true; string weaponSelection = ""; WeaponAttributes weaponSelectionAttributes = null; Weapon.WeaponSize sze = Weapon.WeaponSize.NONE; Weapon.WeaponType tpe = Weapon.WeaponType.NONE; //Debug.LogWarning(typesPossible); int loopCount = 0; while (selectingWeapon) { // Select a random weapon size / type from possibilities. rng = new CryptoRandom(); int pickSize = rng.Next(sizesPossible); rng = new CryptoRandom(); int pickType = pickType = rng.Next(typesPossible); //Debug.LogWarning(pickSize + " " + pickType); sze = (Weapon.WeaponSize) System.Enum.Parse(typeof(Weapon.WeaponSize), sizeArray[pickSize]); tpe = (Weapon.WeaponType) System.Enum.Parse(typeof(Weapon.WeaponType), typeArray[pickType]); //Debug.LogWarning((int)tpe); // Get all the corresponding weapon size dictionary. //Debug.LogWarning(sze.ToString() + " " + tpe.ToString()); Weapon.WeaponTypeCache holder = Game.weaponDictionary[sze.ToString() + "|" + tpe.ToString()]; // Make a list for all the possible weapons in that size. List<WeaponAttributes> weaponsPossible = new List<WeaponAttributes>(); // Insert all weapons possible into that list. foreach (var pair in holder.weapons) { weaponsPossible.Add(pair.Value); } // Select one of the weapons from that list. weaponSelectionAttributes = weaponsPossible[UnityEngine.Random.Range(0,weaponsPossible.Count - 1)]; weaponSelection = weaponSelectionAttributes.path; // // If weapon is selected exit loop. if (weaponSelection.Length > 1) break; // Try 50 times before saying f**k this shit. loopCount++; if (loopCount > 10) return; } // Instantiate proper turret -- Offset it by space between two rig points. Attach. //Debug.Log("Current Position: " + transform.position); //Debug.Log("Weapons/" + sze.ToString() + "/" + tpe.ToString() + "/" + weaponSelection); GameObject tur = PhotonNetwork.Instantiate("Weapons/" + sze.ToString() + "/" + tpe.ToString() + "/" + weaponSelection, rp.position, rp.rotation, 0) as GameObject; Weapon wscript = tur.GetComponent<Weapon>(); wscript.SetAttributes(weaponSelectionAttributes); wscript.owner = this; Weapons.Add(wscript); tur.transform.parent = rp; //tur.transform.position = wscript.owner.transform.position; //tur.transform.localScale = new Vector3(3,3,3); // rPoint or rp figure it out! if (wscript.rigpoint == null) wscript.SetRigPoint(); Vector3 offset = rp.position - wscript.rigpoint.position; tur.transform.position += offset; tur.transform.parent = rp; tur.name = weaponSelection; ++rpcount; } }
public void TOTP_GetExpiryTime() { { Func<DateTime> utcFactory = () => DateTime.UtcNow; DateTime utc = utcFactory(); DateTime expiryTime = Otp.TOTP.GetExpiryTime(); int deltaSeconds = (int)expiryTime.Subtract(utc).TotalSeconds; Assert.IsTrue(deltaSeconds >= 0 && deltaSeconds <= 30, $"deltaSeconds outside expected range [{deltaSeconds.ToString()}]"); } { CryptoRandom rng = new CryptoRandom(); Func<DateTime> utcFactory = () => Otp.TOTP._unixEpoch.AddTicks(rng.NextLong(TimeSpan.FromDays(365.25 * 300).Ticks)); Parallel.For(0, 100000, i => { var utc2 = utcFactory(); DateTime expiryTime = Otp.TOTP.GetExpiryTime(() => utc2); int deltaSeconds = (int)expiryTime.Subtract(utc2).TotalSeconds; Assert.IsTrue(deltaSeconds >= 0 && deltaSeconds <= 30, $"deltaSeconds outside expected range [{deltaSeconds.ToString()}]"); }); } }//TOTP_GetExpiryTime()
public void CryptoRandom_ZeroLengthInput() { var rng = new CryptoRandom(); // While this will do nothing, it's not something that throws. rng.NextBytes(Utils.ZeroLengthArray<byte>.Value); }
static void DifferentSequential(int arraySize) { // Ensure that the RNG doesn't produce a stable set of data. byte[] first = new byte[arraySize]; byte[] second = new byte[arraySize]; var rng = new CryptoRandom(); rng.NextBytes(first); rng.NextBytes(second); // Random being random, there is a chance that it could produce the same sequence. // The smallest test case that we have is 10 bytes. // The probability that they are the same, given a Truly Random Number Generator is: // Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9) // = 1/256 * 1/256 * ... * 1/256 // = 1/(256^10) // = 1/1,208,925,819,614,629,174,706,176 Assert.AreNotEqual(first, second); }
/// <summary> /// The ImageSet2 constructor. /// </summary> /// <param name="type">Specifies the type of data source managed.</param> /// <param name="log">Specifies the output log.</param> /// <param name="factory">Specifies the data factory used to access the database data.</param> /// <param name="src">Specifies the data source descriptor.</param> /// <param name="loadMethod">Specifies the load method used to load the data.</param> /// <param name="random">Specifies the random number generator.</param> /// <param name="rgAbort">Specifies the cancellation handles.</param> public ImageSet2(TYPE type, Log log, DatasetFactory factory, SourceDescriptor src, IMAGEDB_LOAD_METHOD loadMethod, CryptoRandom random, WaitHandle[] rgAbort) : base(factory, src) { m_type = type; m_log = log; m_loadMethod = loadMethod; m_random = random; m_rgAbort.Add(m_evtCancel); if (rgAbort.Length > 0) { m_rgAbort.AddRange(rgAbort); } }
public void CryptoRandom_NullInput() { var rng = new CryptoRandom(); try { rng.NextBytes(null); // should throw } catch (NullReferenceException) { Assert.IsTrue(true); return; } Assert.Fail("Failed to throw NullReferenceException."); }
public void Base64_ToB64Url_Test() { var rnd = new CryptoRandom(); Parallel.For(1, 5000, i => { var byteArray = rnd.NextBytes(i); var offset = 0; var count = Math.Max(i, i - rnd.Next(10)); var byteSegment = new ArraySegment<byte>(byteArray, offset, count); var b64url = byteSegment.ToB64Url(); var b64 = byteSegment.ToB64(); Assert.IsTrue(b64url + b64[b64.Length - 1] == b64); Assert.IsTrue(Enumerable.SequenceEqual(byteSegment, b64url.FromB64Url())); }); }// Base64_ToB64Url_Test()
static void DifferentParallel(int arraySize) { // Ensure that two RNGs don't produce the same data series (such as being implemented via new Random(1)). byte[] first = new byte[arraySize]; byte[] second = new byte[arraySize]; var rng1 = new CryptoRandom(); var rng2 = new CryptoRandom(); rng1.NextBytes(first); rng2.NextBytes(second); // Random being random, there is a chance that it could produce the same sequence. // The smallest test case that we have is 10 bytes. // The probability that they are the same, given a Truly Random Number Generator is: // Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9) // = 1/256 * 1/256 * ... * 1/256 // = 1/(256^10) // = 1/1,208,925,819,614,629,174,706,176 Assert.AreNotEqual(first, second); }
public bool RollReflection() { var rand = new CryptoRandom(); return(rand.Next(0, 101) <= ReflectionChance); }
static void Main(string[] args) { CryptoRandom rng = new CryptoRandom(); Console.WriteLine(rng.Next()); }
public void CryptoRandom_ConcurrentAccess() { const int ParallelTasks = 16; const int PerTaskIterationCount = 20; const int RandomSize = 1024; var tasks = new System.Threading.Tasks.Task[ParallelTasks]; byte[][] taskArrays = new byte[ParallelTasks][]; var rng = new CryptoRandom(); using (var sync = new System.Threading.ManualResetEvent(false)) { for (int iTask = 0; iTask < ParallelTasks; iTask++) { taskArrays[iTask] = new byte[RandomSize]; byte[] taskLocal = taskArrays[iTask]; tasks[iTask] = System.Threading.Tasks.Task.Run( () => { sync.WaitOne(); for (int i = 0; i < PerTaskIterationCount; i++) { rng.NextBytes(taskLocal); } }); } // Ready? Set() Go! sync.Set(); System.Threading.Tasks.Task.WaitAll(tasks); } for (int i = 0; i < ParallelTasks; i++) { // The Real test would be to ensure independence of data, but that's difficult. // The other end of the spectrum is to test that they aren't all just new byte[RandomSize]. // Middle ground is to assert that each of the chunks has neutral(ish) bit parity. AssertNeutralParity(taskArrays[i]); } }
static void Main(string[] args) { const bool SEEDED_TEST = false; const long ITER = 10_000_000L * 2L; const bool IS_SEQUENTIAL = false; const bool IS_PARALLEL = true; if (SEEDED_TEST) { var seedkey = new byte[CryptoRandom.Params.Seeded.SEEDKEY_SIZE]; var seeded = new CryptoRandom(seedkey); Span<byte> data = new byte[256]; seeded.Reseed(seedkey); seeded.NextBytes(data); Convert.ToHexString(data).Dump(); data.Clear(); //seeded = new SeededCryptoRandomImpl(seedkey); seeded.Reseed(seedkey); for (int i = 0; i < data.Length; ++i) { seeded.NextBytes(data.Slice(i, 1)); Convert.ToHexString(data.Slice(0, i + 1)).Dump(); Console.WriteLine("===================="); } return; } var sw = new Stopwatch(); $".NET: [{Environment.Version}]".Dump(); $"{nameof(Environment.ProcessorCount)}: {Environment.ProcessorCount}".Dump(); $"{nameof(CryptoRandom.Params.RNG.BYTE_CACHE_SIZE)}: {CryptoRandom.Params.RNG.BYTE_CACHE_SIZE}".Dump(); $"{nameof(CryptoRandom.Params.RNG.REQUEST_CACHE_LIMIT)}: {CryptoRandom.Params.RNG.REQUEST_CACHE_LIMIT}".Dump(); $"{nameof(TestStruct)} Size: {Utils.StructSizer<TestStruct>.Size}\n".Dump(); for (int _ = 0; _ < 4; ++_) { Guid g = default; cr.Next(ref g); g.Dump(); } "".Dump(); //return; const int REPS = 5; IS_SEQUENTIAL.Dump(nameof(IS_SEQUENTIAL)); IS_PARALLEL.Dump(nameof(IS_PARALLEL)); for (int j = 0; j < REPS; ++j) { { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { var data = default(TestStruct); var span = Utils.AsSpan(ref data); cr.NextBytes(span); }); sw.Stop(); $"{sw.Elapsed} Utils.AsSpan(ref data); cr.NextBytes(span);".Dump(); } { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { var data = default(TestStruct); cr.Next(ref data); }); sw.Stop(); $"{sw.Elapsed} cr.Next(ref data);".Dump(); } { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { var data = default(TestStruct); CryptoRandom.Shared.Next(ref data); }); sw.Stop(); $"{sw.Elapsed} CryptoRandom.Shared.Next(ref data);".Dump(); } { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { cr.NextGuid(); }); sw.Stop(); $"{sw.Elapsed} cr.NextGuid();".Dump(); } { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { cr.Next<Guid>(); }); sw.Stop(); $"{sw.Elapsed} cr.Next<Guid>();".Dump(); } { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { Guid.NewGuid(); }); sw.Stop(); $"{sw.Elapsed} Guid.NewGuid();".Dump(); } { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { cr.SqlServerGuid(); }); sw.Stop(); $"{sw.Elapsed} cr.SqlServerGuid();".Dump(); } { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { cr.Next(); }); sw.Stop(); $"{sw.Elapsed} cr.Next();".Dump(); } { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { cr.NextDouble(); }); sw.Stop(); $"{sw.Elapsed} cr.NextDouble();".Dump(); } { sw.Restart(); Runner(ITER, IS_SEQUENTIAL, IS_PARALLEL, static i => { cr.NextSingle(); }); sw.Stop(); $"{sw.Elapsed} cr.NextSingle();".Dump(); } "".Dump(); }// REPS }//Main()
public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "cookie" }); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = "mvc.owin", Authority = "http://localhost:5000", RedirectUri = "http://localhost:5001/", Scope = "openid profile api1", SignInAsAuthenticationType = "cookie", RequireHttpsMetadata = false, UseTokenLifetime = false, RedeemCode = true, SaveTokens = true, ClientSecret = "secret", ResponseType = "code", ResponseMode = "query", Notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = n => { if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication) { // set PKCE parameters var codeVerifier = CryptoRandom.CreateUniqueId(32); string codeChallenge; using (var sha256 = SHA256.Create()) { var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier)); codeChallenge = Base64Url.Encode(challengeBytes); } n.ProtocolMessage.SetParameter("code_challenge", codeChallenge); n.ProtocolMessage.SetParameter("code_challenge_method", "S256"); // remember code_verifier (adapted from OWIN nonce cookie) RememberCodeVerifier(n, codeVerifier); } return(Task.CompletedTask); }, AuthorizationCodeReceived = n => { // get code_verifier var codeVerifier = RetrieveCodeVerifier(n); // attach code_verifier n.TokenEndpointRequest.SetParameter("code_verifier", codeVerifier); return(Task.CompletedTask); } } }); }
public void Setup() { SymmetricAlgorithm cryptoAlgorithm = Rijndael.Create(); byte[] sequenceKey = pppHelper.GetSequenceKeyFromPassword("zombie"); BigInteger counter = BigInteger.Parse("0"); cryptrnd = new CryptoRandom(cryptoAlgorithm, sequenceKey, counter); Assert.AreEqual(128 / 8, zerobytes.Length, "Zero byte array mismatch!"); }
public void Changing() { CryptoRandom rng = new CryptoRandom(); DescrptHandler display = new DescrptHandler(); double mainSize = VarStorage.Globals.mainSize; double otherSize = VarStorage.Globals.otherSize; double mainFinalSize = VarStorage.Globals.mainSize; double otherFinalSize = VarStorage.Globals.otherSize; string deltaSizeRounded = ""; VarStorage.Globals.percentDelta = ""; int changeType = rng.Next(5) + 1; if (VarStorage.Globals.rollType == 1) { if (changeType <= 5) { double rAmount = rng.Next(110) + 11; double deltaSize = (rAmount / 100) * mainSize; deltaSizeRounded = deltaSize.ToString("0.00"); mainFinalSize = mainSize + Convert.ToDouble(deltaSizeRounded); VarStorage.Globals.changeType = 1; VarStorage.Globals.percentDelta = Convert.ToString(rAmount); } else { double rAmount = rng.Next(Convert.ToInt32(mainSize)); double deltaSize = rAmount / 12; deltaSizeRounded = deltaSize.ToString("0.00"); mainFinalSize = mainSize + Convert.ToDouble(deltaSizeRounded); VarStorage.Globals.changeType = 2; } } else if (VarStorage.Globals.rollType == 2) { if (changeType <= 5) { double rAmount = rng.Next(60) + 11; double deltaSize = (rAmount / 100) * mainSize; deltaSizeRounded = deltaSize.ToString("0.00"); mainFinalSize = mainSize - Convert.ToDouble(deltaSizeRounded); VarStorage.Globals.changeType = 1; VarStorage.Globals.percentDelta = Convert.ToString(rAmount); } else { double rAmount = rng.Next(Convert.ToInt32(mainSize)); double deltaSize = rAmount / 12; deltaSizeRounded = deltaSize.ToString("0.00"); mainFinalSize = mainSize - Convert.ToDouble(deltaSizeRounded); VarStorage.Globals.changeType = 2; VarStorage.Globals.percentDelta = ""; } } else if (VarStorage.Globals.rollType == 3) { if (changeType <= 5) { double rAmount = rng.Next(40) + 11; double deltaSize = (rAmount / 100) * otherSize; deltaSizeRounded = deltaSize.ToString("0.00"); mainFinalSize = mainSize + Convert.ToDouble(deltaSizeRounded); otherFinalSize = otherSize - Convert.ToDouble(deltaSizeRounded); VarStorage.Globals.changeType = 1; VarStorage.Globals.percentDelta = Convert.ToString(rAmount); } else { double rAmount = rng.Next((Convert.ToInt32(otherSize)) - 1); double deltaSize = rAmount / 12; deltaSizeRounded = deltaSize.ToString("0.00"); mainFinalSize = mainSize + Convert.ToDouble(deltaSizeRounded); otherFinalSize = otherSize - Convert.ToDouble(deltaSizeRounded); VarStorage.Globals.changeType = 2; VarStorage.Globals.percentDelta = ""; } } else if (VarStorage.Globals.rollType == 4) { if (changeType <= 5) { double rAmount = rng.Next(60) + 11; double deltaSize = (rAmount / 100) * otherSize; deltaSizeRounded = deltaSize.ToString("0.00"); otherFinalSize = otherSize - Convert.ToDouble(deltaSizeRounded); VarStorage.Globals.changeType = 1; VarStorage.Globals.percentDelta = Convert.ToString(rAmount); } else { double rAmount = rng.Next(Convert.ToInt32(mainSize)); double deltaSize = rAmount / 12; deltaSizeRounded = deltaSize.ToString("0.00"); mainFinalSize = mainSize - Convert.ToDouble(deltaSizeRounded); VarStorage.Globals.changeType = 2; VarStorage.Globals.percentDelta = ""; } } VarStorage.Globals.mainSize = mainSize; VarStorage.Globals.mainFinalSize = mainFinalSize; VarStorage.Globals.otherFinalSize = otherFinalSize; VarStorage.Globals.otherSize = otherSize; VarStorage.Globals.changeDelta = Convert.ToDouble(deltaSizeRounded); VarStorage.Globals.mainCompSize = ((mainFinalSize) * 1828800) / (otherFinalSize); VarStorage.Globals.otherCompSize = ((otherFinalSize) * 1828800) / (mainFinalSize); display.DescPath(); }
// public void Save(string strFile, PwGroup pgDataSource, KdbxFormat fmt, // IStatusLogger slLogger) // { // bool bMadeUnhidden = UrlUtil.UnhideFile(strFile); // // IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile); // this.Save(IOConnection.OpenWrite(ioc), pgDataSource, format, slLogger); // // if(bMadeUnhidden) UrlUtil.HideFile(strFile, true); // Hide again // } /// <summary> /// Save the contents of the current <c>PwDatabase</c> to a KDBX file. /// </summary> /// <param name="sSaveTo">Stream to write the KDBX file into.</param> /// <param name="pgDataSource">Group containing all groups and /// entries to write. If <c>null</c>, the complete database will /// be written.</param> /// <param name="fmt">Format of the file to create.</param> /// <param name="slLogger">Logger that recieves status information.</param> public void Save(Stream sSaveTo, PwGroup pgDataSource, KdbxFormat fmt, IStatusLogger slLogger) { Debug.Assert(sSaveTo != null); if (sSaveTo == null) { throw new ArgumentNullException("sSaveTo"); } if (m_bUsedOnce) { throw new InvalidOperationException("Do not reuse KdbxFile objects!"); } m_bUsedOnce = true; m_format = fmt; m_slLogger = slLogger; m_xmlWriter = null; PwGroup pgRoot = (pgDataSource ?? m_pwDatabase.RootGroup); UTF8Encoding encNoBom = StrUtil.Utf8; CryptoRandom cr = CryptoRandom.Instance; byte[] pbCipherKey = null; byte[] pbHmacKey64 = null; m_pbsBinaries.Clear(); m_pbsBinaries.AddFrom(pgRoot); List <Stream> lStreams = new List <Stream>(); lStreams.Add(sSaveTo); HashingStreamEx sHashing = new HashingStreamEx(sSaveTo, true, null); lStreams.Add(sHashing); try { m_uFileVersion = GetMinKdbxVersion(); int cbEncKey, cbEncIV; ICipherEngine iCipher = GetCipher(out cbEncKey, out cbEncIV); m_pbMasterSeed = cr.GetRandomBytes(32); m_pbEncryptionIV = cr.GetRandomBytes((uint)cbEncIV); // m_pbTransformSeed = cr.GetRandomBytes(32); PwUuid puKdf = m_pwDatabase.KdfParameters.KdfUuid; KdfEngine kdf = KdfPool.Get(puKdf); if (kdf == null) { throw new Exception(KLRes.UnknownKdf + MessageService.NewParagraph + // KLRes.FileNewVerOrPlgReq + MessageService.NewParagraph + "UUID: " + puKdf.ToHexString() + "."); } kdf.Randomize(m_pwDatabase.KdfParameters); if (m_format == KdbxFormat.Default) { if (m_uFileVersion < FileVersion32_4) { m_craInnerRandomStream = CrsAlgorithm.Salsa20; m_pbInnerRandomStreamKey = cr.GetRandomBytes(32); } else // KDBX >= 4 { m_craInnerRandomStream = CrsAlgorithm.ChaCha20; m_pbInnerRandomStreamKey = cr.GetRandomBytes(64); } m_randomStream = new CryptoRandomStream(m_craInnerRandomStream, m_pbInnerRandomStreamKey); } if (m_uFileVersion < FileVersion32_4) { m_pbStreamStartBytes = cr.GetRandomBytes(32); } Stream sXml; if (m_format == KdbxFormat.Default) { byte[] pbHeader = GenerateHeader(); m_pbHashOfHeader = CryptoUtil.HashSha256(pbHeader); MemUtil.Write(sHashing, pbHeader); sHashing.Flush(); ComputeKeys(out pbCipherKey, cbEncKey, out pbHmacKey64); Stream sPlain; if (m_uFileVersion < FileVersion32_4) { Stream sEncrypted = EncryptStream(sHashing, iCipher, pbCipherKey, cbEncIV, true); if ((sEncrypted == null) || (sEncrypted == sHashing)) { throw new SecurityException(KLRes.CryptoStreamFailed); } lStreams.Add(sEncrypted); MemUtil.Write(sEncrypted, m_pbStreamStartBytes); sPlain = new HashedBlockStream(sEncrypted, true); } else // KDBX >= 4 { // For integrity checking (without knowing the master key) MemUtil.Write(sHashing, m_pbHashOfHeader); byte[] pbHeaderHmac = ComputeHeaderHmac(pbHeader, pbHmacKey64); MemUtil.Write(sHashing, pbHeaderHmac); Stream sBlocks = new HmacBlockStream(sHashing, true, true, pbHmacKey64); lStreams.Add(sBlocks); sPlain = EncryptStream(sBlocks, iCipher, pbCipherKey, cbEncIV, true); if ((sPlain == null) || (sPlain == sBlocks)) { throw new SecurityException(KLRes.CryptoStreamFailed); } } lStreams.Add(sPlain); if (m_pwDatabase.Compression == PwCompressionAlgorithm.GZip) { sXml = new GZipStream(sPlain, CompressionMode.Compress); lStreams.Add(sXml); } else { sXml = sPlain; } if (m_uFileVersion >= FileVersion32_4) { WriteInnerHeader(sXml); // Binary header before XML } } else if (m_format == KdbxFormat.PlainXml) { sXml = sHashing; } else { Debug.Assert(false); throw new ArgumentOutOfRangeException("fmt"); } m_xmlWriter = XmlUtilEx.CreateXmlWriter(sXml); WriteDocument(pgRoot); m_xmlWriter.Flush(); } finally { CommonCleanUpWrite(lStreams, sHashing); if (pbCipherKey != null) { MemUtil.ZeroByteArray(pbCipherKey); } if (pbHmacKey64 != null) { MemUtil.ZeroByteArray(pbHmacKey64); } } }
public void TearDown() { cryptrnd = null; }
public void ctor_NullSeqKeyNotAllowed() { //Have to use alternate instance because we are testing //the ctor. CryptoRandom crnd = new CryptoRandom(Rijndael.Create(), null); }
public void ctor_NullCryptoNotAllowed() { //Have to use alternate instance because we are testing //the ctor. CryptoRandom crnd = new CryptoRandom(null, new byte[16]); }