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'm using the "jose-jwt" library in C#. I'm able to get JWE encryption / decryption working for both RSA (RSA_OAEP_256, A256GCM) and EC (ECDH_ES_A256KW, A256GCM) in .NET 4.8. See sample code below.
However for .NET Core 3.1, only the RSA (RSA_OAEP_256, A256GCM) works. The "jose-jwt" library doesn't support EC (ECDH_ES_A256KW, A256GCM) in .NET Core.
Is it possible to use EC (ECDH_ES_A256KW, A256GCM) in .NET Core 3.1? If so, which library should I use? I've taken a look at the Microsoft library, but it appears EC (ECDH_ES_A256KW, A256GCM) is not support as well.
Microsoft.IdentityModel.JsonWebTokens;
Microsoft.IdentityModel.Tokens;
Note: I'm trying to encrypt a string using JWE, and not a claims list payload using JWT.
var payload = "some string";
// jose-jwt
// ECDH_ES_A256KW, A256GCM
var x = new byte[] { 4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9 };
byte[] y = { 131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53 };
var publicEccKey = EccKey.New(x, y, null, CngKeyUsages.KeyAgreement);
var token = JWT.Encode(payload, publicEccKey, JweAlgorithm.ECDH_ES_A256KW, JweEncryption.A256GCM);
//{
// "alg": "ECDH-ES+A256KW",
// "enc": "A256GCM",
// "epk": {
// "kty": "EC",
// "x": "Y-5VLvlizkiIkszi2Z8lKFwQUHrh6RbbIo0KOKm2clo",
// "y": "rducXOiOXDwchHTLfS03ZAQHzFRd4yiudAkzRsGLsvI",
// "crv": "P-256"
// }
//}
// jose-jwt
// RSA_OAEP_256, A256GCM
var publicRSAKey = new RSACryptoServiceProvider();
publicRSAKey.ImportParameters(new RSAParameters
{
// "n"
Modulus = Base64Url.Decode("0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"),
// "e"
Exponent = Base64Url.Decode("AQAB")
});
token = JWT.Encode(payload, publicRSAKey, JweAlgorithm.RSA_OAEP_256, JweEncryption.A256GCM);
//{
// "alg": "RSA-OAEP",
// "enc": "A256GCM"
//}
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 a nodejs buffer:
var buffer = new Buffer([33,49,0,32,0,0,0,0,2,230,69,56,0,1,125,181,99,99,136,122,92,1,99,196,231,90,205,20,75,233,5,103]);
var value = buffer.readUInt32BE(8);
//value == 48645432
I tried read value from C#:
var buffer = new byte[]{33,49,0,32,0,0,0,0,2,230,69,56,0,1,125,181,99,99,136,122,92,1,99,196,231,90,205,20,75,233,5,103};
var value = BitConverter.ToUInt32(buffer, 8)
//value == 944104962
So, I need get value 48645432 from my C# code.
How can I write a method from C# return exact value like readUInt32BE from nodejs?
EDIT: How to get little endian data from big endian in c# using bitConverter.ToInt32 method? not resolve my problem
I resolve my problem
var buffer = new byte[] { 33, 49, 0, 32, 0, 0, 0, 0, 2, 230, 69, 56, 0, 1, 125, 181, 99, 99, 136, 122, 92, 1, 99, 196, 231, 90, 205, 20, 75, 233, 5, 103 };
var value = BitConverter.ToUInt32(buffer, 8);
var rs = BitConverter.ToUInt32(BitConverter.GetBytes(value).Reverse().ToArray(), 0);
//rs = 48645432
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