Converting a String to a String of Binary - c#

My goal is to be able to convert a string into binary code that is still a string. I am able to turn the string into byte[] but not back to a string without decoding it.

You can use the Convert method for that:
byte [] bytesToEncode = Encoding.UTF8.GetBytes (inputText);
string encodedText = Convert.ToBase64String (bytesToEncode);

If you can encode/decode a byte, e.g.
private static String ToBinary(Byte value) {
StringBuilder Sb = new StringBuilder(8);
Sb.Length = 8;
for (int i = 0; i < 8; ++i) {
Sb[7 - i] = (Char) ('0' + value % 2);
value /= 2;
}
return Sb.ToString();
}
private static Byte FromBinary(String value) {
int result = 0;
for (int i = 0; i < value.Length; ++i)
result = result * 2 + value[i] - '0';
return (Byte) result;
}
You can easily encode/decode a whole string:
// Encoding...
String source = "abc";
// 011000010110001001100011
String result = String.Join("", UTF8Encoding.UTF8.GetBytes(source).Select(x => ToBinary(x)));
...
// Decoding...
List<Byte> codes = new List<Byte>();
for (int i = 0; i < result.Length; i += 8)
codes.Add(FromBinary(result.Substring(i, 8)));
// abc
String sourceBack = UTF8Encoding.UTF8.GetString(codes.ToArray());

use
string str = "Welcome";
byte []arr = System.Text.Encoding.ASCII.GetBytes(str);

Related

How to solve Check array index and length?

Error message: System.ArgumentException: 'Destination array is not long enough to copy all the items in the collection. Check array index and length.'
public static string PassConv(string Password)
{
int iLoop;
int iL;
int iTotal;
int iValue;
string sPassConv;
iL = 3;
iTotal = 0;
for (iLoop = 1; iLoop <= Password.Length; iLoop++) {
string sNo = Password.Substring(iLoop-1,1);
byte[] asciiBytes = Encoding.ASCII.GetBytes(sNo);
iValue = BitConverter.ToInt32(asciiBytes, 0); ---->**Error**
iTotal = iTotal + iValue * (iL + iLoop - 1);
sPassConv = iTotal.ToString();
}
return sPassConv;
}
Please Help
Thank
I try to reach your idea because of so many redundancy codes. By using:
SubString exports each character even Encoding.ASCII.GetBytes can return all byte array from these characters
BitConverter expected of 4-byte binary input as well
https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter.toint32 and seem this function is no help at all
Declare iLoop = 1 but inside loop does iLoop - 1
sPassConv gets value from iTotal so many times, should put outside the loop
Quick fix from your code:
public static string PassConv(string Password)
{
int iLoop;
int iL;
int iTotal;
int iValue;
string sPassConv = "";
iL = 3;
iTotal = 0;
for (iLoop = 1; iLoop <= Password.Length; iLoop++)
{
string sNo = Password.Substring(iLoop - 1, 1);
iValue = Encoding.ASCII.GetBytes(sNo)[0];
iTotal = iTotal + iValue * (iL + iLoop - 1);
sPassConv = iTotal.ToString();
}
return sPassConv;
}
A little bit refactor
public static string PassConv2(string Password, int iL = 3)
{
int iTotal = 0;
var bytes = Encoding.ASCII.GetBytes(Password);
for (var iLoop = 0; iLoop < bytes.Length; iLoop++)
{
// bytes[iLoop] = iValue
iTotal += bytes[iLoop] * (iL + iLoop);
}
return iTotal.ToString();
}
This function is need to be improved because it does loop 2 times, first to bytes and second to calculate. Since every character can convert to ASCII even Extended ASCII, so we could cast it directly. PassConv3 gives more exact when input is Unicode such as "Áaa", the Encoding.ASCII.GetByteswill cast as "?aa" with '?' represents 63 ASCII
public static string PassConv3(string Password, int iL = 3)
{
int iTotal = 0;
for (var iLoop = 0; iLoop < Password.Length; iLoop++)
{
iTotal += Password[iLoop] * (iL + iLoop);
}
return iTotal.ToString();
}
And the result
public static void MainFunc()
{
Console.WriteLine(PassConv("ABCD")); // 1202
Console.WriteLine(PassConv2("ABCD")); // 1202
Console.WriteLine(PassConv3("ABCD")); // 1202
}
Hope it helps !

Converting from a string to hex array

I have a problem when converting a char to hex value the code below works correctly when the char is a number but it's throw exception when the char is a latter
System.FormatException: 'Input string was not in a correct format
Code:
public byte[,] get_state(string plainText)
{
char[] cplainText = plainText.ToCharArray();
byte[,] state = new byte[4, 4];
plainText = plainText.Remove(0, 2);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j+=2)
{
string sub = plainText.Substring((i * 4 + j), 2);
state[i, j] = Convert.ToByte(sub);
}
}
return state;
}
The input string was "0x3243F6A8885A308D313198A2e0370734" and the exception across when the iteration of "F6"
Convert.ToByte();
It says in the overload that it only accepts numbers in string format.
You have to think about if you use the right method, or convert it beforehand.

XOR decryption in c#

