First of all, sorry for the long post, I want to include all my thoughts so it's easier for you guys to find what's wrong about my code.
I want to transfer an Hex string from a C# application to a Java application. But, when I convert the same Hex value to a Byte Array on both languages, the output is different.
For instance, the same Hex value gives
[101, 247, 11, 173, 46, 74, 56, 137, 185, 38, 40, 191, 204, 104, 83, 154]
in C# and
[101, -9, 11, -83, 46, 74, 56, -119, -71, 38, 40, -65, -52, 104, 83, -102]
in Java
Here are the methods I use in C#:
public static string ByteArrayToHexString(byte[] byteArray)
{
return BitConverter.ToString(byteArray).Replace("-",""); //To convert the whole array
}
public static byte[] HexStringToByteArray(string hexString)
{
byte[] HexAsBytes = new byte[hexString.Length / 2];
for (int index = 0; index < HexAsBytes.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return HexAsBytes;
}
And the ones in Java:
public static String ByteArrayToHexString(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte b: bytes) {
builder.append(String.format("%02x", b));
}
return builder.toString().toUpperCase();
}
public static byte[] HexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
Here's an example in C#:
String hexString = "65F70BAD2E4A3889B92628BFCC68539A";
byte[] byteArray = HexBytes.HexStringToByteArray(hexString);
//Using the debugger, byteArray = [101, 247, 11, 173, 46, 74, 56, 137, 185, 38, 40, 191, 204, 104, 83, 154]
String hexString2 = HexBytes.ByteArrayToHexString(byteArray)
Console.Write("HEX: " + hexString2);
//Outputs 65F70BAD2E4A3889B92628BFCC68539A
And an example in Java:
String hexString = "65F70BAD2E4A3889B92628BFCC68539A";
byte[] byteArray = HexBytes.HexStringToByteArray(hexString);
//Using the debugger, byteArray = [101, -9, 11, -83, 46, 74, 56, -119, -71, 38, 40, -65, -52, 104, 83, -102]
String hexString2 = HexBytes.ByteArrayToHexString(byteArray);
System.out.println("HEX: " + hexString2);
//Outputs 65F70BAD2E4A3889B92628BFCC68539A
As you can see, when I do the opposite operation, the final Hex value is equal to the first one, which means the way I convert is potentially good in both languages individually. But I don't understand why the conversion from Hex to a byte array is different in both languages. I thought Hexadecimal was simply a number on another base.
Thanks for the help
Cydrick
Update
I fixed this issue by replacing the C# code with the following code:
public static string ByteArrayToHexString(sbyte[] byteArray)
{
return BitConverter.ToString(convert(byteArray)).Replace("-", ""); //To convert the whole array
}
public static sbyte[] HexStringToByteArray(string hexString)
{
byte[] HexAsBytes = new byte[hexString.Length / 2];
for (int index = 0; index < HexAsBytes.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return convert(HexAsBytes);
}
private static sbyte[] convert(byte[] byteArray)
{
sbyte[] sbyteArray = new sbyte[byteArray.Length];
for (int i = 0; i < sbyteArray.Length; i++)
{
sbyteArray[i] = unchecked((sbyte) byteArray[i]);
}
return sbyteArray;
}
private static byte[] convert(sbyte[] sbyteArray)
{
byte[] byteArray = new byte[sbyteArray.Length];
for (int i = 0; i < byteArray.Length; i++)
{
byteArray[i] = (byte) sbyteArray[i];
}
return byteArray;
}
But, when I convert the same Hex value to a Byte Array on both languages, the output is different.
All you're seeing is that bytes are signed in Java and unsigned in C#. So if you add 256 to any negative value in Java, you'll get the value shown in C#. The actual bits in the values are the same - it's just a matter of whether the top bit is treated as a sign bit or not.
EDIT: As noted in comments, if you're ever using the byte as an integer outside the debugger output, you can always use:
int someInt = someByte & 0xff;
to get the unsigned value.
Looks like this is a debugger issue only. Those negative values you're seeing in the Java debugger are the signed equivalents to the unsigned values you're seeing in the C# debugger. For example, signed byte -9 == unsigned byte 247 (notice that they always differ by 256). The data is fine.
Related
I know there are many questions related to it but still they are not solving my problem. Below is my byte array:
As you can see that the byte is of 28 and each 4-byte value represents a single value i.e. I have a client machine which sent me 2.4 and while reading it, it is then converted into bytes.
//serial port settings and opening it
var serialPort = new SerialPort("COM2", 9600, Parity.Even, 8, StopBits.One);
serialPort.Open();
var stream = new SerialStream(serialPort);
stream.ReadTimeout = 2000;
// send request and waiting for response
// the request needs: slaveId, dataAddress, registerCount
var responseBytes = stream.RequestFunc3(slaveId, dataAddress, registerCount);
// extract the content part (the most important in the response)
var data = responseBytes.ToResponseFunc3().Data;
What I want to do?
Convert each 4 byte one by one to hex, save them In a separate variable. Like
hex 1 = byte[0], hex2 = byte[1], hex3 = byte[2], hex4 = byte[3]
..... hex28 = byte[27]
Combine 4-byte hex value and then convert them into float and assign them a variable to hold floating value. Like
v1 = Tofloat(hex1,hex2,hex3,hex4); // assuming ToFloat() is a function.
How can I achieve it?
Since you mentioned that the first value is 2.4 and each float is represented by 4 bytes;
byte[] data = { 64, 25, 153, 154, 66, 157, 20, 123, 66, 221, 174, 20, 65, 204, 0, 0, 65, 163, 51, 51, 66, 95, 51, 51, 69, 10, 232, 0 };
We can group the bytes into 4 byte blocks and reverse them and convert each part to float like:
int offset = 0;
float[] dataFloats =
data.GroupBy(x => offset++ / 4) // group by 4. 0/4 = 0, 1/4 = 0, 2/4 = 0, 3/4 = 0 and 4/4 = 1 etc.
// Need to reverse the bytes to make them evaluate to 2.4
.Select(x => BitConverter.ToSingle(x.ToArray().Reverse().ToArray(), 0))
.ToArray();
Now you have an array of 7 floats:
I'm trying to use Rfc2898DeriveBytes for Android Java and .NET C# framework to generate key for encryption and decryption process.
The problem is in spite of that the input values are same, I'm getting different keys in .NET and Java.
.NET code:
private void btnRfc2898DeriveBytes_Click(object sender, EventArgs e)
{
byte[] salt = new byte[] { 19, 3, 24, 18, 14, 42, 57, 23 };
Rfc2898DeriveBytes keyGenerator = null;
keyGenerator = new Rfc2898DeriveBytes("somestring", salt, 1000);
txtRfc2898DeriveBytes.Text = System.Text.Encoding.UTF8.GetString(keyGenerator.GetBytes(16));
}
Java Code (used in an android application):
byte[] salt = new byte[] { 19, 3, 24, 18, 14, 42, 57, 23 };
Rfc2898DeriveBytes keyGenerator = null;
try {
keyGenerator = new Rfc2898DeriveBytes("somestring", salt, 1000);
} catch (InvalidKeyException e1) {
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("key = ", decodeUTF8(keyGenerator.getBytes(16)));
Java Decode Method:
String decodeUTF8(byte[] bytes) {
private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
return new String(bytes, UTF8_CHARSET);
}
Rfc2898DeriveBytes java class:
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* RFC 2898 password derivation compatible with .NET Rfc2898DeriveBytes class.
*/
public class Rfc2898DeriveBytes {
private Mac _hmacSha1;
private byte[] _salt;
private int _iterationCount;
private byte[] _buffer = new byte[20];
private int _bufferStartIndex = 0;
private int _bufferEndIndex = 0;
private int _block = 1;
/**
* Creates new instance.
* #param password The password used to derive the key.
* #param salt The key salt used to derive the key.
* #param iterations The number of iterations for the operation.
* #throws NoSuchAlgorithmException HmacSHA1 algorithm cannot be found.
* #throws InvalidKeyException Salt must be 8 bytes or more. -or- Password cannot be null.
*/
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) throws NoSuchAlgorithmException, InvalidKeyException {
if ((salt == null) || (salt.length < 8)) { throw new InvalidKeyException("Salt must be 8 bytes or more."); }
if (password == null) { throw new InvalidKeyException("Password cannot be null."); }
this._salt = salt;
this._iterationCount = iterations;
this._hmacSha1 = Mac.getInstance("HmacSHA1");
this._hmacSha1.init(new SecretKeySpec(password, "HmacSHA1"));
}
/**
* Creates new instance.
* #param password The password used to derive the key.
* #param salt The key salt used to derive the key.
* #param iterations The number of iterations for the operation.
* #throws NoSuchAlgorithmException HmacSHA1 algorithm cannot be found.
* #throws InvalidKeyException Salt must be 8 bytes or more. -or- Password cannot be null.
* #throws UnsupportedEncodingException UTF-8 encoding is not supported.
*/
public Rfc2898DeriveBytes(String password, byte[] salt, int iterations) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
this(password.getBytes("UTF8"), salt, iterations);
}
/**
* Creates new instance.
* #param password The password used to derive the key.
* #param salt The key salt used to derive the key.
* #throws NoSuchAlgorithmException HmacSHA1 algorithm cannot be found.
* #throws InvalidKeyException Salt must be 8 bytes or more. -or- Password cannot be null.
* #throws UnsupportedEncodingException UTF-8 encoding is not supported.
*/
public Rfc2898DeriveBytes(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
this(password, salt, 0x3e8);
}
/**
* Returns a pseudo-random key from a password, salt and iteration count.
* #param count Number of bytes to return.
* #return Byte array.
*/
public byte[] getBytes(int count) {
byte[] result = new byte[count];
int resultOffset = 0;
int bufferCount = this._bufferEndIndex - this._bufferStartIndex;
if (bufferCount > 0) { //if there is some data in buffer
if (count < bufferCount) { //if there is enough data in buffer
System.arraycopy(this._buffer, this._bufferStartIndex, result, 0, count);
this._bufferStartIndex += count;
return result;
}
System.arraycopy(this._buffer, this._bufferStartIndex, result, 0, bufferCount);
this._bufferStartIndex = this._bufferEndIndex = 0;
resultOffset += bufferCount;
}
while (resultOffset < count) {
int needCount = count - resultOffset;
this._buffer = this.func();
if (needCount > 20) { //we one (or more) additional passes
System.arraycopy(this._buffer, 0, result, resultOffset, 20);
resultOffset += 20;
} else {
System.arraycopy(this._buffer, 0, result, resultOffset, needCount);
this._bufferStartIndex = needCount;
this._bufferEndIndex = 20;
return result;
}
}
return result;
}
private byte[] func() {
this._hmacSha1.update(this._salt, 0, this._salt.length);
byte[] tempHash = this._hmacSha1.doFinal(getBytesFromInt(this._block));
this._hmacSha1.reset();
byte[] finalHash = tempHash;
for (int i = 2; i <= this._iterationCount; i++) {
tempHash = this._hmacSha1.doFinal(tempHash);
for (int j = 0; j < 20; j++) {
finalHash[j] = (byte)(finalHash[j] ^ tempHash[j]);
}
}
if (this._block == 2147483647) {
this._block = -2147483648;
} else {
this._block += 1;
}
return finalHash;
}
private static byte[] getBytesFromInt(int i) {
return new byte[] { (byte)(i >>> 24), (byte)(i >>> 16), (byte)(i >>> 8), (byte)i };
}
}
Edit:
I also convert it to Hex, but getting different values also.
C# function:
public static String encode(byte[] data)
{
char[] lookup = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int i = 0, p = 2, l = data.Length;
char[] c = new char[l * 2 + 2];
byte d; c[0] = '0'; c[1] = 'x';
while (i < l)
{
d = data[i++];
c[p++] = lookup[d / 0x10];
c[p++] = lookup[d % 0x10];
}
return new string(c, 0, c.Length);
}
Java method:
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
What I'm doing wrong :( ?
Here:
txtRfc2898DeriveBytes.Text = System.Text.Encoding.UTF8.GetString(
keyGenerator.GetBytes(16));
and here:
decodeUTF8(keyGenerator.getBytes(16)
you are using UTF-8 to decode data into a string that isn't UTF-8. Since that does not have a defined output, it is not unreasonable that the two undefined outputs can be different.
Rather than decoding as UTF-8: if you need it as a string, use base-16 (aka "hex") or base-64 to represent the generated bytes. A text encoding (such as UTF-8) is only well-defined when converting string data (in the range of characters supported by that encoding) to/from binary data in that encoding. It is incorrect to "decode" arbitrary binary via a text encoding.
I re-solved the issue, the following code generate same values for me in .NET and Java.
.NET code:
private void btnKey_Click(object sender, EventArgs e)
{
byte[] salt = new byte[] { 172, 137, 25, 56, 156, 100, 136, 211, 84, 67, 96, 10, 24, 111, 112, 137, 3 };
int iterations = 1024;
var rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes("_sOme*ShaREd*SecreT", salt, iterations);
byte[] key = rfc2898.GetBytes(16);
String keyB64 = Convert.ToBase64String(key);
txtRfc2898DeriveBytes.Text = keyB64;
}
Java code:
String password = "_sOme*ShaREd*SecreT";
byte[] salta = new byte[]{-84, -119, 25, 56, -100, 100, -120, -45, 84, 67, 96, 10, 24, 111, 112, -119, 3};
SecretKeyFactory factory = null;
try {
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
} catch (NoSuchAlgorithmException e2) {
e2.printStackTrace();
}
KeySpec spec = new PBEKeySpec(password.toCharArray(), salta, 1024, 128);
SecretKey tmp = null;
try {
tmp = factory.generateSecret(spec);
} catch (InvalidKeySpecException e2) {
e2.printStackTrace();
}
SecretKeySpec secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Log.i("The secret Key: " , Base64.encodeToString(secret.getEncoded(), 0 ));
public void parse_table(BinaryReader inFile)
{
byte[] idstring = inFile.ReadBytes(6);
Console.WriteLine(Convert.ToString(idstring));
}
It is a simple snippet: read the first 6 bytes of the file and convert that to a string.
However the console shows System.Byte[].
Maybe I'm using the wrong class for conversion. What should I be using? It will eventually be parsing filenames encoded in UTF-8, and I'm planning to use the same method to read all filenames.
It's actually:
Console.WriteLine(Encoding.Default.GetString(value));
or for UTF-8 specifically:
Console.WriteLine(Encoding.UTF8.GetString(value));
I was in a predicament where I had a signed byte array (sbyte[]) as input to a Test class and I wanted to replace it with a normal byte array (byte[]) for simplicity. I arrived here from a Google search but Tom's answer wasn't useful to me.
I wrote a helper method to print out the initializer of a given byte[]:
public void PrintByteArray(byte[] bytes)
{
var sb = new StringBuilder("new byte[] { ");
foreach (var b in bytes)
{
sb.Append(b + ", ");
}
sb.Append("}");
Console.WriteLine(sb.ToString());
}
You can use it like this:
var signedBytes = new sbyte[] { 1, 2, 3, -1, -2, -3, 127, -128, 0, };
var unsignedBytes = UnsignedBytesFromSignedBytes(signedBytes);
PrintByteArray(unsignedBytes);
// output:
// new byte[] { 1, 2, 3, 255, 254, 253, 127, 128, 0, }
The ouput is valid C# which can then just be copied into your code.
And just for completeness, here is the UnsignedBytesFromSignedBytes method:
// http://stackoverflow.com/a/829994/346561
public static byte[] UnsignedBytesFromSignedBytes(sbyte[] signed)
{
var unsigned = new byte[signed.Length];
Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
return unsigned;
}
I've used this simple code in my codebase:
static public string ToReadableByteArray(byte[] bytes)
{
return string.Join(", ", bytes);
}
To use:
Console.WriteLine(ToReadableByteArray(bytes));
byte[] bytes = { 1,2,3,4 };
string stringByte= BitConverter.ToString(bytes);
Console.WriteLine(stringByte);
This is just an updated version of Jesse Webbs code that doesn't append the unnecessary trailing , character.
public static string PrintBytes(this byte[] byteArray)
{
var sb = new StringBuilder("new byte[] { ");
for(var i = 0; i < byteArray.Length;i++)
{
var b = byteArray[i];
sb.Append(b);
if (i < byteArray.Length -1)
{
sb.Append(", ");
}
}
sb.Append(" }");
return sb.ToString();
}
The output from this method would be:
new byte[] { 48, ... 135, 31, 178, 7, 157 }
For some fun with linq and string interpolation:
public string ByteArrayToString(byte[] bytes)
{
if ( bytes == null ) return "null";
string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
return $"new byte[] {{ {joinedBytes} }}";
}
Test cases:
byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();
Output:
new byte[] { 1, 2, 3, 4 }
null
new byte[] { }
I'm looking to convert ADPCM data into PCM data from an XNA's .xnb file. (So many abbreviations!)
I've used a couple of places for references, including:
http://www.wooji-juice.com/blog/iphone-openal-ima4-adpcm.html
http://www.cs.columbia.edu/~hgs/audio/dvi/p34.jpg and a couple of others.
I believe that I'm close, as I'm getting a sound that's somewhat similar, but there's a lot of static/corruption in the output sound and I can't seem to figure out why.
The conversion comes down to two functions.
private static byte[] convert(byte[] data)
{
byte[] convertedData = new byte[(data.Length) * 4];
stepSize = 7;
newSample = 0;
index = 0;
var writeCounter = 0;
for (var x = 4; x < data.Length; x++)
{
// First 4 bytes of a block contain initialization information
if ((x % blockSize) < 4)
{
if (x % blockSize == 0) // New block
{
// set predictor/NewSample and index from
// the preamble of the block.
newSample = (short)(data[x + 1] | data[x]);
index = data[x + 2];
}
continue;
}
// Get the first 4 bits from the byte array,
var convertedSample = calculateNewSample((byte)(data[x] >> 4)); // convert 4 bit ADPCM sample to 16 bit PCM sample
// Store 16 bit PCM sample into output byte array
convertedData[writeCounter++] = (byte)convertedSample >> 8;
convertedData[writeCounter++] = (byte)convertedSample & 0x0ff;;
// Convert the next 4 bits of the 8 bit array.
convertedSample = calculateNewSample((byte)(data[x] & 0x0f)); // convert 4 bit ADPCM sample to 16 bit PCM sample.
// Store 16 bit PCM sample into output byte array
convertedData[writeCounter++] = (byte)(convertedSample >> 8);
convertedData[writeCounter++] = (byte)(convertedSample & 0x0ff);
}
// Conversion complete, return data
return convertedData;
}
private static short calculateNewSample(byte sample)
{
Debug.Assert(sample < 16, "Bad sample!");
var indexTable = new int[16] { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 };
var stepSizeTable = new int[89] { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767};
var sign = sample & 8;
var delta = sample & 7;
var difference = stepSize >> 3;
// originalsample + 0.5 * stepSize / 4 + stepSize / 8 optimization.
//http://www.cs.columbia.edu/~hgs/audio/dvi/p34.jpg
if ((delta & 4) != 0)
difference += stepSize;
if ((delta & 2) != 0)
difference += stepSize >> 1;
if ((delta & 1) != 0)
difference += stepSize >> 2;
if (sign != 0)
newSample -= (short)difference;
else
newSample += (short)difference;
// Increment index
index += indexTable[sample];
index = (int)MathHelper.Clamp(index, 0, 88);
newSample = (short)MathHelper.Clamp(newSample, -32768, 32767); // clamp between appropriate ranges
// compute new stepSize.
stepSize = stepSizeTable[index];
return newSample;
}
I don't believe the actual calculateNewSample() function is incorrect, as I've passed it the input values from http://www.cs.columbia.edu/~hgs/audio/dvi/p35.jpg and recieved the same output they have. I've tried flipping between the high/low order bytes to see if I've got that backwards to no avail as well. I feel like there's possibly something fundamental that I'm missing out on, but am having trouble finding it.
Any help would be seriously appreciated.
I found the following AES encryption class from another question here. The class (as is) works great, however, I have been trying to modify the class to my liking which is where I have encountered these errors. Please note that it is a binary file that I am trying to encrypt.
First I will explain the changes I am trying to make.
1) I want to change the parameter of the Encrypt function from a string, to a byte array. I thought this would be very simple task (just do a quick File.ReadAllBytes and pass the byte array to the Encrypt function) but this was not the case.
2) I want the decrypt function to return a byte array. Same issue as above, I can't get this to work properly.
I was hoping that someone would be able to give me a working example of encrypting and decrypting a binary file similar to what I have setup below:
private void button1_Click(object sender, EventArgs e)
{
SimpleAES sa = new SimpleAES();
OpenFileDialog ofd = new OpenFileDialog();
string s = string.Empty;
byte[] b = null;
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
b = File.ReadAllBytes(ofd.FileName);
b = sa.Encrypt(ByteToString(b);
}
File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\TestData123.exe", b);
}
private void button2_Click(object sender, EventArgs e)
{
SimpleAES sa = new SimpleAES();
byte[] b = File.ReadAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\TestData123.exe");
string s = sa.Decrypt(b);
File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\TestData123.exe");
File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\TestData.exe", b);
}
public byte[] StringToByte(string s)
{
Byte[] b = new byte[s.Length];
for (int i = 0; i < s.Length; i++)
{
char c = Convert.ToChar(s.Substring(i, 1));
b[i] = Convert.ToByte(c);
}
return b;
}
public string ByteToString(byte[] input)
{
StringBuilder ss = new System.Text.StringBuilder();
for (int i = 0; i < input.Length; i++)
{
// Convert each byte to char
char c = Convert.ToChar(input[i]);
ss.Append(Convert.ToString(c));
}
return ss.ToString();
}
Here is the AES class I am using:
using System;
using System.Data;
using System.Security.Cryptography;
using System.IO;
public class SimpleAES
{
// Change these keys
private byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 };
private ICryptoTransform EncryptorTransform, DecryptorTransform;
private System.Text.UTF8Encoding UTFEncoder;
public SimpleAES()
{
//This is our encryption method
RijndaelManaged rm = new RijndaelManaged();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// -------------- Two Utility Methods (not used but may be useful) -----------
/// Generates an encryption key.
static public byte[] GenerateEncryptionKey()
{
//Generate a Key.
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateKey();
return rm.Key;
}
/// Generates a unique encryption vector
static public byte[] GenerateEncryptionVector()
{
//Generate a Vector
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateIV();
return rm.IV;
}
/// ----------- The commonly used methods ------------------------------
/// Encrypt some text and return a string suitable for passing in a URL.
public string EncryptToString(string TextValue)
{
return ByteArrToString(Encrypt(TextValue));
}
/// Encrypt some text and return an encrypted byte array.
public byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);
//Used to stream the data in and out of the CryptoStream.
MemoryStream memoryStream = new MemoryStream();
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
#region Write the decrypted value to the encryption stream
CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
byte[] encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
memoryStream.Close();
return encrypted;
}
/// The other side: Decryption methods
public string DecryptString(string EncryptedString)
{
return Decrypt(StrToByteArray(EncryptedString));
}
/// Decryption when working with byte arrays.
public string Decrypt(byte[] EncryptedValue)
{
#region Write the encrypted value to the decryption stream
MemoryStream encryptedStream = new MemoryStream();
CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
Byte[] decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
encryptedStream.Close();
#endregion
return UTFEncoder.GetString(decryptedBytes);
}
/// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
// return encoding.GetBytes(str);
// However, this results in character values that cannot be passed in a URL. So, instead, I just
// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
public byte[] StrToByteArray(string str)
{
if (str.Length == 0)
throw new Exception("Invalid string value in StrToByteArray");
byte val;
byte[] byteArr = new byte[str.Length / 3];
int i = 0;
int j = 0;
do
{
val = byte.Parse(str.Substring(i, 3));
byteArr[j++] = val;
i += 3;
}
while (i < str.Length);
return byteArr;
}
// Same comment as above. Normally the conversion would use an ASCII encoding in the other direction:
// System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
// return enc.GetString(byteArr);
public string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
}
Thank you very much everyone!
Edited the code you provided to work as per the requirements.
private static byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private static byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 };
private static RijndaelManaged _rijndaelManaged;
static void Main(string[] args)
{
var allBytes = File.ReadAllBytes("hello.bin");
_rijndaelManaged = new RijndaelManaged { Key = Key, IV = Vector };
byte[] encBytes = Encrypt(allBytes, Key, Vector);
byte[] decBytes = Decrypt(encBytes, Key, Vector);
using (var mstream = new MemoryStream(decBytes))
using (var breader = new BinaryReader(mstream))
{
Console.WriteLine(breader.ReadString());
}
}
private static byte[] Decrypt(byte[] encBytes, byte[] key, byte[] vector)
{
byte[] decBytes;
using (var mstream = new MemoryStream())
using (var crypto = new CryptoStream(mstream, _rijndaelManaged.CreateDecryptor(key, vector), CryptoStreamMode.Write))
{
crypto.Write(encBytes, 0, encBytes.Length);
crypto.FlushFinalBlock();
mstream.Position = 0;
decBytes = new byte[mstream.Length];
mstream.Read(decBytes, 0, decBytes.Length);
}
return decBytes;
}
private static byte[] Encrypt(byte[] allBytes, byte[] key, byte[] vector)
{
byte[] encBytes;
using (var mstream = new MemoryStream())
using (var crypto = new CryptoStream(mstream, _rijndaelManaged.CreateEncryptor(key, vector), CryptoStreamMode.Write))
{
crypto.Write(allBytes, 0, allBytes.Length);
crypto.FlushFinalBlock();
mstream.Position = 0;
encBytes = new byte[mstream.Length];
mstream.Read(encBytes, 0, encBytes.Length);
}
return encBytes;
}
As Eoin explained, all you had to do was remove the line which converted the bytes back to the string. I posted the entire working code as I was not sure whether the input file being a binary file was causing any issues. It doesnt.
Evan,
I think you might be over complicating things here. And without doing any checking, I think the problem lies with your StringToByte & ByteToString methods. You should really be using one of the System.Text.Encoding classes for string->byte conversion (just like the AES Class does)
But if you only need to encrypt a source byte[] to a destination byte[] you can do the following and forget about strings completely.
Change the SimpleAES Encrypt & Decrypt Signatures as follows
public byte[] Encrypt(Byte[] bytes) //Change To take in a byte[]
{
//Translates our text value into a byte array.
//Byte[] bytes = UTFEncoder.GetBytes(TextValue); <-- REMOVE THIS LINE
... do stuff with `bytes`
}
public byte[] Decrypt(byte[] EncryptedValue) //now returns a byte array instead of a string
{
//return UTFEncoder.GetString(decryptedBytes); <-- JUST RETURN THE BYTE[] INSTEAD
return decryptedBytes;
}
So now you just feed it and input byte [] and receive an encrypted byte [] back.
You can verify this in the debugger using.
SimpleAES sa = new SimpleAES();
byte[] plainBytes = new byte[] { 0x01, 0xFF, 0x53, 0xC2};
byte[] encBytes = sa.Encrypt(plainBytes);
byte[] decBytes = sa.Decrypt(encBytes);
//BREAK HERE
//Compare the values of decBytes & plainBytes