Hey i trying decrypt byte to string, but something go wrong i got some errors like
source.cs(101,55): error CS0571: 'SymmetricAlgorithm.KeySize.set': cannot explicitly call operator or accessor
source.cs(102,34): error CS0571: 'SymmetricAlgorithm.BlockSize.set': cannot explicitly call operator or accessor
source.cs(104,97): error CS0571: 'SymmetricAlgorithm.KeySize.get': cannot explicitly call operator or accessor
i want decrypt 'test' static byte
my script
private static readonly byte[] saltBytes = new byte[16]
{
255,
64,
191,
111,
23,
3,
113,
119,
231,
121,
252,
112,
79,
32,
114,
156
};
private static readonly byte[] cryptKey = new byte[38]
{
104,
116,
116,
112,
115,
58,
47,
47,
103,
105,
116,
104,
117,
98,
46,
99,
111,
109,
47,
76,
105,
109,
101,
114,
66,
111,
121,
47,
83,
116,
111,
114,
109,
75,
105,
116,
116,
121
};
public static string test = Decrypt(new byte[32]
{
169,
182,
79,
179,
252,
54,
138,
148,
167,
99,
216,
216,
199,
219,
10,
249,
131,
166,
170,
145,
237,
248,
142,
78,
196,
137,
101,
62,
142,
107,
245,
134
});
public static string Decrypt(byte[] bytesToBeDecrypted)
{
byte[] bytes = null;
using (MemoryStream memoryStream = new MemoryStream())
{
RijndaelManaged val = new RijndaelManaged();
try
{
((SymmetricAlgorithm)val).set_KeySize(256);
((SymmetricAlgorithm)val).set_BlockSize(128);
Rfc2898DeriveBytes val2 = new Rfc2898DeriveBytes(cryptKey, saltBytes, 1000);
((SymmetricAlgorithm)val).set_Key(((DeriveBytes)val2).GetBytes(((SymmetricAlgorithm)val).get_KeySize() / 8));
((SymmetricAlgorithm)val).set_IV(((DeriveBytes)val2).GetBytes(((SymmetricAlgorithm)val).get_BlockSize() / 8));
((SymmetricAlgorithm)val).set_Mode((CipherMode)1);
CryptoStream val3 = new CryptoStream((Stream)memoryStream, ((SymmetricAlgorithm)val).CreateDecryptor(), (CryptoStreamMode)1);
try
{
((Stream)(object)val3).Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
((Stream)(object)val3).Close();
}
finally
{
((IDisposable)val3)?.Dispose();
}
bytes = memoryStream.ToArray();
}
finally
{
((IDisposable)val)?.Dispose();
}
}
return Encoding.UTF8.GetString(bytes);
}
Basically, property methods get_% or set_% is hided and secured by BindingFlags.NonPublic | BindingFlags.Instance. Seems be like mixing code from Reflection. It is not necessary, use standard assignment operators/public methods.
And... do not implicit cast RijndaelManaged to SymmetricAlgorithm multiple times - these are derived classes. It will works any case, but may hit performance.
public static string Decrypt(byte[] bytesToBeDecrypted)
{
byte[] bytes = Array.Empty<byte>();
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged val = new RijndaelManaged())
{
val.KeySize = 256;
val.BlockSize = 128;
Rfc2898DeriveBytes val2 = new Rfc2898DeriveBytes(cryptKey, saltBytes, 1000);
val.Key = val2.GetBytes(val.KeySize / 8);
val.IV = val2.GetBytes(val.BlockSize / 8);
val.Mode = CipherMode.CBC;
using (CryptoStream val3 = new CryptoStream(ms, val.CreateDecryptor(), CryptoStreamMode.Write))
{
val3.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
}
}
bytes = ms.ToArray();
}
return Encoding.UTF8.GetString(bytes);
}
I have aproblem with testing my unzip method.
My unit test method is like:
[Fact]
public void UnzipData_CalledWithByteArrayParameter_ReturnsString()
{
_serializationService.CallerName = "";
byte[] array = new byte[] { 31, 139, 8, 0, 0, 0, 0, 0, 0, 11, 117, 205, 49, 15, 130, 48, 16, 134, 255, 255, 114, 43, 148, 220, 157, 165, 45, 55, 234, 204, 98, 216, 140, 3, 9, 23, 37, 209, 18, 67, 53, 38, 134, 255, 46, 168, 139, 3, 243, 247, 189, 121, 14, 47, 232, 159, 32, 148, 195, 110, 136, 73, 99, 170, 135, 78, 47, 32, 47, 136, 237, 85, 65, 160, 214, 211, 185, 141, 144, 195, 163, 31, 251, 52, 126, 174, 93, 155, 150, 137, 145, 130, 65, 103, 152, 26, 44, 165, 172, 4, 109, 65, 155, 210, 57, 79, 25, 178, 32, 206, 213, 114, 221, 235, 237, 174, 99, 210, 238, 175, 129, 105, 202, 191, 56, 175, 226, 219, 97, 13, 174, 12, 178, 97, 219, 80, 16, 14, 98, 185, 32, 31, 188, 117, 62, 67, 90, 133, 127, 205, 12, 31, 223, 154, 207, 196, 62, 247, 0, 0, 0 };
string result = _serializationService.UnzipData(array);
Assert.False(result.Length == 0);
Assert.True(result.Length > array.Length);
}
but result variable is null. Sut based on this answer:
public string UnzipData(byte[] bytes)
{
LoadDictionaries();
CallerName = _messageService.GetCallerName();
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
try
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
CopyTo(gs, mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
catch (Exception e)
{
_logger.Error(e, MessagesError[CallerName]);
return null;
}
}
}
and
public static void CopyTo(Stream src, Stream dest)
{
byte[] bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
{
dest.Write(bytes, 0, cnt);
}
}
The main problem is that I am not quite sure how to pass byte[] compressed by GZipStream data in my unit test.
As I belive, in test preparation I am not supposed to do something like this? Is not it breaking testability?
[Fact]
public void UnzipData_CalledWithByteArrayParameter_ReturnsString()
{
_serializationService.CallerName = "";
string someString = "fdfsdfsdfsdfsf";
byte[] array = _serializationService.ZipData(someString); //using compress method first????
string result = _serializationService.UnzipData(array);
Assert.False(result.Length == 0);
Assert.True(result.Length > array.Length);
}
Or maybe I can?
ZipData method:
public byte[] ZipData(string data)
{
LoadDictionaries();
CallerName = _messageService.GetCallerName();
var bytes = Encoding.UTF8.GetBytes(data);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
try
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
CopyTo(msi, gs);
}
byte[] toReturn = mso.ToArray();
return toReturn;
}
catch (Exception e)
{
_logger.Error(e, MessagesError[CallerName]);
return null;
}
}
}
And compressing method returns me:
new byte[] { 31, 139, 8, 0, 0, 0, 0, 0, 0, 11, 125, 206, 61, 11, 194, 48, 16, 6, 224, 255, 114, 171, 77, 185, 94, 62, 74, 179, 234, 234, 34, 221, 196, 33, 144, 27, 2, 53, 197, 38, 138, 80, 250, 223, 141, 90, 16, 151, 194, 45, 7, 247, 222, 243, 158, 103, 8, 79, 176, 77, 5, 251, 49, 102, 142, 249, 56, 122, 30, 192, 206, 16, 221, 149, 193, 194, 193, 69, 7, 21, 120, 151, 223, 27, 97, 99, 4, 106, 129, 166, 39, 178, 100, 202, 212, 168, 100, 139, 170, 219, 33, 189, 196, 245, 244, 196, 183, 59, 167, 204, 254, 47, 3, 203, 182, 125, 61, 218, 240, 166, 129, 35, 151, 63, 143, 144, 66, 78, 159, 110, 63, 93, 9, 236, 4, 233, 30, 181, 45, 5, 164, 172, 165, 54, 70, 181, 155, 250, 154, 41, 250, 229, 5, 222, 237, 15, 25, 239, 0, 0, 0 }
from string:
[{\"ix\":1,\"ContentModel\":{\"name\":\"Dana\",\"date\":\"2016-05-06T22:26:26.0437049+02:00\",\"dateRequested\":\"2016-05-06\"}},{\"ix\":2,\"ContentModel\":{\"name\":\"Darlene\",\"visits\":1,\"date\":\"2014-09-25T05:22:33.3566479+02:00\",\"dateRequested\":\"2014-09-25\"}}]
UPDATED TEST
[Fact]
public void UnzipData_CalledWithByteArrayParameter_ReturnsString()
{
//string _jsonExample i converted in txtwizard.net/compression
string _jsonExample = "[{\"ix\":1,\"ContentModel\":{\"name\":\"Dana\",\"date\":\"2016-05-06T22:26:26.0437049+02:00\",\"dateRequested\":\"2016-05-06\"}},{\"ix\":2,\"ContentModel\":{\"name\":\"Darlene\",\"visits\":1,\"date\":\"2014-09-25T05:22:33.3566479+02:00\",\"dateRequested\":\"2014-09-25\"}}]";
var base64String = "H4sIAAAAAAAA/4WOPwvCMBDFv0tWm3K9/CnNqquLdDMOgdwQqCmaKIL0uxu1irgUbjjevXfvt79bFm6WmaaybD3GTDFvR09DkcopuiOVzbKNi86y4vEuvxWERnNQHHSPaFCXqUGKFmS3AjQAX/uOThdKmfxfzrJpqj79uNR/HijS6+c1pJDTzPzLIzl0HFUPyhQkIWqhtJbtIs+ce/IcHmtZn30RAQAA";
byte[] array = Convert.FromBase64String(base64String);
_serializationService.CallerName = "";
string result = _serializationService.UnzipData(array);
Assert.Equals(result, _jsonExample); //not equal, added extra backslashes
Assert.Equal("SomeMethod", _serializationService.CallerName);
_messageServiceMock.Verify(m => m.GetCallerName(It.IsAny<string>()), Times.Once);
}
Your source data in:-
byte[] array = new byte[] { 31, 139, 8, 0, 0, 0, 0, 0, 0, 11, 117, 205, 49, 15, 130, 48, 16, 134, 255, 255, 114, 43, 148, 220, 157, 165, 45, 55, 234, 204, 98, 216, 140, 3, 9, 23, 37, 209, 18, 67, 53, 38, 134, 255, 46, 168, 139, 3, 243, 247, 189, 121, 14, 47, 232, 159, 32, 148, 195, 110, 136, 73, 99, 170, 135, 78, 47, 32, 47, 136, 237, 85, 65, 160, 214, 211, 185, 141, 144, 195, 163, 31, 251, 52, 126, 174, 93, 155, 150, 137, 145, 130, 65, 103, 152, 26, 44, 165, 172, 4, 109, 65, 155, 210, 57, 79, 25, 178, 32, 206, 213, 114, 221, 235, 237, 174, 99, 210, 238, 175, 129, 105, 202, 191, 56, 175, 226, 219, 97, 13, 174, 12, 178, 97, 219, 80, 16, 14, 98, 185, 32, 31, 188, 117, 62, 67, 90, 133, 127, 205, 12, 31, 223, 154, 207, 196, 62, 247, 0, 0, 0 };
Is not valid Gzip data, and your method is throwing an InvalidDataException where you are returning null.
Otherwise, your method works fine with correct input data.
Using the core parts of your provided code to create a minimal example of the subject under test
public class Subject {
public byte[] ZipData(string data) {
//LoadDictionaries();
//CallerName = _messageService.GetCallerName();
var bytes = Encoding.UTF8.GetBytes(data);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream()) {
try {
using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
msi.CopyTo(gs);
}
byte[] toReturn = mso.ToArray();
return toReturn;
} catch (Exception e) {
// _logger.Error(e, MessagesError[CallerName]);
return Array.Empty<byte>();
}
}
}
public string UnzipData(byte[] bytes) {
//LoadDictionaries();
//CallerName = _messageService.GetCallerName();
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream()) {
try {
using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
gs.CopyTo(mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
} catch (Exception e) {
//_logger.Error(e, MessagesError[CallerName]);
return string.Empty;
}
}
}
}
The following test behaves as expected when exercised
[TestClass]
public class MyTestClass {
[TestMethod]
public void UnzipData_CalledWithByteArrayParameter_ReturnsString() {
//Arrange
var _serializationService = new Subject();
string expected = "[{\"ix\":1,\"ContentModel\":{\"name\":\"Dana\",\"date\":\"2016-05-06T22:26:26.0437049+02:00\",\"dateRequested\":\"2016-05-06\"}},{\"ix\":2,\"ContentModel\":{\"name\":\"Darlene\",\"visits\":1,\"date\":\"2014-09-25T05:22:33.3566479+02:00\",\"dateRequested\":\"2014-09-25\"}}]";
byte[] array = _serializationService.ZipData(expected);
//Act
string actual = _serializationService.UnzipData(array);
//Assert
actual.Should().NotBeNull()
.And.Be(expected);
}
}
Note the changes made to the used functions. Mainly not returning null which can bring its own complications.
Your assertions were also in accurate since the string and byte array lengths wont match given the zip process.
In my opinion zipping the data as part of arranging the test does not break isolation since the zip is not what is being tested (technically).
You could easily have rewritten the zip code again manually in the test to ensure you have correct data to supply to the member under test but why repeat existing functionality.
That would not be very DRY.
The assumption here would be that the zip functionality would have also had its own isolated unit test. If its test failed then that member is already covered.
I have Packet byte[]:
byte[] arr = {
17, 34, 51, 68, 85, 102, 0, 20, 34, 24, 129, 17, 8, 0, 69, 0, 0, 95,
88, 117, 0, 0, 128, 17, 136, 254, 10, 61, 50, 135, 172, 49, 112, 37,
9, 129, 6, 110, 0, 75, 244, 143, 4, 1, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 107, 105, 110, 111, 8, 6, 10, 61 ,50, 135,
9, 6, 255, 255, 255, 255, 31, 8, 55, 55, 55, 55, 55, 55, 40, 6, 0, 0, 0,
1, 44, 6, 53, 53, 53, 53, 30, 9, 55, 53, 50, 50, 53, 53, 53 };
What i want to do is try to change my Packet IP Address so i found this function that calculate Checksum and i only want to understand what parameters i need to send to this function (i don't have much knowledge in networking and i started to learn)
private Packet ChangePacketIp(Packet packet, IpV4Address oldIpAddress, IpV4Address newIpAddress)
{
// calculate the checksum
ushort checksum = ComputeHeaderIpChecksum(packet.Buffer, 0, packet.Buffer.Length);
// create header from checksum and data
byte[] header = new byte[packet.Buffer.Length + 2];
Array.Copy(packet.Buffer, 0, header, 2, packet.Buffer.Length);
header[0] = (byte)(checksum >> 8); // high byte first
header[1] = (byte)(checksum & 0xff); // low byte 2n)d
try
{
EthernetLayer ethernet = (EthernetLayer)packet.Ethernet.ExtractLayer();
IpV4Layer ipV4Layer = (IpV4Layer)packet.Ethernet.IpV4.ExtractLayer();
DateTime packetTimestamp = packet.Timestamp;
if (packet.Ethernet.IpV4.Source == oldIpAddress)
{
ipV4Layer.Source = newIpAddress;
ipV4Layer.HeaderChecksum = null;
}
else if (packet.Ethernet.IpV4.Destination == oldIpAddress)
{
ipV4Layer.CurrentDestination = newIpAddress;
ipV4Layer.HeaderChecksum = null;
}
if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
{
TcpLayer tcpLayer = (TcpLayer)packet.Ethernet.IpV4.Tcp.ExtractLayer();
tcpLayer.Checksum = null;
ILayer payload = packet.Ethernet.IpV4.Tcp.Payload.ExtractLayer();
return PacketBuilder.Build(packetTimestamp, ethernet, ipV4Layer, tcpLayer, payload);
}
else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
{
UdpLayer udpLayer = (UdpLayer)packet.Ethernet.IpV4.Udp.ExtractLayer();
udpLayer.Checksum = null;
ILayer payload = packet.Ethernet.IpV4.Udp.Payload.ExtractLayer();
return PacketBuilder.Build(packetTimestamp, ethernet, ipV4Layer, udpLayer, payload);
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
That would be
// calculate the checksum
ushort checksum = XYClassName.ComputeHeaderIpChecksum(arr, 0, arr.Length);
// create header from checksum and data
byte[] header = new byte[arr.Length + 2];
Array.Copy(arr, 0, header, 2, arr.Length);
header[0] = checksum >> 8; // high byte first
header[1] = checksum & 0xff; // low byte 2nd
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have this byte[] that represent IPv4 packet:
byte[] arr = { 0, 48, 136, 21, 69, 131, 0, 24, 231, 253, 174, 161, 8, 0, 69, 0, 0, 52, 2, 31, 64, 0, 128, 6, 230, 22, 212, 25, 99, 74, 202, 177, 16, 121, 194, 156, 0, 119, 160, 128, 75, 200, 249, 141, 210, 78, 80, 24, 64, 252, 130, 182, 0, 0, 65, 82, 84, 73, 67, 76, 69, 32, 51, 52, 13, 10 };
And i want to calculate the IPV4 address
Here's a simple parser to examine your byte array:
void Main()
{
byte[] arr = { 0, 48, 136, 21, 69, 131, 0, 24, 231, 253, 174, 161, 8, 0, 69, 0, 0, 52, 2, 31, 64, 0, 128, 6, 230, 22, 212, 25, 99, 74, 202, 177, 16, 121, 194, 156, 0, 119, 160, 128, 75, 200, 249, 141, 210, 78, 80, 24, 64, 252, 130, 182, 0, 0, 65, 82, 84, 73, 67, 76, 69, 32, 51, 52, 13, 10 };
var stream = new MemoryStream(arr, 0, arr.Length);
var reader = new BinaryReader(stream);
Print("Version and header length", reader.ReadByte());
Print("Diff services", reader.ReadByte());
Print("Total length", IPAddress.NetworkToHostOrder(reader.ReadInt16()));
Print("ID", IPAddress.NetworkToHostOrder(reader.ReadInt16()));
Print("Flags and offset", IPAddress.NetworkToHostOrder(reader.ReadInt16()));
Print("TTL", reader.ReadByte());
Print("Protocol", reader.ReadByte());
Print("Checksum", reader.ReadInt16());
Print("Source IP", new IPAddress((int) reader.ReadInt32()));
Print("Destination IP", new IPAddress((int) reader.ReadInt32()));
}
This produces this output:
Version and header length = 0
Diff services = 48
Total length = -30699
ID = 17795
Flags and offset = 24
TTL = 231
Protocol = 253
Checksum = -24146
Source IP = 8.0.69.0
Destination IP = 0.52.2.31
This doesn't seem very right (negative length/checksum? + the protocol should return '6' for TCP or '8' for UDP). You might want to verify your data is correct first.
I wrote this up with code from a tiny project of mine which might help you with future issues. Definitely look at the packet layout on wikipedia, you'll need it with DNS/UDP as well.