I'm trying to decrypt xor string with key in c# but decrypting is wrong and i'm getting wrong value.
string text = "xorhash";
string key = "xorkey";
var result = new StringBuilder();
for (int c = 0; c < text.Length; c++)
result.Append((char)((uint)text[c] ^ (uint)key[c % key.Length]));
return result.ToString();
I've get it from this python code, which working good.
def xor(message, key):
return "".join(chr(ord(message[i]) ^ ord(key[i % len(key)])) for i in xrange(len(message)))
key = "my_xor_key"
message = "my_xor_hash".decode("hex")
print xor(message, key)
as soon as your input string is actually hex representation of codes, c# code should look like this:
for (int c = 0; c < text.Length; c+=2)
result.Append((char)(Convert.ToUInt16(text.Substring(c, 2), 16) ^ (ushort)key[ (c/2) % key.Length]));
private static string xor(string text, string key) {
var result = new StringBuilder();
for (int c = 0; c < text.Length; c++)
result.Append((char)((uint)text[c] ^ (uint)key[c % key.Length]));
return result.ToString();
}
string text = "my_xor_hash";
string key = "my_xor_key";
string encrypt = xor(text, key);
string decrypt = xor(encrypt, key);
System.Console.Write("Encrypt " + encrypt);
System.Console.Write("Decrypt " + decrypt);
Prints:
Encrypt
Decrypt my_xor_hash
And I didn't change a single line, only indentation.
Edit:
private static string xor(string text, string key) {
var result = new StringBuilder();
for (int c = 0; c < text.Length; c++)
result.Append((char)((uint)text[c] ^ (uint)key[c % key.Length]));
return result.ToString();
}
private static string FromHex(string hex) {
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 Encoding.ASCII.GetString(raw);
}
public static void Main() {
string text = FromHex("xor_hash");
string key = "xor_key";
string decrypt = xor(text, key);
System.Console.Write("Decrypt " + decrypt);
}
Prints:
Decrypt HARPERS
public static byte[] EncryptOrDecrypt(byte[] text, byte[] key)
{
byte[] xor = new byte[text.Length];
for (int i = 0; i < text.Length; i++)
{
xor[i] = (byte)(text[i] ^ key[i % key.Length]);
}
return xor;
}
static void Main(string[] args){
string input;
byte[] inputBytes;
string inputKey;
byte[] key;
do
{
input = System.Console.ReadLine();
inputBytes = Encoding.Unicode.GetBytes(input);
inputKey = System.Console.ReadLine();
key = Encoding.Unicode.GetBytes(inputKey);
//byte[] key = { 0, 0 }; if key is 0, encryption will not happen
byte[] encryptedBytes = EncryptOrDecrypt(inputBytes, key);
string encryptedStr = Encoding.Unicode.GetString(encryptedBytes);
byte[] decryptedBytes = EncryptOrDecrypt(encryptedBytes, key);
string decryptedStr = Encoding.Unicode.GetString(decryptedBytes);
System.Console.WriteLine("Encrypted string:");
System.Console.WriteLine(encryptedStr);
System.Console.WriteLine("Decrypted string:");
System.Console.WriteLine(decryptedStr);
} while (input != "-1" && inputKey != "-1");
//test:
//pavle
//23
//Encrypted string:
//BRD_W
//Decrypted string:
//pavle
}

Removing Leading Zeros in a Char Array

I'm attempting to subtract two strings (of theoretically infinite length) without the use of libraries like BigIntbut I was wondering if anybody has any good ideas on how to remove the leading zeros in the corner cases like the one below?
static void Main(string[] args)
{
Console.WriteLine(Subtract("10", "10005"));
}
static string ReverseInput(string inputString)
{
char[] charArray = inputString.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static string Subtract(string firstNumInput, string secondNumInput)
{
string firstNum = String.Empty;
string secondNum = String.Empty;
bool negative = false;
// Reverse order of string input
if (firstNumInput.Length > secondNumInput.Length)
{
firstNum = ReverseInput(firstNumInput);
secondNum = ReverseInput(secondNumInput);
}
else if (firstNumInput.Length < secondNumInput.Length)
{
negative = true;
firstNum = ReverseInput(secondNumInput);
secondNum = ReverseInput(firstNumInput);
}
else if (firstNumInput.Length == secondNumInput.Length)
{
// iterate through string to find largest
}
char[] result = new char[firstNum.Length + 1];
int resultLength = 0;
int carry = 0;
for (int i = 0; i < firstNum.Length; i++)
{
int an = (i < firstNum.Length) ? int.Parse(firstNum[i].ToString()) : 0;
int bn = (i < secondNum.Length) ? int.Parse(secondNum[i].ToString()) : 0;
int rn = an - bn - carry;
if (rn < 0)
{
carry = 1;
rn += 10;
}
else
{
carry = 0;
}
result[resultLength++] = (char)(rn + '0');
}
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength));
if (negative)
{
finalResult = '-' + finalResult;
}
return finalResult;
}
Are you looking for TrimStart?
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength)).TrimStart('0');

Help me with XOR encryption

