I have a quick question. I have a keygen to generate random passwords for my app. It generates capital letters and numbers but I want it to be like in some programs that formats their code like this xxxx-xxxx-xxxx. so far my code is this
Random random = new Random(0);
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = getrandomcode();
}
public string getrandomcode()
{
char[] tokens = {'0', '1', '2', '3', '4', '5', '7', '8', '9', 'A', 'B', 'C',
'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char[] codeArray = new char[24];
for (int i = 0; i < 24; i++)
{
int index = random.Next(tokens.Length - 1);
codeArray[i] = tokens[index];
}
return new String(codeArray);
}
Its something simple not to complex so I hope there is a way to implement the "-" to this code.
thanks in advance!
Include this in your 'for' loop :
if (i % 5 == 4)
{
codeArray[i] = '-';
}
else
{
int index = random.Next(tokens.Length - 1);
codeArray[i] = tokens[index];
}
Or if you want to use regular expression, try this:
textBox1.Text = Regex.Replace(getrandomcode(), #"(\w{4})(\w{4})(\w{4})(\w{4})(\w{4})", "$1-$2-$3-$4-$5")
Try this:
for (int i = 0; i < 24; i++)
{
if (i % 5 == 4) {
codeArray[i] = '-';
} else {
int index = random.Next(tokens.Length - 1);
codeArray[i] = tokens[index];
}
}
If you want your password to have 24 non-dash characters, change the 24 to 29.
But I also have to tell you that using a random function seeded with 0 is not a very secure way to generate passwords. If the application is stopped and restarted, it will generate the same set of passwords the second time that it did the first time. It is better to not pass an initialization argument in which case it will use the time to seed the random number generator.
If these passwords are going to be used for something important or something which the whole world can access (or both), then even this isn't really random enough to be secure. You should look at cryptographic random number generators like System.Security.Cryptography.RNGCryptoServiceProvider
Related
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 2 years ago.
I'm quite new to C# and I made this method to create random words and it takes in a minimum length and maximum as a parameter. But when I put it in a for loop 20 times I can see that every few in a row are identical. How do I fix this?
static string makename(int min, int max)
{
Random rnd = new Random();
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
char[] consonants = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z' };
int namelength = rnd.Next(min, max);
char twoago = '2';
char oneago = '1';
string name = "";
for (int i = 0; i < namelength; i++)
{
if (oneago != twoago)
{
twoago = oneago;
if (rnd.Next(0, 2) == 1)
{
name = name + vowels[rnd.Next(0, vowels.Count())];
oneago = 'v';
}
else
{
name = name + consonants[rnd.Next(0, consonants.Count())];
oneago = 'c';
}
}
else if (oneago == 'c')
{
name = name + vowels[rnd.Next(0, vowels.Count())];
oneago = 'v';
}
else
{
name = name + consonants[rnd.Next(0, consonants.Count())];
oneago = 'c';
}
if (i == 0)
{
name = name.ToUpper();
}
}
return name;
}
Here is an example of the output (parameters are 4,10) (there was one output before this I cut off):console
When you instantiate the Random (with new Random();) random is being reset to the system clock. Your method is getting called quickly enough that the call is sometimes getting the same system clock time. Random on a computer is never random. It is based on a fairly random mathematical function that behaves fairly randomly as long as it is seeded (started) with a different number each time.
Note, you only need to seed random once for an application run in order for it to behave randomly. It is when you seed it multiple times that you get into trouble.
I have a reshuffle method that is of string type and it takes a char array as an argument it must randomize the characters inside the array each time the Encrypt method is used .. when I tried to call it in another method it gives me the syntax error "Method has some invalid arguments" This is the code
char[] p = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
string reshuffle(char[] alpas)
{
Random random=new Random();
for (int t = 0; t < alpas.Length; t++)
{
char tmp = alpas[t];
int r = random.Next(t, alpas.Length);
alpas[t] = alpas[r];
alpas[r] = tmp;
}
return new string (alpas);
}
public string Encrypt(string pt)
{
reshuffledChars=reshuffle(p[25]);
char[] ch = reshuffledChars.ToCharArray();
char[] buffer = new char[(pt.Length)];
for(int i=0;i<pt.Length;i++)
{
for(int j=0;j<26;j++)
{
if (char.ToUpper(p[j]) == pt[i])
{
buffer[i] = char.ToUpper(ch[j]);
break;
}
else if(char.ToLower(p[j])==pt[i])
{
buffer[i] = char.ToLower(ch[j]);
break;
}
else if(pt[i]==' ')
{
buffer[i] = ' ';
}
}
}
return new string(buffer);
}
Instead of passing reshuffle(p[25]), which is a single char, you should pass the entire array, like so: reshuffle(p).
In this line:
"reshuffledChars=reshuffle(p[25]);"
p[25] returns a char
This line in Encrypt():
reshuffle(p[25]);
should (I'm assuming) be:
reshuffle(p);
You're passing a char not a char[] to reshuffle() -- p[25] is the last char in the array p.
BTW if p should remain unchanged you'll need to copy it before passing to reshuffle.
You are passing wrong parameters instead of reshuffle(p[25]) use reshuffle(p) to send entire array.
If you are looking for a random string generator, this link will help. I have provided a working example in dotnet fiddle.
using System;
using System.Linq;
namespace Rextester
{
public class Program
{
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine(RandomString(8));
}
}
}
I have 4 buttons on my form and I want the user to input his word by clicking up, down, left and right on the buttons.
Image of the example form
The user can choose his letter, number or symbol by going up and down.
Left and right will be for going back and forth in the word. Back in case he made a mistake and forward in case he wants to confirm his current letter.
these are the variables
private string word;
private StringBuilder sb = new StringBuilder();
private char[] wordsAndLetters = { ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',', '.', '!', '?' };
Now we need to give the buttons the option to go between the letters, etc.
private int i;
public Form1()
{
InitializeComponent();
tbOutput.Text = word;
}
private void btnUp_Click(object sender, EventArgs e)
{
//We don't want the i to go above the array
if (i <= 39)
{
i = i + 1;
}
tbOutput.Text = word + Convert.ToString(wordsAndLetters[i]);
}
private void btnDown_Click(object sender, EventArgs e)
{
//We don't want the i to go below the array
if (i > 0)
{
i = i - 1;
}
tbOutput.Text = word + Convert.ToString(wordsAndLetters[i]);
}
private void btnRight_Click(object sender, EventArgs e)
{
tbOutput.Text = word;
sb.Append(wordsAndLetters[i]);
word = sb.ToString();
i = 0;
tbOutput.Clear();
tbOutput.Text = word;
}
private void btnLeft_Click(object sender, EventArgs e)
{
int lengthword = sb.Length;
sb.Remove(lengthword -1, 1);
word = sb.ToString();
tbOutput.Clear();
tbOutput.Text = word;
}
}
This is what I have right now and it works but it isn't flawless. Do you guys have any way of making my current program better?
You cannot technically add to an existing string, as they are immutable. Instead, here are a couple simple options:
1) Concatenate the new character each time.
word += wordsAndLetters[i];
//Which is the same as:
//word = word + wordsAndLetters[i];
2) Use a StringBuilder as Jay mentions in his comment to your post.
StringBuilder sb = new StringBuilder();
sb.Append(wordsAndLetters[i]);
word = sb.ToString();
I am trying to write to a new file (create a new file), and I want everything that is shown in the command console (the 26 shifts) when the program runs to all be shown in the new file. However, when I use file.WriteAllText() it overwrites each shift and then only shows the 26th shift in the new file I create.
using System;
using System.IO;
namespace ceasarAssignment
{
public class caesarShift
{
public static void Main()
{
string file = #"text.txt", // Name of the file that is being read from
encrypted = File.ReadAllText(file), // Reading the file
decrypted = " ";
char character = '0';
int shift = 0;
encrypted = encrypted.ToUpper(); // Puts the string into uppercase
char[] alph = new char[26] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
// The array above is the alphabet (26 characters)
Console.WriteLine("Encrypted text: \n{0}", encrypted);
//Shows the encrypted text before it is decrypted
for (int i = 0; i < alph.Length; i++) //adds a counter so that this for loop will repeat until it has happened 26 times
{
decrypted = "";
foreach (char c in encrypted)
{
character = c;// each letter in the file is now defined as a 'character'
if (!char.IsLetter(c)) {
decrypted += c;
continue;
}
shift = Array.IndexOf(alph, character) - i; //searchs the array for the character then minuses the counter to add the correct shift
if (shift <= 0)
shift = shift + 26;// if the character is at the beginning of the array go to the end
if (shift >= 26)
shift = shift - 26;// if the character is at the end of the array go to the beginning
decrypted += alph[shift];
}
Console.WriteLine("\n Shift {0} \n {1}", i+1, decrypted); //Shows the decrypted code for each 26 shifts
}
}
}
}
You need to use File.AppendAllText(path, appendText)
File.WriteAllText() will overwrite the file each time the loop is run
I am currently writing a Caesar Cipher program in C# for my assignment and I am having a problem.
I am approaching this task using an array where I store the whole alphabet and I declare a shift variable which is defined by character index in the array - the iteration of a for loop. The shift calculation is done in a foreach loop, that fetches a character from a string that is read from a text file. Foreach loop is contained within a for loop that iterates to output every possible shift.
However, the problem is that when I try to access the character in an array by a value of my shift variable, the program doesn't seem to access the character I want, it just outputs the same character as in the original string.
This is the code for the program:
using System;
using System.IO;
public class caesar_shift
{
public static void Main()
{
string file = #"C:\Users\terasss2\Desktop\Programming and Data Structures\caesarShiftEncodedText.txt"; //String variable that stores a file location
string encrypted_text = File.ReadAllText(file); //String variable that contains the text from a file. To get the text, the method in a class SystemIO is ran to read the text. It expects a parameter, which is a file directory.
string decoded_text = " ";
int shift = 0;
char character = '0';
char[] alphabet = new char[26]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
Console.WriteLine("The encrypted text is \n{0}", encrypted_text); //Display the encrypted text
for(int i = 0; i < alphabet.Length; i++) //Start a loop which will display 25 different candidates of decipher
{
foreach(char c in encrypted_text)
{
character = c;
if(character == '\'' || character == ' ')
continue;
shift = Array.IndexOf(alphabet, character) - i; //Define a shift which is the index of a character in an alphabet array, take away the itteration of this loop. Store the result in a variable
if(shift <= 0)
shift = shift + 26;
if(shift >= 26)
shift = shift - 26;
character = alphabet[shift]; //Set the character to a shifted letter by accessing the array element of a value shift
Console.WriteLine(character);
decoded_text = decoded_text + character;
}
Console.WriteLine("\nShift {0} \n {1}",i + 1, decoded_text);
}
}
}
I played a bit with your code. The following gives you the solution, but you have to take care: you couldonly use capital letters, because theres a difference in upper and lower charts. I used the ToUpper() method. Works fine for me. I think that's what your problem was.
public static void Main()
{
string encrypted_text = "BCD"; //String variable that contains the text from a file. To get the text, the method in a class SystemIO is ran to read the text. It expects a parameter, which is a file directory.
string decoded_text = " ";
int shift = 0;
char character = '0';
encrypted_text = encrypted_text.ToUpper();
char[] alphabet = new char[26] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
Console.WriteLine("The encrypted text is \n{0}", encrypted_text); //Display the encrypted text
for (int i = 0; i < alphabet.Length; i++) //Start a loop which will display 25 different candidates of decipher
{
decoded_text = "";
foreach (char c in encrypted_text)
{
character = c;
if (character == '\'' || character == ' ')
continue;
shift = Array.IndexOf(alphabet, character) - i; //Define a shift which is the index of a character in an alphabet array, take away the itteration of this loop. Store the result in a variable
if (shift <= 0)
shift = shift + 26;
if (shift >= 26)
shift = shift - 26;
decoded_text += alphabet[shift];
}
Console.WriteLine("\nShift {0} \n {1}", i + 1, decoded_text);
}
}
I took a look at your code and made a slight adjustment. First of all, I converted it to a method that lets you pass in the string and the amount you want to shift, so that you can either call it in a loop from 0 to 25 to see all the permutations, or you can just get a single value. I also check to see if each character is actually in the array, and if it isn't, then don't change it (in your code you were only checking for '\' and ' ' characters:
public static string ShiftText(string input, int shiftAmount)
{
if (input == null) return null;
char[] alphabet =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
shiftAmount %= 26; // Ensure shift is between 0 and 25
var shiftedText = string.Empty;
foreach (var character in input)
{
var index = Array.IndexOf(alphabet, character);
if (index < 0)
{
// This character isn't in the array, so don't change it
shiftedText += character;
}
else
{
var newIndex = index - shiftAmount;
// If it's negative, wrap around to end of array
if (newIndex < 0) newIndex += 26;
shiftedText += alphabet[newIndex];
}
}
return shiftedText;
}
But another way to do this that works for upper AND lower case, and which is less code, is to simply test if char.IsLetter(character), and then shift the ASCII value of the character within the same 0-25 range.
For example, this does the same as the code above, only it works for lower case letters as well. The difference here is that before we compare the character to our lowest valued character ('a' or 'A'), we test if char.IsLower() first. This way we stay within the ASCII range for this character set:
/// <summary>
/// This method takes the input string and shifts all letter characters
/// to the left (subtracts) by the amount specified in shiftAmount, so
/// if shiftAmount = 1, then 'M' becomes 'L', and 'a' becomes 'z'.
/// </summary>
/// <param name="input">The input string to apply changes to</param>
/// <param name="shiftAmount">A value from 0 to 25, used to shift the characters</param>
/// <returns>The modified (shifted) string</returns>
public static string ShiftText(string input, int shiftAmount)
{
if (input == null) return null;
// Ensure shift is between 0 and 25
shiftAmount %= 26;
var result = string.Empty;
// Loop through input and update result with shifted letters
foreach (var character in input)
{
if (!char.IsLetter(character))
{
// If the character isn't a letter, don't change it
result += character;
}
else
{
var newChar = (char) (character - shiftAmount);
// Adjust newChar to stay within this character range
if (newChar < (char.IsLower(character) ? 'a' : 'A')) newChar += (char) 26;
result += newChar;
}
}
return result;
}
Why don't you just use character's ASCII values. I would convert ciphertext to lower case first. For example a's asci value is 97. I would write a method to extract 97 every characters so a=0,b=1..... z=25. Then for every character in your ciphertext get -3 shifted value of that char.For example input char d should return value 0 which corresponds a.