Serial key generation xor string encryption - c#

When I do an xor on a string I get special characters
private void btnEncryptDecrypt_Click(object sender, EventArgs e)
{
byte[] bytes = Encoding.UTF8.GetBytes(keyTextBox.Text);
textTextBox.Text = string.Empty;
foreach (byte i in bytes)
{
byte c = Convert.ToByte(i ^ Convert.ToByte(textBox1.Text));
textTextBox.Text = textTextBox.Text + Convert.ToChar(c);
}
}
62FA7AC4 1234567890 xor to !%QV VT#7&%$#"! /.'
I want to use it for serial key generation with only alphanumeric characters
I want to pass "62FA7AC4", a date and a number between 0 and 5000 and a few random dummy numbers
Input will be "62FA7AC4"+"2500"+"21/05/2018"
Output should be something like "5QBK-J4D1-8CF6-5MW2-78FZ-2FPL-4S6S-CTGB"
What am I doing Wrong?

Try working with numbers, not strings:
using System.Numerics;
...
// Let's use BigInteger for arbitrary long values
BigInteger left = BigInteger.Parse("62FA7AC4", NumberStyles.HexNumber);
BigInteger right = BigInteger.Parse("1234567890", NumberStyles.HexNumber);
string result = (left ^ right).ToString("X");
Console.Write(result);
So you have
1256AC0254
Edit: As far as I can see you want alphanumeric (i.e. Base 36 == 26 letters + 10 digits output). You can use the same approach: operate with integer(s), not string(s)
private static Random s_Random = new Random();
...
BigInteger value = BigInteger.Parse(
"0" + // we don't want negative values
"62FA7AC4" + // header
s_Random.Next(5001).ToString("0000") + // random in [0..5000] range
DateTime.Today.ToString("ddMMyyyy"), // Date like 21052018
NumberStyles.HexNumber);
Then do any xor (if you like):
value ^= some_secret_value;
Finally represent the value in base 36:
private static String ToBase36(BigInteger value) {
List<char> list = new List<char>();
for (int index = 0; value > 0; value /= 36, index++) {
if (index > 0 && index % 4 == 0)
list.Add('-');
BigInteger v = value % 36;
list.Add(v < 10 ? (char)('0' + v) : (char) ('A' + v - 10));
}
list.Reverse();
return string.Concat(list);
}
Test:
BigInteger value = BigInteger.Parse(
"0" +
"62FA7AC4" +
"2500" +
DateTime.Today.ToString("ddMMyyyy"),
NumberStyles.HexNumber);
string result = ToBase36(value);
Console.Write(result);
Outcome:
2443-WNC5-AVBB-M32W
Edit 2: To restore the original number
private static BigInteger FromBase36(string value) {
BigInteger result = 0;
BigInteger power = 1;
for (int i = value.Length - 1; i >= 0; --i) {
char item = value[i];
if (item >= '0' && item <= '9') {
result += power * (item - '0');
power *= 36;
}
else if (item >= 'A' && item <= 'Z') {
result += power * (item - 'A' + 10);
power *= 36;
}
else if (item >= 'a' && item <= 'z') {
result += power * (item - 'a' + 10);
power *= 36;
}
}
return result;
}
e.g.
BigInteger value = BigInteger.Parse(
"0" +
"62FA7AC4" +
"2500" +
DateTime.Today.ToString("ddMMyyyy"),
NumberStyles.HexNumber);
string result = ToBase36(value);
BigInteger back = FromBase36(result);
Console.WriteLine(string.Join(Environment.NewLine, value, result, back));
Outcome:
467412447575903165554712
2443-WNC5-AVBB-M32W
467412447575903165554712

Related

Convert oct to dex integer

