Skip to content

Instantly share code, notes, and snippets.

@windwp
Last active November 2, 2015 10:19
Show Gist options
  • Save windwp/2b331cb141284cb7ee2c to your computer and use it in GitHub Desktop.
Save windwp/2b331cb141284cb7ee2c to your computer and use it in GitHub Desktop.
C# useful function
/// <summary>
/// Simple encrypt
/// </summary>
/// <param name="pstrText">String Encrypt</param>
/// <param name="deskey">key for encrypt only need 8 character</param>
/// <returns></returns>
public static string Encrypt(string pstrText, string deskey= "012345678")
{
byte[] byKey = { };
byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
byKey = System.Text.Encoding.UTF8.GetBytes(deskey.Substring(0, 8));
var des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(pstrText);
var ms = new MemoryStream();
var cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// Simple Decrypt
/// </summary>
/// <param name="pstrText">String Decrypt</param>
/// <param name="deskey">key for Decrypt only need 8 character</param>
/// <returns></returns>
public static string Decrypt(string pstrText, string deskey = "012345678")
{
try
{
pstrText = pstrText.Replace(" ", "+");
byte[] byKey = { };
byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
byte[] inputByteArray = new byte[pstrText.Length];
byKey = System.Text.Encoding.UTF8.GetBytes(deskey.Substring(0, 8));
var des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(pstrText);
var ms = new MemoryStream();
var cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception)
{
return string.Empty;
}
}
/// <summary>
/// Generates a unique Id as a string of up to 16 characters.
/// Based on a GUID and the size takes that subset of a the
/// Guid's 16 bytes to create a string id.
///
/// String Id contains numbers and lower case alpha chars 36 total.
///
/// Sizes: 6 gives roughly 99.97% uniqueness.
/// 8 gives less than 1 in a million doubles.
/// 16 will give full GUID strength uniqueness
/// </summary>
/// <returns></returns>
/// <summary>
public static string GenerateUniqueId(int stringSize = 8)
{
string chars = "abcdefghijkmnopqrstuvwxyz1234567890";
StringBuilder result = new StringBuilder(stringSize);
int count = 0;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
result.Append(chars[b % (chars.Length - 1)]);
count++;
if (count >= stringSize)
return result.ToString();
}
return result.ToString();
}
/// Generates a unique numeric ID. Generated off a GUID and
/// returned as a 64 bit long value
/// </summary>
/// <returns></returns>
public static long GenerateUniqueNumericId()
{
byte[] bytes = Guid.NewGuid().ToByteArray();
return BitConverter.ToInt64(bytes, 0);
}
/// <summary>Serializes the specified object as a JSON string</summary>
/// <param name="objectToSerialize">Specified object to serialize</param>
/// <returns>JSON string of serialzied object</returns>
private static string Serialize(object objectToSerialize)
{
using (System.IO.MemoryStream _Stream = new System.IO.MemoryStream())
{
try
{
var _Serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(objectToSerialize.GetType());
_Serializer.WriteObject(_Stream, objectToSerialize);
_Stream.Position = 0;
System.IO.StreamReader _Reader = new System.IO.StreamReader(_Stream);
return _Reader.ReadToEnd();
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Serialize:" + e.Message);
return string.Empty;
}
}
}
/// <summary>Deserializes the JSON string as a specified object</summary>
/// <typeparam name="T">Specified type of target object</typeparam>
/// <param name="jsonString">JSON string source</param>
/// <returns>Object of specied type</returns>
private static T Deserialize<T>(string jsonString)
{
using (System.IO.MemoryStream _Stream = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
try
{
var _Serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
return (T)_Serializer.ReadObject(_Stream);
}
catch (Exception) { throw; }
}
}
public string Serialize<T>(T settings)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
StringWriter outStream = new StringWriter();
serializer.Serialize(outStream, settings);
return outStream.ToString();
}
public T DeSerialize<T>(string xmlstring)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
StringReader outStream = new StringReader(xmlstring);
var obj=serializer.Deserialize(outStream);
return (T)obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment