/// <summary> /// Encrypt a string using Triple DES encryption and additional SHA1 hash. /// </summary> /// <param name="clearText">UTF8 Clear text to be encrypted</param> /// <param name="key">Encryption key used by both methods</param> /// <returns>Encrypted base 64 string</returns> /// public static string EncryptTextDual(string clearText, string key) { byte[] key24Len = new byte[24]; var toEncryptArray = Encoding.UTF8.GetBytes(clearText); var sha1Provider = new SHA512CryptoServiceProvider(); var keyArray = sha1Provider.ComputeHash(Encoding.UTF8.GetBytes(key)); sha1Provider.Clear(); for (int idx = 0; idx < 24; idx++) { key24Len[idx] = keyArray[idx]; } var tripleDesProvider = new TripleDESCryptoServiceProvider { }; tripleDesProvider.Key = key24Len; tripleDesProvider.Mode = CipherMode.ECB; tripleDesProvider.Padding = PaddingMode.PKCS7; var iCryptoTransform = tripleDesProvider.CreateEncryptor(); var resultArray = iCryptoTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tripleDesProvider.Clear(); return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); }
/// <summary> /// Decrypt a Base 64 string using Triple DES encryption method and SHA1 hash. /// </summary> /// <param name="cipherText">Encrypted text</param> /// <param name="key">Encryption key used by both methods</param> /// <returns>Clear text UTF8 string</returns> /// public static Tuple <string, bool> DecryptTextDual(string cipherText, string key) { try { var key24Len = new byte[24]; var toDecryptArray = Convert.FromBase64String(cipherText); var sha1Provider = new SHA512CryptoServiceProvider(); var keyArray = sha1Provider.ComputeHash(Encoding.UTF8.GetBytes(key)); sha1Provider.Clear(); for (var idx = 0; idx < 24; idx++) { key24Len[idx] = keyArray[idx]; } var tripleDesProvider = new TripleDESCryptoServiceProvider { }; tripleDesProvider.Key = key24Len; tripleDesProvider.Mode = CipherMode.ECB; tripleDesProvider.Padding = PaddingMode.PKCS7; var iCryptoTransform = tripleDesProvider.CreateDecryptor(); var resultArray = iCryptoTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length); tripleDesProvider.Clear(); return(new Tuple <string, bool>(Encoding.UTF8.GetString(resultArray), true)); } catch (Exception ex) { return(new Tuple <string, bool>(ex.Message, false)); } }
/* Good1() changes the "if" so that both branches use the GoodSink */ private void Good1() { if (IO.StaticReturnsTrueOrFalse()) { using (HashAlgorithm sha = new SHA512CryptoServiceProvider()) { /* FIX: Use a sufficiently random salt */ var salt = new byte[32]; using (var random = new RNGCryptoServiceProvider()) { random.GetNonZeroBytes(salt); byte[] textWithSaltBytes = Encoding.UTF8.GetBytes(string.Concat("hash me", salt)); byte[] hashedBytes = sha.ComputeHash(textWithSaltBytes); sha.Clear(); IO.WriteLine(IO.ToHex(hashedBytes)); } } } else { using (HashAlgorithm sha = new SHA512CryptoServiceProvider()) { /* FIX: Use a sufficiently random salt */ var salt = new byte[32]; using (var random = new RNGCryptoServiceProvider()) { random.GetNonZeroBytes(salt); byte[] textWithSaltBytes = Encoding.UTF8.GetBytes(string.Concat("hash me", salt)); byte[] hashedBytes = sha.ComputeHash(textWithSaltBytes); sha.Clear(); IO.WriteLine(IO.ToHex(hashedBytes)); } } } }
/* Good2() reverses the blocks in the switch */ private void Good2() { switch (7) { case 7: using (HashAlgorithm sha = new SHA512CryptoServiceProvider()) { /* FIX: Use a sufficiently random salt */ var salt = new byte[32]; using (var random = new RNGCryptoServiceProvider()) { random.GetNonZeroBytes(salt); byte[] textWithSaltBytes = Encoding.UTF8.GetBytes(string.Concat("hash me", salt)); byte[] hashedBytes = sha.ComputeHash(textWithSaltBytes); sha.Clear(); IO.WriteLine(IO.ToHex(hashedBytes)); } } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); break; } }
public static IEnumerable <byte> CalculateHash512(IEnumerable <byte> data) { var algorithm = new SHA512CryptoServiceProvider(); var result = algorithm.ComputeHash(data.ToArray()); algorithm.Clear(); return(result); }
public override void Bad() { using (HashAlgorithm sha = new SHA512CryptoServiceProvider()) { /* FLAW: SHA512 with no salt */ byte[] textWithoutSaltBytes = Encoding.UTF8.GetBytes("hash me"); byte[] hashedBytes = sha.ComputeHash(textWithoutSaltBytes); sha.Clear(); IO.WriteLine(IO.ToHex(hashedBytes)); } }
private string CalclateSha512(byte[] data) { // SHA512のプロバイダーを作成 var sha512 = new SHA512CryptoServiceProvider(); // ハッシュ値を計算 var hashedBytes = sha512.ComputeHash(data); // リソース開放 sha512.Clear(); // ハッシュ値をテキストに戻す return(GetTextFromHash(hashedBytes)); }
public static string SHA512Encrypt(string strIN) { byte[] tmpByte; SHA512 sha512 = new SHA512CryptoServiceProvider(); tmpByte = sha512.ComputeHash(GetKeyByteArray(strIN)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < tmpByte.Length; i++) { sb.Append(tmpByte[i].ToString("x2")); } sha512.Clear(); return(sb.ToString()); }
public static string GetHashString(string text) { byte[] data = Encoding.UTF8.GetBytes(text); var algorithm = new SHA512CryptoServiceProvider(); byte[] bs = algorithm.ComputeHash(data); algorithm.Clear(); var result = new StringBuilder(); foreach (byte b in bs) { result.Append(b.ToString("X2")); } return(result.ToString()); }
/// <summary> /// SHA512加密,不可逆转 /// </summary> /// <param name="data">string data:被加密的字符串</param> /// <param name="isBase64"></param> /// <returns>返回加密后的字符串</returns> public static string HashSHA512(string data, bool isBase64 = false) { SHA512 s512 = new SHA512CryptoServiceProvider(); byte[] byte1 = Encoding.Default.GetBytes(data); byte1 = s512.ComputeHash(byte1); s512.Clear(); if (isBase64) { return(Convert.ToBase64String(byte1)); } else { return(ConvertHelper.ToString(byte1)); } }
/// <summary> /// 计算SHA-512码 /// </summary> /// <param name="word">字符串</param> /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param> /// <returns></returns> public static string Hash_SHA_512(string word, bool toUpper = false) { try { SHA512CryptoServiceProvider SHA512CSP = new SHA512CryptoServiceProvider(); byte[] bytValue = Encoding.UTF8.GetBytes(word); byte[] bytHash = SHA512CSP.ComputeHash(bytValue); SHA512CSP.Clear(); //根据计算得到的Hash码翻译为SHA-1码 string sHash = "", sTemp = ""; for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } //根据大小写规则决定返回的字符串 return(toUpper ? sHash : sHash.ToLower()); } catch (Exception ex) { throw new Exception(ex.Message); } }
public override void Bad() { switch (7) { case 7: using (HashAlgorithm sha = new SHA512CryptoServiceProvider()) { /* FLAW: SHA512 with no salt */ byte[] textWithoutSaltBytes = Encoding.UTF8.GetBytes("hash me"); byte[] hashedBytes = sha.ComputeHash(textWithoutSaltBytes); sha.Clear(); IO.WriteLine(IO.ToHex(hashedBytes)); } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); break; } }
} //compute hash from arguments and return hash value as string private static string GetSHA512Hash(string text) { //create variables for computing hash and making it a string UnicodeEncoding UniCode = new UnicodeEncoding(); byte[] HashResult; byte[] msg = UniCode.GetBytes(text); SHA512 hashString = new SHA512CryptoServiceProvider(); string Str = ""; //compute hash with SHA512 module and format output as string //convert bytes in HashResult to string values HashResult = hashString.ComputeHash(msg); foreach (byte x in HashResult) { Str += String.Format("{0:x2}", x); } //clear excess resource usage hashString.Clear(); return(Str); } //compute hash from arguments and return hash value as string
/// <summary> /// Metodo para generar un token binario(Tipo no base2) /// </summary> /// <param name="idReceptor"></param> /// <returns></returns> public string generarTokenBinario(string consecutivo) { string resultado = ""; //Se inicializa el proveedor de servicio SHA512CryptoServiceProvider proServ = new SHA512CryptoServiceProvider(); try { //Se obtienen los bytes del consecutivo byte[] tokenBytes = System.Text.Encoding.UTF8.GetBytes(consecutivo); //Se aplica el hash byte[] tokBytes = proServ.ComputeHash(tokenBytes); //Se limpia el proveedor de servicios proServ.Clear(); resultado = Convert.ToBase64String(tokBytes); } catch (Exception) { } return(resultado); }
static int Main(string[] args) { try { string hash = string.Empty; string str = string.Empty; string result; if (args.Length != 2) { return(WriteError("Missing or invalid parameters")); } foreach (string arg in args) { switch (arg.Substring(0, 3).ToUpper()) { case "/A:": case "/H:": hash = arg.Substring(3).ToUpper(); break; case "/S:": str = arg.Substring(3); break; default: return(WriteError("Invalid parameter: " + arg)); } } if (string.IsNullOrEmpty(hash) || string.IsNullOrEmpty(str)) { return(WriteError("Missing required parameters")); } HashAlgorithm ha; switch (hash) { case "MD5": ha = new MD5CryptoServiceProvider(); break; case "SHA1": case "SHA-1": ha = new SHA1CryptoServiceProvider(); break; case "SHA256": case "SHA-256": ha = new SHA256CryptoServiceProvider(); break; case "SHA384": case "SHA-384": ha = new SHA384CryptoServiceProvider(); break; case "SHA512": case "SHA-512": ha = new SHA512CryptoServiceProvider(); break; default: return(WriteError("Invalid hash type")); } result = BitConverter.ToString(ha.ComputeHash(StrToByteArray(str))); ha.Clear(); StringBuilder sb = new StringBuilder(result.ToLowerInvariant()); Console.OpenStandardOutput(); Console.WriteLine(sb.Replace("-", "")); return(0); } catch (Exception e) { return(WriteError(e)); } }