Is there any Checksum like mechanism for JSON? - json

I need to upload large amount of JSON data to a webservice. Whats the best way to analyse that the server received the data correctly and all data is uploaded? Please let me know if anyone has any experience in this regards. Thanks.

You can check out my project :
https://github.com/hidayetcolkusu?tab=repositories
Calculation:
ChecksumCalculator checksumCalculator = new ChecksumCalculator();
string json = #"{""Name"":""Hidayet Raşit"",""Surname"":""ÇÖLKUŞU""}";
ushort checksum = checksumCalculator.Calculate(json);
Result: 43460
Comparing:
ChecksumCalculator checksumCalculator = new ChecksumCalculator();
string json = #"{""Name"":""Hidayet Raşit"",""Surname"":""ÇÖLKUŞU""}";
bool result = checksumCalculator.Compare(json, 43460);
Resut:true
Or
ChecksumCalculator checksumCalculator = new ChecksumCalculator();
string json = #"{""Name"":""Hidayet Raşit"",""Surname"":""ÇÖLKUŞU"",""Checksum"":43460}";
bool result = checksumCalculator.Compare(json);
Result:true

You can calculate json's hash value like this:
var sha1 = System.Security.Cryptography.SHA1.Create();
byte[] buf = System.Text.Encoding.UTF8.GetBytes(jsonString);
byte[] hash= sha1.ComputeHash(buf, 0, buf.Length);
var hashstr = System.BitConverter.ToString(hash).Replace("-", "");

You can calculate md5 to compare two json.
public static string CreateMD5(string json)
{
// Use json string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(json);
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}

Related

How to implement AES Encrypt (AesManaged Rfc2898DeriveBytes) in Windows Runtime

I met a blocking issue when I tried to immigrate my project from Windows Phone Silverlight 8.1 to Windows Runtime.
In Windows Runtime the AES-encrypted string is not the same as the one on Silverlight before.
In Silverlight:
public static string EncryptAES(string encryptString)
{
AesManaged aes = null;
MemoryStream ms = null;
CryptoStream cs = null;
string encryptKey = "testtest123";
string salt = "abcabcabcd";
try
{
Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(encryptKey, Encoding.UTF8.GetBytes(salt));
aes = new AesManaged();
aes.Key = rfc2898.GetBytes(aes.KeySize / 8);
aes.IV = rfc2898.GetBytes(aes.BlockSize / 8);
ms = new MemoryStream();
cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
byte[] data = Encoding.UTF8.GetBytes(encryptString);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch
{
return encryptString;
}
finally
{
if (cs != null)
cs.Close();
if (ms != null)
ms.Close();
if (aes != null)
aes.Clear();
}
}
In Windows Runtime:
public static string EncryptAES(string plainText)
{
string pw = "testtest123";
string salt = "abcabcabcd";
IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8);
IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8);
IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256);
// using salt and 1000 iterations
KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);
// create a key based on original key and derivation parmaters
CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);
// derive buffer to be used for encryption salt from derived password key
IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);
// display the buffers - because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial);
string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);
//AES_CBC_PKCS7
SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
// create symmetric key from derived password key
CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
// encrypt data buffer using symmetric key and derived salt material
IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial);
string result = CryptographicBuffer.EncodeToBase64String(resultBuffer);
return result;
}
In Silverlight Project, string "123456" encrypted by AES is "4UfdhC/0MFQlMhl7N7gqLg==";
While in Windows Runtime Project, the AES-encrypted string is "jxsR5EuhPXgRsHLs4N3EGQ=="
So how can I get the same string on WinRT as the one on Silverlight ?
The AES classes default to a random IV on the Microsoft runtimes. To get the same ciphertext you'll need to use a static IV. That's however not secure. Instead you should just check if you get the same key bytes and let the ciphertext differ for each run. Otherwise you can clearly distinguish identical plaintext.
You also seem to be using the wrong hash algorithm, Rfc2898DeriveBytes uses SHA-1 instead of SHA-256 as underlying hash function.
I've created class which works for me as replacement for System.Security.Cryptography.Rfc2898DeriveBytes:
public class Rfc2898DeriveBytes
{
private readonly string _password;
private readonly byte[] _salt;
public Rfc2898DeriveBytes(string password, byte[] salt)
{
_password = password;
_salt = salt;
IterationCount = 1000;
}
public uint IterationCount { get; set; }
public byte[] GetBytes(uint cb)
{
var provider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1);
var buffSecret = CryptographicBuffer.ConvertStringToBinary(_password, BinaryStringEncoding.Utf8);
var buffsalt = CryptographicBuffer.CreateFromByteArray(_salt);
var keyOriginal = provider.CreateKey(buffSecret);
var par = KeyDerivationParameters.BuildForPbkdf2(buffsalt, IterationCount);
var keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, par, cb);
byte[] result;
CryptographicBuffer.CopyToByteArray(keyMaterial, out result);
return result;
}
}

Windows phone can't save CookieContainer