Incorrectly converts a number
In the program you need to convert from octal number system to decimal
"a" is a integer class field that uses the GetDex() method
Construct - this.a = a;
public int GetDex()
{
int res = 0;
int exp = 1;
for (int i = Convert.ToString(a).Length - 1; i >= 0; i--)
{
res += exp * Convert.ToInt32(Convert.ToString(a)[i]);
exp *= 8;
}
return res;
}
The problem is in the
Convert.ToInt32(Convert.ToString(a)[i])
fragment. You actually add ascii codes, not digits. To get digit integer 5 from character '5' just subtract '0':
(Convert.ToString(a)[i] - '0')
Your code corrected:
public int GetDex()
{
int res = 0;
int exp = 1;
for (int i = Convert.ToString(a).Length - 1; i >= 0; i--)
{
//DONE: you should add digits, not ascii codes: - '0'
res += exp * (Convert.ToString(a)[i] - '0');
exp *= 8;
}
return res;
}
You can put it compact with a help of Linq:
public int GetDex() => a
.ToString()
.Aggregate(0, (s, i) => s * 8 + i - '0');

Increment a unique field with specified character pattern

I am trying to find a way to increment a user defined idenitifer. I have written something that achieves what I want the code to do, but I highly doubt it's the best way to do this:
The character pattern is:
AAA000
AAA999
BAA000
BAA999
BBA000
And so on, although:
AAA000
AAA999
BAA000
BAA999
CAA000
Would be acceptable.
Here is my code to just generate that pattern:
int i = 30;
char char1 = 'A';
char char2 = 'A';
char char3 = 'A';
double number = 998;
for (int j = 0; j < i; j++)
{
string id = $"{char1}{char2}{char3}{number.ToString().PadLeft(3, '0')}";
if (number == 999)
{
number = 998;
if (char1 == char2 && char1 == char3 && char1 != 'Z')
{
char1++;
}
else if (char1 > char2 && char2 != 'Z')
{
char2++;
}
else if (char3 != 'Z')
{
char3++;
}
}
else
{
number++;
}
Console.WriteLine(id);
}
To clarify, I need to build a function that can take the latest value, for example:
DEF123
which in turn will return:
DEF124
Or DEF999 which will return DEG000.
Using Maximillians answer, I have amended the method:
static void NextId(string highestId)
{
char startChar1 = highestId[0];
char startChar2 = highestId[1];
char startChar3 = highestId[2];
int startNumber = int.Parse(highestId.Substring(highestId.Length - 3));
int n = 1;
int i = 0;
for (char char1 = startChar1; char1 <= 'Z' && i < n; char1++)
{
for (char char2 = startChar2; char2 <= 'Z' && i < n; char2++)
{
for (char char3 = startChar3; char3 <= 'Z' && i < n; char3++)
{
for (int number = startNumber; number < 1000 && i < n; number++)
{
string id = $"{char1}{char2}{char3}{number.ToString().PadLeft(3, '0')}";
Console.WriteLine(id);
i++;
}
}
}
}
}
This is almost perfect, except:
DEZ998 returns DEZ998, DEZ999 being the highest id passed in returns DEZ999.
Any recommendations on achieving this would be a great help.
I had to do some assumptions on your pattern, but as far as I understood your question I'd use nested loops instead one loop to rule them all.
int n = 30;
int i = 0;
for (char char1 = 'A'; char1 <= 'Z' && i < n; char1++)
{
for (char char2 = 'A'; char2 <= 'Z' && i < n; char2++)
{
for (char char3 = 'A'; char3 <= 'Z' && i < n; char3++)
{
for(int number = 0; number < 1000 && i < n; number++)
{
string id = $"{char1}{char2}{char3}{number.ToString().PadLeft(3, '0')}";
Console.WriteLine(id);
i++;
}
}
}
}
This will:
Increment the number from 0 to 999
Afterwards it'll increment Char1 by one and start again at (1.) until Z is reached
Afterwards it'll increment Char2 by one and start again at (2.) until Z is reached
Afterwards it'll increment Char3 by one and start again at (3.) until Z is reached
It will stop at any point if the maximum amount(n) is reached
→ You will get a maximum amout of 17575999 possible unique ID's
Update:
The method GetNextId(Tuple<char, char, char, int> id) could help you for that. It calculates the next ID depending on the previous one.
void GenerateIDs()
{
char char1 = 'B';
char char2 = 'F';
char char3 = 'A';
int number = 159;
int n = 30;
// this one is the current ID
var iterationId = new Tuple<char, char, char, int>(char1, char2, char3, number);
for(int i = 1; i < n; i++)
{
iterationId = GetNextId(iterationId);
Console.WriteLine(IdToString(iterationId));
}
}
/// returns: c1Next, c2Next, c3Next, numberNext
private Tuple<char, char, char, int> GetNextId(Tuple<char, char, char, int> id)
{
var number = id.Item4 + 1;
var c3 = id.Item3;
var c2 = id.Item2;
var c1 = id.Item1;
if(number > 999)
{
number = 0;
c3++;
if(c3 > 'Z')
{
c3 = 'A';
c2++;
if (c2 > 'Z')
{
c2 = 'A';
c1++;
if(c1 > 'Z')
{
throw new IndexOutOfRangeException("Next ID bigger than \"ZZZ999\"");
}
}
}
}
return new Tuple<char, char, char, int>(c1, c2, c3, number);
}
private string IdToString(Tuple<char, char, char, int> id)
{
return $"{id.Item1}{id.Item2}{id.Item3}{id.Item4.ToString().PadLeft(3, '0')}";
}
Alternatevly
You could just store an int to the database and use the values 0 to 17575999 and then calculate the display ID
private string IntToId(int intId)
{
var number = intId % 1000;
intId /= 1000;
char c3 = (char) ('A' + (intId % 26));
intId /= 26;
var c2 = (char) ('A' + (intId % 26));
intId /= 26;
var c1 = (char) ('A' + (intId % 26));
return $"{c1}{c2}{c3}{number.ToString().PadLeft(3, '0')}";
}
private int IdToInt(string id)
{
int c1 = id[0] - 'A';
int c2 = id[1] - 'A';
int c3 = id[2] - 'A';
int number = Int32.Parse(id.Substring(3));
return ((((((c1 * 26) + c2) *26) + c3) * 1000) + number);
}

How do I print my output from left to right?

Below codes run perfectly fine. But how to I print converted number in left to right manner. For example if I input 898989, it will give me the output DB7AD. How do I print
DB7AD to
D
B
7
A
D
Codes:
public static void Main()
{
int decimalNumber, quotient;
int i = 1, j, num = 0;
char [] hexadecimalNumber = new char[100];
char temp;
Console.WriteLine("Decimal to HexaDecimal conversion using Ascii code.\n");
Console.WriteLine("Input DECIMAL NUMBER(S) you want to convert to HEXADECIMAL(S):\t\n");
Console.Write("Decimal Numbers : \t");
decimalNumber = int.Parse(Console.ReadLine());
quotient = decimalNumber;
while (quotient != 0)
{
num = quotient % 16;
if (num < 10)
num = num + 48;
else
num = num + 55;
temp = Convert.ToChar(num);
hexadecimalNumber[i++] = temp;
quotient = quotient / 16;
}
Console.Write("HexaDecimal Numbers : \t");
for (j = i - 1; j > 0; j--)
Console.Write(hexadecimalNumber[j]);
Console.WriteLine();
Console.Read();
}
Since you are printing your number character-by-character, you need to modify this loop
for (j = i - 1; j > 0; j--) {
Console.Write(hexadecimalNumber[j]);
}
in such a way as to print zero tabs before the first digit, one tab before the second digit, two tabs before the third digit, and so on. You can do it by making a string tabs variable, and adding a "\t" to it after each iteration:
string tabs = "";
for (j = i - 1; j > 0; j--) {
Console.WriteLine(tabs + hexadecimalNumber[j]);
tabs += "\t";
}
Demo on ideone.

.NET Conversion of very large numbers to different number base

Is there any way to convert very large binary, decimal and hexadecimal numbers to each other?
I have to use it to simulate addressing process up to 256 bits.
I want to do the following conversions (and if it's possible, store them in one object)
very large binary number -> very large decimal number
very large binary number -> very large hexadecimal number
very large decimal number -> very large binary number
very large decimal number -> very large hexadecimal number
very large hexadecimal number -> very large binary number
very large hexadecimal number -> very large decimal number
very large binary number -> string
very large decimal number -> string
very large hexadecimal number -> string
The possibility of splitting and joining very large binary numbers is very important.
If it's possible, I would use a class supported solution, and avoid manual conversion from one number base to another using byte[] type.
I've tried the BigInteger class, it can store very large numbers, but can't convert them to another number base.
Solution by Andrew Jonkers :
//Convert number in string representation from base:from to base:to.
//Return result as a string
public static String Convert(int from, int to, String s)
{
//Return error if input is empty
if (String.IsNullOrEmpty(s))
{
return ("Error: Nothing in Input String");
}
//only allow uppercase input characters in string
s = s.ToUpper();
//only do base 2 to base 36 (digit represented by characters 0-Z)"
if (from < 2 || from > 36 || to < 2 || to > 36)
{ return ("Base requested outside range"); }
//convert string to an array of integer digits representing number in base:from
int il = s.Length;
int[] fs = new int[il];
int k = 0;
for (int i = s.Length - 1; i >= 0; i--)
{
if (s[i] >= '0' && s[i] <= '9') { fs[k++] = (int)(s[i] - '0'); }
else
{
if (s[i] >= 'A' && s[i] <= 'Z') { fs[k++] = 10 + (int)(s[i] - 'A'); }
else
{ return ("Error: Input string must only contain any of 0-9 or A-Z"); } //only allow 0-9 A-Z characters
}
}
//check the input for digits that exceed the allowable for base:from
foreach(int i in fs)
{
if (i >= from) { return ("Error: Not a valid number for this input base"); }
}
//find how many digits the output needs
int ol = il * (from / to+1);
int[] ts = new int[ol+10]; //assign accumulation array
int[] cums = new int[ol+10]; //assign the result array
ts[0] = 1; //initialize array with number 1
//evaluate the output
for (int i = 0; i < il; i++) //for each input digit
{
for (int j = 0; j < ol; j++) //add the input digit
// times (base:to from^i) to the output cumulator
{
cums[j] += ts[j] * fs[i];
int temp = cums[j];
int rem = 0;
int ip = j;
do // fix up any remainders in base:to
{
rem = temp / to;
cums[ip] = temp-rem*to; ip++;
cums[ip] += rem;
temp = cums[ip];
}
while (temp >=to);
}
//calculate the next power from^i) in base:to format
for (int j = 0; j < ol; j++)
{
ts[j] = ts[j] * from;
}
for(int j=0;j<ol;j++) //check for any remainders
{
int temp = ts[j];
int rem = 0;
int ip = j;
do //fix up any remainders
{
rem = temp / to;
ts[ip] = temp - rem * to; ip++;
ts[ip] += rem;
temp = ts[ip];
}
while (temp >= to);
}
}
//convert the output to string format (digits 0,to-1 converted to 0-Z characters)
String sout = String.Empty; //initialize output string
bool first = false; //leading zero flag
for (int i = ol ; i >= 0; i--)
{
if (cums[i] != 0) { first = true; }
if (!first) { continue; }
if (cums[i] < 10) { sout += (char)(cums[i] + '0'); }
else { sout += (char)(cums[i] + 'A'-10); }
}
if (String.IsNullOrEmpty(sout)) { return "0"; } //input was zero, return 0
//return the converted string
return sout;
}
I had the same issue once. I wrote simple method which changes array of decimal numbers to array of binary numbers.
private int[] ConvertDecimalCharArrayToBinaryCharArray(int[] decimalValues)
{
List<int> result = new List<int>();
bool end = false;
while (end == false)
{
result.Add(decimalValues[decimalValues.Length - 1] % 2);
int previous = 0;
bool allzeros = true;
for (int i = 0; i < decimalValues.Length; i++)
{
var x = decimalValues[i];
if (x != 0)
{
allzeros = false;
}
if (allzeros && i == decimalValues.Length - 1)
{
end = true;
}
var a = (x + previous) / 2;
if ((x + previous) % 2== 1)
{
previous = 10;
}
else
{
previous = 0;
}
decimalValues[i] = a;
}
}
result.RemoveAt(result.Count - 1);
result.Reverse();
return result.ToArray();
}

Column No to Column Letter in Excel/VSTO using C#

How to find column's name or header?
For example if i select column 5 in excel means i want the result as "E".
How to get the alphabet or letter corresponding to column no.
Please help me with the code
public static string GetColumnName(int columnNumber)
{
const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string columnName = "";
while (columnNumber > 0)
{
columnName = letters[(columnNumber - 1) % 26] + columnName;
columnNumber = (columnNumber - 1) / 26;
}
return columnName;
}
What about using Application.ActiveCell.get_Address(true, true, Excel.AlReferenceStyle.xlA1, missing, missing) and then parse the result string or use a RegEx to get the column heading?
I simply used:
string location = Application.ActiveCell.get_Address(true, true, Excel.AlReferenceStyle.xlA1, missing, missing);
string tokens = x.Split("$".ToCharArray());
MessageBox.Show(String.Format("Column {0}", result[0]));
public static long GetColumnNumber(string columnName)
{
int letterPos = 0;
long columnNumber = 0;
for (int placeHolder = columnName.Length - 1; placeHolder >= 0; placeHolder--)
{
int currentSum = 1;
for (int multiplier = 0; multiplier < placeHolder; multiplier++)
currentSum *= 26;
int letterValue = (int) columnName[letterPos];
currentSum *= letterValue - 64;
columnNumber += currentSum;
if (letterPos != columnName.Length)
letterPos++;
//Console.WriteLine(((int)columnName[i]-64) + " = " + columnName[i]);
}
return columnNumber;
}
The following is a complete method which gives you the corresponding alphabet for an integer value that is passed.
private String Number2String(int number, bool isCaps)
{
int number1 = number / 27;
int number2 = number - (number1 * 26);
if (number2 > 26)
{
number1 = number1 + 1;
number2 = number - (number1 * 26);
}
Char a = (Char)((isCaps ? 65 : 97) + (number1 - 1));
Char b = (Char)((isCaps ? 65 : 97) + (number2 - 1));
Char c = (Char)((isCaps ? 65 : 97) + (number - 1));
string d = String.Concat(a, b);
if (number <= 26)
return c.ToString();
else
return d;
}
I use these two:
public string GetExcelColumn(int index)
{
int quotient = index / 26;
if (quotient > 0)
return GetExcelColumn(quotient - 1) + (char)((int)'A' + (index % 26));
else
return "" + (char)((int)'A' + index);
}
static IEnumerable<string> GetExcelColumns()
{
var alphabet = new string[]{""}.Union(from c in Enumerable.Range((int)'A', 26) select Convert.ToString((char)c));
return from c1 in alphabet
from c2 in alphabet
from c3 in alphabet.Skip(1) // c3 is never empty
where c1 == string.Empty || c2 != string.Empty // only allow c2 to be empty if c1 is also empty
select c1 + c2 + c3;
}
This works well in VBA by using a double replace, where R is a Single Cell Excel Range:
ColumnLetter = Replace(Replace(R.AddressLocal(ReferenceStyle:=1), "$", vbNullString), R.Row, vbNullString)
It is based on the equivalent idea for use on a Worksheet. In a Cell Formula use this, it is even shorter:
=SUBSTITUTE(ADDRESS(1,COLUMN(M1),4),1,"")
This returns the letter M and works right up to Column XFD. The cell reference M1 can be any Range anywhere. The top left Column is returned for Ranges or more than one cell.
It gets the ADDRESS of the first Cell in the Column and then removes the trailing 1 by substituting a NullString for it. (The 4 in the ADDRESS makes sure that the Address is returned as a Relative Address, i.e. one without and $ signs in it.)
Thanks to barry houdini who set me off on the quest for a good answer to this.

Categories