I wrote this code in C# to encrypt a string with a key:
private static int Bin2Dec(string num)
{
int _num = 0;
for (int i = 0; i < num.Length; i++)
_num += (int)Math.Pow(2, num.Length - i - 1) * int.Parse(num[i].ToString());
return _num;
}
private static string Dec2Bin(int num)
{
if (num < 2) return num.ToString();
return Dec2Bin(num / 2) + (num % 2).ToString();
}
public static string StrXor(string str, string key)
{
string _str = "";
string _key = "";
string _xorStr = "";
string _temp = "";
for (int i = 0; i < str.Length; i++)
{
_temp = Dec2Bin(str[i]);
for (int j = 0; j < 8 - _temp.Length + 1; j++)
_temp = '0' + _temp;
_str += _temp;
}
for (int i = 0; i < key.Length; i++)
{
_temp = Dec2Bin(key[i]);
for (int j = 0; j < 8 - _temp.Length + 1; j++)
_temp = '0' + _temp;
_key += _temp;
}
while (_key.Length < _str.Length) _key += _key;
if (_key.Length > _str.Length) _key = _key.Substring(0, _str.Length);
for (int i = 0; i < _str.Length; i++)
if (_str[i] == _key[i]) { _xorStr += '0'; } else { _xorStr += '1'; }
_str = "";
for (int i = 0; i < _xorStr.Length; i += 8)
{
char _chr = (char)0;
_chr = (char)Bin2Dec(_xorStr.Substring(i, 8)); //ERROR : (Index and length must refer to a location within the string. Parameter name: length)
_str += _chr;
}
return _str;
}
The problem is that I always get error when I want to decrypt an encryted text with this code:
string enc_text = ENCRYPT.XORENC("abc","a"); // enc_text = " ♥☻"
string dec_text = ENCRYPT.XORENC(enc_text,"a"); // ArgumentOutOfRangeException
Any clues?
If you have a character, a char, you can convert it to an integer, an int.
And then you can use the ^ operator to perform XOR on it. You don't appear to be using that operator at the moment, which might be the source of your problem.
string EncryptOrDecrypt(string text, string key)
{
var result = new StringBuilder();
for (int c = 0; c < text.Length; c++)
result.Append((char)((uint)text[c] ^ (uint)key[c % key.Length]));
return result.ToString();
}
That kind of thing. Here's a longer version with comments that does the same thing in steps, to make it easier to learn from:
string EncryptOrDecrypt(string text, string key)
{
var result = new StringBuilder();
for (int c = 0; c < text.Length; c++)
{
// take next character from string
char character = text[c];
// cast to a uint
uint charCode = (uint)character;
// figure out which character to take from the key
int keyPosition = c % key.Length; // use modulo to "wrap round"
// take the key character
char keyChar = key[keyPosition];
// cast it to a uint also
uint keyCode = (uint)keyChar;
// perform XOR on the two character codes
uint combinedCode = charCode ^ keyCode;
// cast back to a char
char combinedChar = (char)combinedCode;
// add to the result
result.Append(combineChar);
}
return result.ToString();
}
The short version is the same but with the intermediate variables removed, substituting expressions directly into where they're used.
// Code
public static byte[] EncryptOrDecrypt(byte[] text, byte[] key)
{
byte[] xor = new byte[text.Length];
for (int i = 0; i < text.Length; i++)
{
xor[i] = (byte)(text[i] ^ key[i % key.Length]);
}
return xor;
}
// Test
static void Main(string[] args){
string input;
byte[] inputBytes;
string inputKey;
byte[] key;
do
{
input = System.Console.ReadLine();
inputBytes = Encoding.Unicode.GetBytes(input);
inputKey = System.Console.ReadLine();
key = Encoding.Unicode.GetBytes(inputKey);
//byte[] key = { 0, 0 }; if key is 0, encryption will not happen
byte[] encryptedBytes = EncryptOrDecrypt(inputBytes, key);
string encryptedStr = Encoding.Unicode.GetString(encryptedBytes);
byte[] decryptedBytes = EncryptOrDecrypt(encryptedBytes, key);
string decryptedStr = Encoding.Unicode.GetString(decryptedBytes);
System.Console.WriteLine("Encrypted string:");
System.Console.WriteLine(encryptedStr);
System.Console.WriteLine("Decrypted string:");
System.Console.WriteLine(decryptedStr);
} while (input != "-1" && inputKey != "-1");
//test:
//pavle
//23
//Encrypted string:
//BRD_W
//Decrypted string:
//pavle
}
Here is some simple code to encrypt and decrypt
class CEncryption
{
public static string Encrypt(string strIn, string strKey)
{
string sbOut = String.Empty;
for (int i = 0; i < strIn.Length; i++)
{
sbOut += String.Format("{0:00}", strIn[i] ^ strKey[i % strKey.Length]);
}
return sbOut;
}
public static string Decrypt(string strIn, string strKey)
{
string sbOut = String.Empty;
for (int i = 0; i < strIn.Length; i += 2)
{
byte code = Convert.ToByte(strIn.Substring(i, 2));
sbOut += (char)(code ^ strKey[(i/2) % strKey.Length]);
}
return sbOut;
}
}

Categories