I apologize for my english :)
I catch cookies from server. And try to save it in order to use cookeis later.
var Settings = IsolatedStorageSettings.ApplicationSettings;
CookieContainer _Cookie = new CookieContainer()
_Cookie.Add(new Uri("http://www.portal.fa.ru/Job/SearchResultDiv"), response.Cookies);
Settings.Clear();
Settings["UserID"] = userID;
Settings["Cookie"] = _Cookie;
Settings.Save();
Ok it working. But after restart app cookie has losted. (Object has remain but cookies count = 0). I don't know.
So i try to convert from CookieContainer to array byte than save and load it when i need it.
public static byte[] ToByte(CookieContainer data)
{
byte[] CookieByte;
DataContractSerializer serializer = new DataContractSerializer(typeof(CookieContainer));
using (var memoryStream = new MemoryStream())
{
serializer.WriteObject(memoryStream, data);
CookieByte = memoryStream.ToArray();
}
return CookieByte;
}
public static CookieContainer FromByte(byte[] data)
{
CookieContainer Cookie;
DataContractSerializer serializer = new DataContractSerializer(typeof(CookieContainer));
using (var memoryStream = new MemoryStream(data))
{
Cookie = (CookieContainer)serializer.ReadObject(memoryStream);
}
return Cookie;
}
But this code did not work again. When i convert to byte and back i losing cookies (count = 0).
So what can i do?
PS write pls your code when you deal with authorization and cookies. Thx

I'm getting wrong Json format while converting xml to Json and returning back in WCF

I'm using code as below
string strFetchResData = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
double RateId = 299;
bool UseNetMetering = true;
string StartTime = "2/26/2008%2011:00:00%20AM";
string EndTime = "2/26/2009%2010:00:00%20AM";
using (var client = new CookieAwareWebClient())
{
Uri uri = new Uri("https://www.myServiceUrl.com/Services.svc/SynthesizedBill?RateId=" + RateId + "&UseNetMetering=" + UseNetMetering + "&StartTime=" + StartTime + "&EndTime=" + EndTime + "");
client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["CPRUserName"], ConfigurationManager.AppSettings["CPRPassword"]);
strFetchResData = client.DownloadString(uri);
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(strFetchResData);
objSynthesizedData.PowerBill = JsonConvert.SerializeXmlNode(doc).Replace(#"#", #"").Remove(1, 44);
am Using Data member as
[DataContract]
public class SynthesizedPowerBill
{
[DataMember]
public string PowerBill { get; set; }
}
but I'm not getting the output in json format,
Why the format is not coming in JSON format? it is coming like a normal string, i want json format.
please help me..
Use a DataContractJsonSerializer instead?
http://msdn.microsoft.com/en-us/library/bb410770(v=vs.110).aspx

WCF, Serialize Json to XML

Using DataContractJsonSerializer, I was able to get Json string.
Now, I want to convert this Json(named 'stream') to XML.
Is there any way without using "[WebInvoke(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]"?
IService
[OperationContract]
string JsonSerializeFromDatabase();
[OperationContract]
string XmlSerializeFromJson(string strJson);
ClientSide
WCFService.Service1Client client = new WCFService.Service1Client();
string stream = client.JsonSerializeFromDatabase();
string stream2 = client.XmlSerializeFromJson(stream);
div1.InnerText = stream2;
ServerSide that I currently have (but no luck)
public string XmlSerializeFromJson(string strJson)
{
Stream stream1 = new FileStream("temp.xml", FileMode.Create);
XmlWriter xmlWriter = XmlWriter.Create(stream1);
XmlSerializerser = new XmlSerializer(typeof(string));
ser.Serialize(xmlWriter, strJson);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
string strXml = sr.ReadToEnd();
stream1.Dispose();
stream1.Close();
return strXml;
}
You need to first deserialize your json string into an instance of a type, and then create the serializer specifically to serialize the instance of the type to xml.
Something like:
var myInstance = new JavaScriptSerializer().Deserialize<InstanceType>(strJson);
var ser = new XmlSerializer(typeof(InstanceType));
ser.Serialize(xmlWriter, myInstance);

Convert Byte Array into List Windows phone 8

I am using this piece of code to convert List into byte array but again I want to convert to this data into List how it is possible.
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s)).ToArray();
In your example it isn't possible, because you have no way to tell where a string ends and where the next one starts. It would be possible by using a separator (the character \0 is often used to indicate the end of a string):
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s + '\0').ToArray();
You can then retrieve your list by using the Split method:
var stringList = System.Text.Encoding.UTF8.GetString(byteArr, 0, byteArr.Length).Split('\0');
But overall I don't think it's a good idea. Depending on what you need, I'd rather recommend to use the DataContractSerializer to convert your array to bytes:
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List<string>));
byte[] byteArr;
using (var ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, stringlist);
byteArr = ms.ToArray();
}
And to convert it back:
using (var ms = new System.IO.MemoryStream(byteArr))
{
stringlist = (Sserializer.ReadObject(ms);
}