Created
April 14, 2015 00:10
-
-
Save jchandra74/65052a3b17357cd5602d to your computer and use it in GitHub Desktop.
String Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace __NAMESPACE__ | |
{ | |
using System.Text; | |
using System.Security.Cryptography; | |
using System.Text.RegularExpressions; | |
public static class StringExtension | |
{ | |
public static string StripInvalidUnicodeCharacters(this string str) | |
{ | |
if (string.IsNullOrWhiteSpace(str)) return ""; | |
var invalidCharactersRegex = new Regex("(" | |
+ '\xFFFF' + "|" | |
+ "[\u0000-\u0008]|[\u000b-\u000c]|[\u000f-\u001f]|[\ud800-\udbff](?![\udc00-\udfff]))|((?<![\ud800-\udbff])[\udc00-\udfff])"); | |
return invalidCharactersRegex.Replace(str, ""); | |
} | |
public static string TrimLeadingZeros(this string str) | |
{ | |
if (string.IsNullOrWhiteSpace(str)) return ""; | |
var re = new Regex(@"^\s*0+"); | |
var output = re.Replace(str, ""); | |
return output; | |
} | |
private static string ByteArrayToString(byte[] ba) | |
{ | |
StringBuilder hex = new StringBuilder(ba.Length * 2); | |
foreach (byte b in ba) | |
hex.AppendFormat("{0:x2}", b); | |
return hex.ToString(); | |
} | |
public static string Hash(this string input) | |
{ | |
var saltedInput = "__REPLACE_WITH_YOUR_OWN_SALT_HERE__"; | |
var temp = Encoding.UTF8.GetBytes(saltedInput); | |
using (var sha1 = new SHA1Managed()) | |
{ | |
var hash = sha1.ComputeHash(temp); | |
return ByteArrayToString(hash); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment