I have an aes encryption code, i want to make it only return alphanumerical characters like {0123456789ABCDEFGHIJKLMNOPQRSTWUVYZ}
But however i could not figure out how to do that. I have almost no idea about encryption, could not figure out where to fix. I would really apreciate your feedback. Regards...
public class clsCrypto
{
private string _KEY = string.Empty;
protected internal string KEY
{
get
{
return _KEY;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_KEY = value;
}
}
}
private string _IV = string.Empty;
protected internal string IV
{
get
{
return _IV;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_IV = value;
}
}
}
private string CalcMD5(string strInput)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
StringBuilder strHex = new StringBuilder();
using (MD5 md5 = MD5.Create())
{
byte[] bytArText = Encoding.Default.GetBytes(strInput);
byte[] bytArHash = md5.ComputeHash(bytArText);
for (int i = 0; i < bytArHash.Length; i++)
{
strHex.Append(bytArHash[i].ToString("X2"));
}
strOutput = strHex.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
private byte[] GetBytesFromHexString(string strInput)
{
byte[] bytArOutput = new byte[] { };
if ((!string.IsNullOrEmpty(strInput)) && strInput.Length % 2 == 0)
{
SoapHexBinary hexBinary = null;
try
{
hexBinary = SoapHexBinary.Parse(strInput);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
bytArOutput = hexBinary.Value;
}
return bytArOutput;
}
private byte[] GenerateIV()
{
byte[] bytArOutput = new byte[] { };
try
{
string strIV = CalcMD5(IV);
bytArOutput = GetBytesFromHexString(strIV);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
private byte[] GenerateKey()
{
byte[] bytArOutput = new byte[] { };
try
{
string strKey = CalcMD5(KEY);
bytArOutput = GetBytesFromHexString(strKey);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
protected internal string Encrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] bytePlainText = Encoding.Default.GetBytes(strInput);
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateEncryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream())
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Write))
{
cpoStream.Write(bytePlainText, 0, bytePlainText.Length);
cpoStream.FlushFinalBlock();
}
strOutput = Encoding.Default.GetString(memStream.ToArray());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
protected internal string Decrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] byteCipherText = Encoding.Default.GetBytes(strInput);
byte[] byteBuffer = new byte[strInput.Length];
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateDecryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream(byteCipherText))
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Read))
{
cpoStream.Read(byteBuffer, 0, byteBuffer.Length);
}
strOutput = Encoding.Default.GetString(byteBuffer);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
}
Encryption and decryption functions use byte arrays as parameters.
So, you must convert these arrays to base 36 string.
You can use the following class (Base36) to make these conversions:
All you have to do, is calling these two functions:
byte[] byteArray;
//To convert byte array to String
string byteArrayInBase36 = Base36.ByteArrayToBase36String(byteArray);
//To convert String to byte Array
byte[] byteArray2 = Base36.Base36StringToByteArray(byteArrayInBase36);
and, this is the class:
using System;
using System.Collections.Generic;
class Base36
{
#region public methods
public static string ByteArrayToBase36String(byte[] bytes)
{
string result = string.Empty;
result = Encode36((ulong)bytes.Length).PadLeft(BASE36_LENGTH_BLOC_SIZE_36, '0');
if (bytes.Length > 0)
{
List<byte[]> byteslist = SplitBytes(bytes, 8);
if (byteslist[byteslist.Count - 1].Length < 8)
{
byte[] newLastArray = new byte[8];
byteslist[byteslist.Count - 1].CopyTo(newLastArray, 0);
byteslist[byteslist.Count - 1] = newLastArray;
}
foreach (byte[] byteArray in byteslist)
{
ulong value = 0;
//for (int i = 0; i < byteArray.Length; i++) value = value * 256 + byteArray[i];
value = BitConverter.ToUInt64(byteArray, 0);
result = result + Encode36(value).PadLeft(BASE36_BLOC_SIZE_36, '0');
}
}
return result;
}
public static byte[] Base36StringToByteArray(string input)
{
byte[] result = new byte[0];
if (input.Length >= BASE36_LENGTH_BLOC_SIZE_36)
{
int arrayLength = (int)Decode36(input.Substring(0, BASE36_LENGTH_BLOC_SIZE_36));
string data = input.Remove(0, BASE36_LENGTH_BLOC_SIZE_36);
List<byte[]> bytesList = new List<byte[]>();
foreach (string value36 in new List<string>(SplitStringByLength(data, BASE36_BLOC_SIZE_36)))
{
byte[] byteArray = BitConverter.GetBytes(Decode36(value36));
bytesList.Add(byteArray);
}
result = JoinBytes(bytesList);
Array.Resize(ref result, arrayLength);
}
return result;
}
#endregion
#region Const
private const int BASE36_LENGTH_BLOC_SIZE_36 = 6;
private const int BASE36_BLOC_SIZE_36 = 13; //Encode36(ulong.MaxValue).Length;
#endregion
#region private methods
static string _CharList36 = string.Empty;
static private string CharList36
{
get
{
if (_CharList36.Length < 36)
{
char[] array = new char[36];
for (int i = 0; i < 10; i++) array[i] = (char)(i + 48);
for (int i = 0; i < 26; i++) array[i + 10] = (char)(i + 97);
_CharList36 = new string(array);
}
return _CharList36;
}
}
private static List<string> SplitStringByLength(string str, int chunkSize)
{
List<string> list = new List<string>();
int i;
for (i = 0; i < str.Length / chunkSize; i++)
{
list.Add(str.Substring(i * chunkSize, chunkSize));
}
i = i * chunkSize;
if (i < str.Length - 1)
list.Add(str.Substring(i, str.Length - i));
return list;
}
private static String Encode36(ulong input)
{
if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
char[] clistarr = CharList36.ToCharArray();
var result = new Stack<char>();
while (input != 0)
{
result.Push(clistarr[input % 36]);
input /= 36;
}
return new string(result.ToArray()).ToUpper();
}
private static ulong Decode36(string input)
{
var reversed = ReverseString(input.ToLower());
ulong result = 0;
int pos = 0;
foreach (char c in reversed)
{
result += (ulong)CharList36.IndexOf(c) * (ulong)Math.Pow(36, pos);
pos++;
}
return result;
}
private static string ReverseString(string text)
{
char[] cArray = text.ToCharArray();
string reverse = String.Empty;
for (int i = 0; i < cArray.Length / 2; i++)
{
char c = cArray[i];
cArray[i] = cArray[cArray.Length - 1 - i];
cArray[cArray.Length - 1 - i] = c;
}
return new string(cArray);
}
private static byte[] StringToBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
private static List<byte[]> SplitBytes(byte[] bytes, int length)
{
List<byte[]> result = new List<byte[]>();
int position = 0;
while (bytes.Length - position > length)
{
byte[] temp = new byte[length];
for (int i = 0; i < temp.Length; i++) temp[i] = bytes[i + position];
position += length;
result.Add(temp);
}
if (position < bytes.Length)
{
byte[] temp = new byte[bytes.Length - position];
for (int i = 0; i + position < bytes.Length; i++) temp[i] = bytes[i + position];
result.Add(temp);
}
return result;
}
private static string BytesToString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
private static byte[] JoinBytes(List<byte[]> listBytes)
{
int totalLength = 0;
foreach (byte[] bytes in listBytes) totalLength += bytes.Length;
byte[] result = new byte[totalLength];
int position = 0;
foreach (byte[] bytes in listBytes)
for (int i = 0; i < bytes.Length; i++)
{
result[position] = bytes[i];
position++;
}
return result;
}
#endregion
}
You can encode the resulting bytes using Base36 or another such binary-to-text encoding.
Related
I have a socket.io client which sends data to each other where encryption is based on ARC4.
I tried multiple different scenarios but it keeps failing to decrypt anything and I'm not sure why.
The class: ARC4_New
public class ARC4_New
{
private int i;
private int j;
private byte[] bytes;
public const int POOLSIZE = 256;
public ARC4_New()
{
bytes = new byte[POOLSIZE];
}
public ARC4_New(byte[] key)
{
bytes = new byte[POOLSIZE];
this.Initialize(key);
}
public void Initialize(byte[] key)
{
this.i = 0;
this.j = 0;
for (i = 0; i < POOLSIZE; ++i)
{
this.bytes[i] = (byte)i;
}
for (i = 0; i < POOLSIZE; ++i)
{
j = (j + bytes[i] + key[i % key.Length]) & (POOLSIZE - 1);
this.Swap(i, j);
}
this.i = 0;
this.j = 0;
}
private void Swap(int a, int b)
{
byte t = this.bytes[a];
this.bytes[a] = this.bytes[b];
this.bytes[b] = t;
}
public byte Next()
{
this.i = ++this.i & (POOLSIZE - 1);
this.j = (this.j + this.bytes[i]) & (POOLSIZE - 1);
this.Swap(i, j);
return this.bytes[(this.bytes[i] + this.bytes[j]) & 255];
}
public void Encrypt(ref byte[] src)
{
for (int k = 0; k < src.Length; k++)
{
src[k] ^= this.Next();
}
}
public void Decrypt(ref byte[] src)
{
this.Encrypt(ref src);
}
}
public System.Numerics.BigInteger RandomInteger(int bitSize)
{
var integerData = new byte[bitSize / 8];
_numberGenerator.NextBytes(integerData);
integerData[integerData.Length - 1] &= 0x7f;
return new System.Numerics.BigInteger(integerData);
}
My script which generates a key:
System.Numerics.BigInteger DHPrivate = RandomInteger(256);
System.Numerics.BigInteger DHPrimal = RandomInteger(256);
System.Numerics.BigInteger DHGenerated = RandomInteger(256);
if (DHGenerated > DHPrimal)
{
System.Numerics.BigInteger tempG = DHGenerated;
DHGenerated= DHPrimal;
DHPrimal = tempG;
}
Then with those values I generate a public key:
System.Numerics.BigInteger DHPublic = System.Numerics.BigInteger.ModPow(DHGenerated, DHPrivate, DHPrimal);
Then I encrypt this key:
string pkey = EncryptY(CalculatePublic, DHPublic);
(Additional code for the encryption below)
protected virtual string EncryptY(Func<System.Numerics.BigInteger, System.Numerics.BigInteger> calculator, System.Numerics.BigInteger value)
{
byte[] valueData = Encoding.UTF8.GetBytes(value.ToString());
valueData = PKCSPad(valueData);
Array.Reverse(valueData);
var paddedInteger = new System.Numerics.BigInteger(valueData);
System.Numerics.BigInteger calculatedInteger = calculator(paddedInteger);
byte[] paddedData = calculatedInteger.ToByteArray();
Array.Reverse(paddedData);
string encryptedValue = Utils.Converter.BytesToHexString(paddedData).ToLower();
return encryptedValue.StartsWith("00") ? encryptedValue.Substring(2) : encryptedValue;
}
protected virtual byte[] PKCSPad(byte[] data)
{
var buffer = new byte[128 - 1];
int dataStartPos = (buffer.Length - data.Length);
buffer[0] = (byte)Padding;
Buffer.BlockCopy(data, 0, buffer, dataStartPos, data.Length);
int paddingEndPos = (dataStartPos - 1);
bool isRandom = (Padding == PKCSPadding.RandomByte);
for (int i = 1; i < paddingEndPos; i++)
{
buffer[i] = (byte)(isRandom ?
_numberGenerator.Next(1, 256) : byte.MaxValue);
}
return buffer;
}
After all that I sent the string PKEY to the server.
And after decrypting the string, the server gets the public key which is for example: 127458393
When I connect both my client and server using: 127458393
Like:
BigInteger key = System.Numerics.BigInteger.Parse("127458393");
client = new ARC4_New(PrimalDing.ToByteArray());
My client sends a string like:
client.Encrypt(BYTE_HERE);
And my server reads it like:
client.Decrypt(BYTE_HERE);
But it fails, and gets a random unreadable string.
What am I doing wrong here?
I managed to fix the issue
For some reason, my server was and is reversing the bytes i used in the ARC4 client..
So i simple reverse it now as a hotfix
System.Numerics.BigInteger temp = System.Numerics.BigInteger.Parse(textBox1.Text);
client = new ARC4_New(temp.ToByteArray().Reverse().ToArray());
I'm looking for a way to get random characters.I need a string must be contain at 2 least uppercase letters, at least 1 number and special characters.
Here is my code:
public static string CreateRandomPassword(int Length)
{
string _Chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ[_!23456790";
Byte[] randomBytes = new Byte[Length];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
var chars = new char[Length];
int Count = _Chars.Length;
for(int i = 0;i<Length;i++)
{
chars[i] = _Chars[(int)randomBytes[i] % Count];
}
return new string(chars);
}
some results:
ZNQzvUPFKOL3x
BQSEkKHXACGO
They haven't special characters and numbers.
your code works great! I've just wrapped it with a function that validate your conditions.
I've executed the following:
public static string CreateRandomPassword(int Length)
{
string _Chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ[_!23456790";
Byte[] randomBytes = new Byte[Length];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
var chars = new char[Length];
int Count = _Chars.Length;
for (int i = 0; i < Length; i++)
{
chars[i] = _Chars[(int)randomBytes[i] % Count];
}
return new string(chars);
}
public static string CreateRandomPasswordWith2UpperAnd1NumberAnd1Special(int length)
{
while (true)
{
var pass = CreateRandomPassword(length);
int upper=0, num =0, special = 0,lower=0;
foreach (var c in pass)
{
if (c > 'A' && c < 'Z')
{
upper++;
}
else if (c > 'a' && c < 'z')
{
lower++;
}
else if (c > '0' && c < '9')
{
num++;
}
else
{
special++;
}
}
if (upper>=2&&num>=1&&1>=special)
{
return pass;
}
}
}
[Test]
public void CreateRandomPassword_Length13_RandomPasswordWithNumbers()
{
var random = CreateRandomPasswordWith2UpperAnd1NumberAnd1Special(13);
Assert.IsTrue(true);
}
I'd like to convert this function:
function DoHashPassword($username, $clear_password)
{
return strtoupper(bin2hex(strrev(hex2bin(strtoupper(hash("sha256",strtoupper(hash("sha256", strtoupper($username)).":".strtoupper($clear_password))))))));
}
to C# language.
How can I do that?
At the moment I'm at this point:
Remaining (in PHP)
strtoupper(bin2hex(strrev(hex2bin($password))));
What I've done (in C#)
public static string DoShaHashPassword256(string _email, string _password)
{
byte[] emailbyte = Encoding.ASCII.GetBytes(_email.ToUpper());
var sha_email = SHA256.Create();
byte[] bytehashemail = sha_email.ComputeHash(emailbyte);
_email = HexStringFromBytes(bytehashemail);
//now with password
byte[] passbyte = Encoding.ASCII.GetBytes(_email.ToUpper() + ":" + _password.ToUpper());
var sha_pass = SHA256.Create();
byte[] bytehashpass = sha_pass.ComputeHash(passbyte);
_password = HexStringFromBytes(bytehashpass).ToUpper();
return /* hashed password */
}
private static string HexStringFromBytes(byte[] bytes)
{
var sb = new StringBuilder();
foreach (byte b in bytes)
{
var hex = b.ToString("x2");
sb.Append(hex);
}
return sb.ToString();
}
I don't know how to go on now.
This is the answer to the question. Thanks for your bad votes to my question (you should help, not give bad vote and no answer.).
public static string DoShaHashPassword256(string _email, string _password)
{
byte[] emailbyte = Encoding.ASCII.GetBytes(_email.ToUpper());
var sha_email = SHA256.Create();
byte[] bytehashemail = sha_email.ComputeHash(emailbyte);
_email = HexStringFromBytes(bytehashemail);
//now with password
byte[] passbyte = Encoding.ASCII.GetBytes(_email.ToUpper() + ":" + _password.ToUpper());
var sha_pass = SHA256.Create();
byte[] bytehashpass = sha_pass.ComputeHash(passbyte);
_password = HexStringFromBytes(bytehashpass).ToUpper();
//hex2bin
var bindata = hex2bin(_password);
//strrev
char[] chararray = bindata.ToCharArray();
Array.Reverse(chararray);
var reversedstring = new string(chararray);
//bin2hex
byte[] bytes = Encoding.GetEncoding(1252).GetBytes(reversedstring);
string hexString = HexStringFromBytes(bytes);
return hexString.ToUpper();
}
private static string HexStringFromBytes(byte[] bytes)
{
var sb = new StringBuilder();
foreach (byte b in bytes)
{
var hex = b.ToString("x2");
sb.Append(hex);
}
return sb.ToString();
}
private static string hex2bin(string hexdata)
{
if (hexdata == null)
throw new ArgumentNullException("hexdata");
if (hexdata.Length % 2 != 0)
throw new ArgumentException("hexdata should have even length");
byte[] bytes = new byte[hexdata.Length / 2];
for (int i = 0; i < hexdata.Length; i += 2)
bytes[i / 2] = (byte)(HexValue(hexdata[i]) * 0x10
+ HexValue(hexdata[i + 1]));
return Encoding.GetEncoding(1252).GetString(bytes);
}
private static int HexValue(char c)
{
int ch = (int)c;
if (ch >= (int)'0' && ch <= (int)'9')
return ch - (int)'0';
if (ch >= (int)'a' && ch <= (int)'f')
return ch - (int)'a' + 10;
if (ch >= (int)'A' && ch <= (int)'F')
return ch - (int)'A' + 10;
throw new ArgumentException("Not a hexadecimal digit.");
}
I wrote a code for custom encryption. It is a challenge. Right now it doesn't work for some reasons like:
Encrypt("abc", "hello everyone")
Returns: sdfhsjfjs
Decrypt("abc", "sdfhsjfjs")
Retruns: diuifidu
public int CountCharInStringAccordingToArray(string Text)
{
int Count = 0;
foreach (char x in Text)
{
Count++;
}
return Count - 1;
}
public int CountCharInString(string Text)
{
int Count = 0;
foreach (char x in Text)
{
Count++;
}
return Count;
}
public string Encrypt(string Key, string PlainText)
{
int[] TempKey = new int[CountCharInString(Key)];
int[] TempText = new int[CountCharInString(PlainText)];
int[] EncryptedInt = new int[CountCharInString(PlainText)];
char[] EncryptedChar = new char[CountCharInString(PlainText)];
for (int i = 0; i < CountCharInStringAccordingToArray(Key); i++)
{
TempKey[i] = (int)Key[i];
}
for (int i = 0; i < CountCharInStringAccordingToArray(PlainText); i++)
{
TempText[i] = (int)PlainText[i];
}
int Index = 0;
for (int i = 0; i < CountCharInStringAccordingToArray(PlainText); i++)
{
if (Index == CountCharInStringAccordingToArray(Key))
{
Index = 0;
}
EncryptedInt[i] = TempKey[Index] + TempText[i];
Index++;
EncryptedChar[i] = (char)EncryptedInt[i];
}
return new string(EncryptedChar);
}
public string Decrypt(string Key, string EncryptedText)
{
int[] TempKey = new int[CountCharInString(Key)];
int[] TempText = new int[CountCharInString(EncryptedText)];
int[] DecryptedInt = new int[CountCharInString(EncryptedText)];
char[] DecryptedChar = new char[CountCharInString(EncryptedText)];
for (int i = 0; i < CountCharInStringAccordingToArray(Key); i++)
{
TempKey[i] = (int)Key[i];
}
for (int i = 0; i < CountCharInStringAccordingToArray(EncryptedText); i++)
{
TempText[i] = (int)EncryptedText[i];
}
int Index = 0;
for (int i = 0; i < CountCharInStringAccordingToArray(EncryptedText); i++)
{
if (Index == CountCharInStringAccordingToArray(Key))
{
Index = 0;
}
DecryptedInt[i] = TempText[i] - TempKey[Index];
Index++;
DecryptedChar[i] = (char)DecryptedInt[i];
}
return new string(DecryptedChar);
}
Also I know that string have a length property it just I forget to correct it.
Change the line
return Count - 1;
in CountCharInStringAccordingToArray to
return Count;
A representation of your code:
String That(String key, String text, int sign) {
return new String(Enumerable.Range(0, text.Length).Select((x, i) => (char)(text.ToArray()[i]+sign*key.ToArray()[i%key.Length])).ToArray());
}
public String Encrypt(String key, String text) {
return That(key, text, 1);
}
public String Decrypt(String key, String text) {
return That(key, text, -1);
}
The principle of how it works is easy. Look at the graph:
The characters in the key are used repeatedly to add to the text and resulting a sequence that considered encrypted. The decryption is just a reverse operation by subtracting.
The maximum value can store in a byte is 0x0ff, but the maximum value of visible characters is 0x7e, that is ~, and 0x7e+0x7e=0xfc.
So as long as your key and text are in the range of visible characters, it will not cause overflowing. That is, you can decrypt the encrypted sequence to the original correctly.
Get string length and output string
using System;
class MainClass {
public static void Main() {
string str1 = "ABCDEabcde1234567890";
Console.WriteLine("str1: " + str1);
Console.WriteLine("Length of str1: " + str1.Length);
}
}
I need some help in converting a hex string into an image
doing some researches i came up to this code:
private byte[] HexString2Bytes(string hexString)
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x*2, 2),16);
}
return bytes;
}
public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
try
{
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);
_FileStream.Close();
return true;
}
catch (Exception _Exception)
{
MessageBox.Show(_Exception.Message);
}
return false;
}
The problem is that the resulting image is almost all black and i guess i need to apply some filters to better translate the gray-scale (since the original image is in gray-scale only)
Can anyone help me?
Many thanks
You don't need to apply any filters. I guess that the hexString variable that you are passing as input is simply a black image. The following works great for me:
class Program
{
static void Main()
{
byte[] image = File.ReadAllBytes(#"c:\work\someimage.png");
string hex = Bytes2HexString(image);
image = HexString2Bytes(hex);
File.WriteAllBytes("visio.png", image);
Process.Start("visio.png");
}
private static byte[] HexString2Bytes(string hexString)
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
private static string Bytes2HexString(byte[] buffer)
{
var hex = new StringBuilder(buffer.Length * 2);
foreach (byte b in buffer)
{
hex.AppendFormat("{0:x2}", b);
}
return hex.ToString();
}
}