i was going through encryption today and my colleague told me a simpler/custom way to do it, what i did is listed down there, so can you please tell me what type of encryption or hashign is that? he told me that this is the mixture of some sort of hashing and encryption. Sorry for stupid question i am new here. :)
the below method takes a string (password in my case). reverses it and makes a dictionary (adding dictionary items are listed below) and matches the keys and values and return encrypted data.
public static string Encrypt(string source)
{
string enCrypted = "";
try
{
source = Reverse(source);
Dictionary<char, char> sourceTable = AddDictionaryItems();
char[] sourceArray = source.ToCharArray();
StringBuilder encryptedData = new StringBuilder();
foreach (char chr in sourceArray)
{
KeyValuePair<char, char> Pair;
Pair = sourceTable.First(tuple => tuple.Key == chr);
encryptedData.Append(Pair.Value);
}
enCrypted=encryptedData.ToString();
}
catch (Exception ex)
{
}
return enCrypted;
}
the below method adds items into dictionary, items are basically based on ascii codes. i loop through all asciis and then corresponding charachters are added in the dictionary. but the real trick is that when adding an item in the dictionary. e.g., when i add 'A' in dictionary as a key, then its value would be 'D'. the variable "jump" specifies the difference between key and value. so if my password is 'ABC' it would return 'DEF' or 'FED' if i reverse that thing.
public static Dictionary<char, char> AddDictionaryItems()
{
Dictionary<char, char> dc = new Dictionary<char, char>();
try
{
int initial = 33;
int jump = 3;
int final = 127 - jump;
for (int ascii = initial; ascii < final; ascii++)
{
dc.Add((char)ascii, (char)(ascii + jump));
}
for (int ascii = final; ascii < final + jump; ascii++)
{
dc.Add((char)ascii, (char)(initial));
initial++;
}
}
catch (Exception ex)
{
throw ex;
}
return dc;
}
That would be a Substitution Cipher, however unless you are making this for fun, do not use this method for anything that requires security. 1000's of people crack this encryption method every day for fun (check your local newspaper, it likely has one too, it is usually next to the crossword).
guys i have tailored my code
public static string Reverse(string str)
{
char[] charArray = str.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public static string Encrypt(string source)
{
string prefix = Guid.NewGuid().ToString();
string infix = Guid.NewGuid().ToString();
string postfix = Guid.NewGuid().ToString();
int length = source.Length;
string firstHalf = source.Substring(0, length / 2);
string secondHalf = source.Substring(length / 2);
string ConcatedPassword = prefix + firstHalf + infix + secondHalf + postfix;
string enCrypted = "";
try
{
ConcatedPassword = Reverse(ConcatedPassword);
Dictionary<char, char> sourceTable = AddDictionaryItems();
char[] sourceArray = ConcatedPassword.ToCharArray();
StringBuilder encryptedData = new StringBuilder();
foreach (char chr in sourceArray)
{
KeyValuePair<char, char> Pair;
Pair = sourceTable.First(tuple => tuple.Key == chr);
encryptedData.Append(Pair.Value);
}
enCrypted = encryptedData.ToString();
}
catch (Exception ex)
{
}
return enCrypted;
}
public static string Decrypt(string source)
{
string deCrypted = "";
try
{
source = Reverse(source);
Dictionary<char, char> sourceTable = AddDictionaryItems();
char[] sourceArray = source.ToCharArray();
StringBuilder decryptedData = new StringBuilder();
foreach (char chr in sourceArray)
{
KeyValuePair<char, char> Pair;
Pair = sourceTable.First(tuple => tuple.Value == chr);
decryptedData.Append(Pair.Key);
}
deCrypted = decryptedData.ToString();
string prefixRemoved = deCrypted.Remove(0, 36);
string postfixRemoved = prefixRemoved.Remove(prefixRemoved.Length - 36);
string infixRemoved = postfixRemoved.Remove((postfixRemoved.Length - 36) / 2, 36);
deCrypted = infixRemoved;
}
catch (Exception ex)
{
}
return deCrypted;
}
public static Dictionary<char, char> AddDictionaryItems()
{
Dictionary<char, char> dc = new Dictionary<char, char>();
try
{
int initial = 33;
int jump = 10;
int final = 127 - jump;
for (int ascii = initial; ascii < final; ascii++)
{
dc.Add((char)ascii, (char)(ascii + jump));
}
for (int ascii = final; ascii < final + jump; ascii++)
{
dc.Add((char)ascii, (char)(initial));
initial++;
}
}
catch (Exception ex)
{
}
return dc;
}
protected void Page_Load(object sender, EventArgs e)
{
string password = "$Om3P#55w0r6";
string encrypted = Encrypt(password);
string decrypted = Decrypt(encrypted);
}
the encryption is not secure but its a start. i hope it helps someone writing his own method from the scratch.
Related
I am trying to "decode" this following Base64 string:
OBFZDTcPCxlCKhdXCQ0kMQhKPh9uIgYIAQxALBtZAwUeOzcdcUEeW0dMO1kbPElWCV1ISFFKZ0kdWFlLAURPZhEFQVseXVtPOUUICVhMAzcfZ14AVEdIVVgfAUIBWVpOUlAeaUVMXFlKIy9rGUN0VF08Oz1POxFfTCcVFw1LMQNbBQYWAQ==
This is what I know about the string itself:
The original string is first passed through the following code:
private static string m000493(string p0, string p1)
{
StringBuilder builder = new StringBuilder(p0);
StringBuilder builder2 = new StringBuilder(p1);
StringBuilder builder3 = new StringBuilder(p0.Length);
int num = 0;
Label_0084:
while (num < builder.Length)
{
int num2 = 0;
while (num2 < p1.Length)
{
if ((num == builder.Length) || (num2 == builder2.Length))
{
MessageBox.Show("EH?");
goto Label_0084;
}
char ch = builder[num];
char ch2 = builder2[num2];
ch = (char)(ch ^ ch2);
builder3.Append(ch);
num2++;
num++;
}
}
return m0001cd(builder3.ToString());
}
The p1 part in the code is supposed to be the string "_p0lizei.".
It is then converted to a Base64 string by the following code:
private static string m0001cd(string p0)
{
string str2;
try
{
byte[] buffer = new byte[p0.Length];
str2 = Convert.ToBase64String(Encoding.UTF8.GetBytes(p0));
}
catch (Exception exception)
{
throw new Exception("Error in base64Encode" + exception.Message);
}
return str2;
}
The question is, how do I decode the Base64 string so that I can find out what the original string is?
Simple:
byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);
The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encoding and decoding the text. All you have to do is reverse m0001cd:
string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));
string result = m000493(p0, "_p0lizei.");
// result == "gaia^unplugged^Ta..."
with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.
// Decode a Base64 string to a string
public static string DecodeBase64(string value)
{
if(string.IsNullOrEmpty(value))
return string.Empty;
var valueBytes = System.Convert.FromBase64String(value);
return System.Text.Encoding.UTF8.GetString(valueBytes);
}
I want to repeat the Encrypt function along the entire length of the bina / how to do it?
private void carbonFiberButton11_Click_1(object sender, EventArgs e)
{
textBox1.Text = PairConcat(Encrypt(), bina());
}
public static string PairConcat(string Encrypt, string bina)
{
StringBuilder result = new StringBuilder();
int i = 0;
for(; i<Encrypt.Length & i < bina.Length; i++)
{
result.Append(Encrypt[i].ToString());
result.Append(bina[i].ToString());
}
result.Append(Encrypt.Substring(i));
result.Append(bina.Substring(i));
return result.ToString();
}
For example:
string bina = "1234567";
string Encrypt = "abcdefg";
textbox1.text = 1a2b3c4d.. ;but it is doesn't works if I have different length:
string bina = "12345"
string Encrypt = "abc"
textbox1.text = 1a2b3c45 , but I need - 1a2b3c4a5b.
Encrypt function:
string Encrypt() //random to binary
{
var encrypt = textBox4.Text;
StringBuilder binary = new StringBuilder();
for (int i = 0; i < encrypt.Length; i++)
{
binary.Append(Convert.ToString(encrypt[i], 2).PadLeft(8, '0'));
}
return binary.ToString();
}
I can't understand what to do/ Help me, please
Just make the Encrypt string in minimum as long as the bina string.
// Calculate smallest multiple of Encrypt.Length at least as long as bina.Length
int lb = bina.Length;
int le = Encrypt.Length;
int bufferLength = (lb + le - 1) / le * le;
var sb = new StringBuilder(Encrypt, bufferLength);
while (sb.Length < lb) {
sb.Append(Encrypt);
}
Encrypt = sb.ToString();
string result = String.Join("", bina.Zip(Encrypt, (a, b) => a.ToString() + b));
The LINQ Zip method combines 2 sequences by providing pairs of items from the two sequences until one sequence ends. Here the sequences consist of chars.
The StringBuilder works most efficiently if does not have to resize its internal buffer. I calculate it by using integer arithmetic.
I'm writing a console app that will grab some data from a Chrome extension and email me a report. The data is stored as JSON in the localstorage file, which is a sqlite database. If I copy the hex and convert it online at http://string-functions.com/hex-string.aspx it converts to the JSON properly. But, no matter how I try to do it in C#, it looks like this:
Here's my main portion of code:
static void Main(string[] args)
{
var dbLocation = ConfigurationManager.AppSettings["dbLocation"];
using (var connection = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbLocation)))
{
connection.Open();
var response = connection.Query<string>("SELECT hex(value) FROM ItemTable WHERE key = 'state'").Single();
var json = ConvertHex(response);
//var response = JsonConvert.DeserializeObject<ChromeData>(json);
}
}
For the ConvertHex function here's everything I have tried, all of which have the same result. These are pulled from various other StackOverflow answers.
public static string ConvertHex(String hexString)
{
try
{
string ascii = string.Empty;
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = string.Empty;
hs = hexString.Substring(i, 2);
uint decval = System.Convert.ToUInt32(hs, 16);
char character = System.Convert.ToChar(decval);
ascii += character;
}
return ascii;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return string.Empty;
}
private static string HexString2Ascii(string hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= hexString.Length - 2; i += 2)
{
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
return sb.ToString();
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
static string HexStringToString(string hexString)
{
if (hexString == null || (hexString.Length & 1) == 1)
{
throw new ArgumentException();
}
var sb = new StringBuilder();
for (var i = 0; i < hexString.Length; i += 2)
{
var hexChar = hexString.Substring(i, 2);
sb.Append((char)Convert.ToByte(hexChar, 16));
}
return sb.ToString();
}
Any help is appreciated. Thanks!
Try below code.
Change the try block of ConvertHex as said below.
Look into comments for the details.
public static string ConvertHex(String hexString)
{
try
{
//DECLARE A VARIABLE TO RETURN
string ascii = string.Empty;
//SPLIT THE HEX STRING BASED ON SPACE (ONE SPACE BETWEEN TWO NUMBERS)
string[] hexSplit = hexString.Split(' ');
//LOOP THROUGH THE EACH HEX SPLIT
foreach (String hex in hexSplit)
{
// CONVERT THE NUMBER TO BASE 16
int value = Convert.ToInt32(hex, 16);
// GET THE RESPECTIVE CHARACTER
string stringValue = Char.ConvertFromUtf32(value);
char charValue = (char)value;
//APPEND THE STRING
ascii += charValue;
}
//RETURN THE STRING
return ascii;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return string.Empty;
}
I am working on a function that will evaluate a string and only allow x instances of each character.
For example, you can have 2 allowed character so
aaaabbbbbcddddd
would be evaluated to
aabbcdd
So far I have written this:
public static string removeDuplicateCharacters(String text, int allowedDuplicates)
{
string seen="";
foreach (char c in text){
if(!seen.Contains(c)){
seen = seen + c;
} else if(seen.Contains(c)){
// while the sting contains < allowedDuplicates
// add c
}
}
return seen;
}
I can't at the moment work out how create a while condition that is also going to count through my seen string for the number of current instances of the char currently being evaluated.
Easy solution with a Dictionary to keep track of the character counts:
public static string removeDuplicateCharacters(String text, int allowedDuplicates)
{
string seen="";
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in text)
{
if(!charCount.ContainsKey(c))
{
seen += c;
charCount.Add(c, 1);
}
else if(charCount[c] < allowedDuplicates)
{
charCount[c] += 1;
seen += c;
}
else
{
//Reached max, do nothing
}
}
return seen;
}
This is your base and you can make it as nice and fancy as you want from here.
E.g.: I would suggest a StringBuilder if the strings can get long as it less taxing on memory since you don't have to allocate permanently new Strings when doing += on them.
public static string removeDuplicateCharacters(String text, int allowedDuplicates)
{
StringBuilder seen = new StringBuilder();
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in text)
{
if(!charCount.ContainsKey(c))
{
seen.Append(c);
charCount.Add(c, 1);
}
else if(charCount[c] < allowedDuplicates)
{
charCount[c] += 1;
seen.Append(c);
}
else
{
//Reached max, do nothing
}
}
return seen.ToString();
}
Another thing would be if you want lower and uppercase to be treated the same.
Then I would change the test to upper or lower case, but if you want to keep the casing of the original character in the return string you could do the following.
public static string removeDuplicateCharacters(String text, int allowedDuplicates)
{
StringBuilder seen = new StringBuilder();
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in text)
{
char upperCase = c.ToUpper();
if(!charCount.ContainsKey(upperCase))
{
seen.Append(c);
charCount.Add(upperCase , 1);
}
else if(charCount[upperCase] < allowedDuplicates)
{
charCount[upperCase ] += 1;
seen.Append(c);
}
else
{
//Reached max, do nothing
}
}
return seen.ToString();
}
Just customize from here on.
Use a dictionary to keep track of character count
public static string removeDuplicateCharacters(string text, int allowedDuplicates)
{
var frequency = new Dictionary<char, int>();
StringBuilder output = new StringBuilder();
foreach (char c in text)
{
int count = 1;
if (frequency.ContainsKey(c))
count = ++frequency[c];
else
frequency.Add(c, count);
if (count <= allowedDuplicates)
output.Append(c);
}
return output.ToString();
}
Here we keep track of the seen characters and how many times we have seen them by using a Dictionary, and we assemble the output string with a StringBuilder:
public static string RemoveDuplicateCharacters(string text, int allowedDuplicates)
{
var seen = new Dictionary<char, int>();
var sb = new StringBuilder();
foreach (char c in text)
{
int count;
if (seen.TryGetValue(c, out count))
{
count++;
} else
{
count = 1;
}
seen[c] = count;
if (count <= allowedDuplicates)
sb.Append(c);
}
return sb.ToString();
}
Test:
Console.WriteLine(RemoveDuplicateCharacters("aaaabbbbbcddddda", 3));
Output:
aaabbbcddd
This is possibly a more appropriate approach for a beginner student. It doesn't require the use of arrays or dictionaries and sticks to simple algorithmic primitives. (I'm not objecting to their use, I just have a hunch that this is a student exercise and might even be one designed to motivate their introduction.)
public static string removeDuplicateCharacters(String text, int allowedDuplicates)
{
string seen= "";
int count = 0;
foreach (char c in text) {
count = 0;
foreach (char c2 in seen) {
if (c2 == c) count++;
}
if (count < allowedDuplicates) {
seen = seen + c;
}
}
return seen;
}
I'm trying to generate a 16 chars random string with NO DUPLICATE CHARS. I thoght that it shouldn't be to hard but I'm stuck.
I'm using 2 methods, one to generate key and another to remove duplicate chars. In main I've created a while loop to make sure that generated string is 16 chars long.
There is something wrong with my logic because it just shoots up 16-char string
with duplicates. Just can't get it right.
The code:
public string RemoveDuplicates(string s)
{
string newString = string.Empty;
List<char> found = new List<char>();
foreach (char c in s)
{
if (found.Contains(c))
continue;
newString += c.ToString();
found.Add(c);
}
return newString;
}
public static string GetUniqueKey(int maxSize)
{
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
data = new byte[maxSize];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(maxSize);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
string builder = "";
do
{
builder = GetUniqueKey(16);
RemoveDuplicates(builder);
lblDir.Text = builder;
Application.DoEvents();
} while (builder.Length != 16);
Consider implementing shuffle algorithm with which you will shuffle your string with unique characters and then just pick up first 16 characters.
You can do this in-place, by allocating single StringBuffer which will contain your initial data ("abc....") and just use Durstenfeld's version of the algorithm to mutate your buffer, than return first 16 chars.
There are many algorithms for this.
One easy one is:
Fill an array of chars with the available chars.
Shuffle the array.
Take the first N items (where N is the number of characters you need).
Sample code:
using System;
namespace ConsoleApplication2
{
internal class Program
{
private static void Main(string[] args)
{
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
Random rng = new Random();
for (int i = 0; i < 10; ++i)
{
string randomString = RandomString(16, chars, rng);
Console.WriteLine(randomString);
}
}
public static string RandomString(int n, char[] chars, Random rng)
{
Shuffle(chars, rng);
return new string(chars, 0, n);
}
public static void Shuffle(char[] array, Random rng)
{
for (int n = array.Length; n > 1; )
{
int k = rng.Next(n);
--n;
char temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
}
}
const string chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var r = new Random();
var s = new string(chars.OrderBy(x => r.Next()).Take(16).ToArray());
I am using a GUID generation method it itself generates random strings and you can modify it if a number appears in the beginning,
use the code given below:
string guid = System.Guid.NewGuid().ToString("N");
while (char.IsDigit(guid[0]))
guid = System.Guid.NewGuid().ToString("N");
Hope that helps.
See if this helps:
RandomString()
{
string randomStr = Guid.NewGuid().ToString();
randomStr = randomStr.Replace("-", "").Substring(0, 16);
Console.WriteLine(randomStr);
}
This returns alpha-numeric string.