public static string Sha1(string text) { byte[] buffer = Encoding.UTF8.GetBytes(text); SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider(); byte[] outbuffer = cryptoTransformSHA1.ComputeHash(buffer); return Convert.ToBase64String(outbuffer); }
/// <summary> /// Returns a byte array containing the proper encryption of the /// given password/seed according to the new 4.1.1 authentication scheme. /// </summary> /// <param name="password"></param> /// <param name="seed"></param> /// <returns></returns> private byte[] Get411Password(string password, byte[] seedBytes) { // if we have no password, then we just return 1 zero byte if (password.Length == 0) return new byte[1]; #if !NETSTANDARD1_6 SHA1 sha = new SHA1CryptoServiceProvider(); #else SHA1 sha = SHA1.Create(); #endif #if !NETSTANDARD1_6 byte[] firstHash = sha.ComputeHash(AliasText.Encoding.Default.GetBytes(password)); #else byte[] firstHash = sha.ComputeHash(AliasText.Encoding.UTF8.GetBytes(password)); #endif byte[] secondHash = sha.ComputeHash(firstHash); byte[] input = new byte[seedBytes.Length + secondHash.Length]; Array.Copy(seedBytes, 0, input, 0, seedBytes.Length); Array.Copy(secondHash, 0, input, seedBytes.Length, secondHash.Length); byte[] thirdHash = sha.ComputeHash(input); byte[] finalHash = new byte[thirdHash.Length + 1]; finalHash[0] = 0x14; Array.Copy(thirdHash, 0, finalHash, 1, thirdHash.Length); for (int i = 1; i < finalHash.Length; i++) finalHash[i] = (byte)(finalHash[i] ^ firstHash[i - 1]); return finalHash; }
public string GetGeneratedDatabasePincode (string plainPincode) { SHA1CryptoServiceProvider sha1Provider = new SHA1CryptoServiceProvider (); string pincode = string.Empty; if(!string.IsNullOrEmpty (plainPincode)){ pincode = plainPincode; } string key = string.Empty; #if DEBUG key = "XI134=fV$/IP/ qE@|3a0iI:-R-|<*6C>`!F,Np9O;L1KhT"; #else key += "35" + Android.OS.Build.Board.Length % 10 + Android.OS.Build.Brand.Length % 10 + Android.OS.Build.CpuAbi.Length % 10 + Android.OS.Build.Device.Length % 10 + Android.OS.Build.Display.Length % 10 + Android.OS.Build.Host.Length % 10 + Android.OS.Build.Id.Length % 10 + Android.OS.Build.Manufacturer.Length % 10 + Android.OS.Build.Model.Length % 10 + Android.OS.Build.Product.Length % 10 + Android.OS.Build.Tags.Length % 10 + Android.OS.Build.Type.Length % 10 + Android.OS.Build.User.Length % 10; #endif int hashRounds = 0; char[] charArray = key.ToCharArray (); Array.Reverse (charArray); hashRounds = Android.OS.Build.Board.Length % 2 == 0 ? 1 : 2; hashRounds += Android.OS.Build.Brand.Length % 2 == 0 ? 1 : 2; hashRounds += Android.OS.Build.Model.Length % 2 == 0 ? 1 : 2; hashRounds += Android.OS.Build.Device.Length % 2 == 0 ? 1 : 2; hashRounds += Android.OS.Build.Product.Length % 2 == 0 ? 1 : 2; string salt = Convert.ToBase64String (sha1Provider.ComputeHash (Encoding.Default.GetBytes (new string (charArray)))); for (int i = 0; i < hashRounds; i++) { if (string.IsNullOrEmpty (pincode)) { pincode = key; } pincode += i % 2 == 0 ? salt : string.Empty; byte[] originalBytes = Encoding.Default.GetBytes (pincode); byte[] encodedBytes = sha1Provider.ComputeHash (originalBytes); pincode = string.Empty; foreach (byte bit in encodedBytes) { pincode += bit.ToString ("x2"); } } SaveValueToKeyChain (StorageConstants.SaltStorageKey, salt); return pincode; }
/// <summary> /// Returns a byte array containing the proper encryption of the /// given password/seed according to the new 4.1.1 authentication scheme. /// </summary> /// <param name="password"></param> /// <param name="seed"></param> /// <returns></returns> public static byte[] Get411Password(string password, string seed) { // if we have no password, then we just return 2 zero bytes if (password.Length == 0) return new byte[1]; #if NET451 SHA1 sha = new SHA1CryptoServiceProvider(); #else SHA1 sha = SHA1.Create(); #endif byte[] firstHash = sha.ComputeHash(Encoding.UTF8.GetBytes(password)); byte[] secondHash = sha.ComputeHash(firstHash); byte[] seedBytes = Encoding.UTF8.GetBytes(seed); byte[] input = new byte[seedBytes.Length + secondHash.Length]; Array.Copy(seedBytes, 0, input, 0, seedBytes.Length); Array.Copy(secondHash, 0, input, seedBytes.Length, secondHash.Length); byte[] thirdHash = sha.ComputeHash(input); byte[] finalHash = new byte[thirdHash.Length + 1]; finalHash[0] = 0x14; Array.Copy(thirdHash, 0, finalHash, 1, thirdHash.Length); for (int i = 1; i < finalHash.Length; i++) finalHash[i] = (byte)(finalHash[i] ^ firstHash[i - 1]); return finalHash; //byte[] buffer = new byte[finalHash.Length - 1]; //Array.Copy(finalHash, 1, buffer, 0, finalHash.Length - 1); //return buffer; }
/// <summary> /// Creates a hash for the password. /// </summary> /// <param name="sessionId"> The current session id.</param> /// <param name="password"> The password.</param> /// <returns></returns> private string HashPassword(string sessionId, string password) { SHA1CryptoServiceProvider hashProvider = new SHA1CryptoServiceProvider(); string salt = Convert.ToBase64String(hashProvider.ComputeHash(System.Text.Encoding.UTF8.GetBytes(sessionId))); byte[] hash = hashProvider.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password + salt)); return Convert.ToBase64String(hash); }
private bool HashFilesEqual(byte[] contentFile1, byte[] contentFile2) { using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) { string hashFile1 = BitConverter.ToString(sha1.ComputeHash(contentFile1)).Replace("-", string.Empty); string hashFile2 = BitConverter.ToString(sha1.ComputeHash(contentFile2)).Replace("-", string.Empty); return hashFile1 == hashFile2; } }
private void Initialize() { rijndael = new RijndaelManaged() { Padding = PaddingMode.None }; aesInitializationVector = new byte[CRYPTO_BLOCK_SIZE]; int rawLength = 2 * password.Length; byte[] rawPassword = new byte[rawLength + 8]; byte[] passwordBytes = Encoding.Unicode.GetBytes(password); for (int i = 0; i < rawLength; i++) { rawPassword[i] = passwordBytes[i]; } for (int i = 0; i < salt.Length; i++) { rawPassword[i + rawLength] = salt[i]; } SHA1 sha = new SHA1CryptoServiceProvider(); const int noOfRounds = (1 << 18); IList<byte> bytes = new List<byte>(); byte[] digest; //TODO slow code below, find ways to optimize for (int i = 0; i < noOfRounds; i++) { bytes.AddRange(rawPassword); bytes.AddRange(new[] { (byte)i, (byte)(i >> 8), (byte)(i >> CRYPTO_BLOCK_SIZE) }); if (i % (noOfRounds / CRYPTO_BLOCK_SIZE) == 0) { digest = sha.ComputeHash(bytes.ToArray()); aesInitializationVector[i / (noOfRounds / CRYPTO_BLOCK_SIZE)] = digest[19]; } } digest = sha.ComputeHash(bytes.ToArray()); //slow code ends byte[] aesKey = new byte[CRYPTO_BLOCK_SIZE]; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) aesKey[i * 4 + j] = (byte) (((digest[i * 4] * 0x1000000) & 0xff000000 | (uint)((digest[i * 4 + 1] * 0x10000) & 0xff0000) | (uint)((digest[i * 4 + 2] * 0x100) & 0xff00) | (uint)(digest[i * 4 + 3] & 0xff)) >> (j * 8)); rijndael.IV = new byte[CRYPTO_BLOCK_SIZE]; rijndael.Key = aesKey; rijndael.BlockSize = CRYPTO_BLOCK_SIZE * 8; }
public static Assembly LoadDll(string dllname) { Assembly Target = Assembly.GetExecutingAssembly(); string resourceName = string.Format("{0}.Resources.{1}.dll", Target.GetName().Name, dllname); byte[] assemblyData = null; // Managed using (Stream stream = Target.GetManifestResourceStream(resourceName)) { assemblyData = new byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); try { return Assembly.Load(assemblyData); } catch { // Purposely do nothing // Unmanaged dll or assembly cannot be loaded directly from byte[] // Let the process fall through for next part } } // Unmanaged bool fileOk = false; string tempFile = Path.GetTempPath() + dllname + ".dll"; if (File.Exists(tempFile)) { byte[] bb = File.ReadAllBytes(tempFile); using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) { string fileHash = BitConverter.ToString(sha1.ComputeHash(assemblyData)).Replace("-", string.Empty); ; string fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).Replace("-", string.Empty); fileOk = (fileHash == fileHash2); } } if (!fileOk) { File.WriteAllBytes(tempFile, assemblyData); } //return Assembly.LoadFile(tempFile); LoadLibrary(tempFile); return null; }
/// <summary> /// Takes a string and generates a hash value of 16 bytes. /// </summary> /// <param name="buffer">The string to be hashed</param> /// <param name="passwordFormat">Selects the hashing algorithm used. Accepted values are "sha1" and "md5".</param> /// <returns>A string of the hashed password.</returns> public static string EncodeBinary(byte[] buffer, string passwordFormat) { if (buffer == null) { return(null); } byte[] result; switch (passwordFormat) { case "sha1": SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); result = sha1.ComputeHash(buffer); break; case "md5": MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); result = md5.ComputeHash(buffer); break; default: throw new ArgumentException("Invalid format value. Accepted values are 'sha1' and 'md5'.", nameof(passwordFormat)); } // Loop through each byte of the hashed data // and format each one as a hexadecimal string. var sb = new StringBuilder(16); foreach (byte t in result) { sb.Append(t.ToString("x2")); } return(sb.ToString()); }
static byte[] sha1(byte[] input) { byte[] hash; using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider()) hash = sha1.ComputeHash(input); return(hash); }
/// <summary> /// 验证消息是否来自微信服务器 /// </summary> /// <param name="signature">微信加密签名</param> /// <param name="timestamp">时间戳</param> /// <param name="nonce">随机数</param> /// <param name="echostr">随机字符串</param> /// <param name="token">公众号基本配置中填写的Token</param> /// <returns></returns> public static bool CheckSignature(string signature, string timestamp, string nonce) { if (String.IsNullOrEmpty(signature) || String.IsNullOrEmpty(timestamp) || String.IsNullOrEmpty(nonce)) { return(false); } List <string> sortList = new List <string> { timestamp, nonce, WxToken }; sortList.Sort(); byte[] data = WxEncoding.GetBytes(string.Join("", sortList)); System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] result = sha1.ComputeHash(data); //得到哈希值 string srt = System.BitConverter.ToString(result).Replace("-", "").ToLower(); //转换成为字符串的显示 if (srt == signature) { return(true); } else { return(false); } }
private byte[] CalculateHashValue(byte[] SerializedData) { // Calculte the serialized data's hash value SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider(); byte[] hash = SHA.ComputeHash(SerializedData); return hash; }
/// <summary> /// Open file and get it's SHA1 hash /// </summary> /// <param name="file_name">File name (full path)</param> /// <returns>String representation of the SHA1 hash</returns> public static string GetSHAHashFromFile(string file_name, SHAType shaType) { System.IO.FileStream file = new System.IO.FileStream(file_name, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] retVal = null; switch (shaType) { case SHAType.SHA1: System.Security.Cryptography.SHA1 sha1obj = new System.Security.Cryptography.SHA1CryptoServiceProvider(); retVal = sha1obj.ComputeHash(file); break; case SHAType.SHA256: System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create(); retVal = sha256.ComputeHash(file); break; case SHAType.SHA384: System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384.Create(); retVal = sha384.ComputeHash(file); break; case SHAType.SHA512: System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512.Create(); retVal = sha512.ComputeHash(file); break; } file.Close(); return(BitConverter.ToString(retVal).Replace("-", "").ToLower()); }
private string EncodeBySHA1(string str) { System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] data = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str)); return(Convert.ToBase64String(data)); }
// https://stackoverflow.com/a/800469 public static string GetHashSHA1(this byte[] data) { using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider()) { return(string.Concat(sha1.ComputeHash(data).Select(x => x.ToString("X2")))); } }
public static string GetSHA1Hash(string pathName) { string strResult = ""; string strHashData = ""; byte[] arrbytHashValue; System.IO.FileStream oFileStream = null; System.Security.Cryptography.SHA1CryptoServiceProvider osha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); try { oFileStream = new System.IO.FileStream(pathName.Replace("\"", ""), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); arrbytHashValue = osha1.ComputeHash(oFileStream); //计算指定Stream 对象的哈希值 oFileStream.Close(); //由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A” strHashData = System.BitConverter.ToString(arrbytHashValue); //替换- strHashData = strHashData.Replace("-", ""); strResult = strHashData; } catch (System.Exception ex) { Console.WriteLine(ex.Message); } return(strResult); }
internal static byte[] ComputeFileHash(byte[] fileBytes) { using (var sha1 = new SHA1CryptoServiceProvider()) { return sha1.ComputeHash(fileBytes); } }
private string EncodeByRSA(string str) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "请选择证书"; ofd.Filter = "pfx证书(*.pfx)|*.pfx"; if (ofd.ShowDialog() == DialogResult.Cancel) { return(string.Empty); } //1.读取证书中的私钥 //2.计算sha1值 //3.证书私钥->rsa->rsaformatter->对sha1值签名 string pfxPrivateKey; System.Security.Cryptography.X509Certificates.X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(ofd.FileName, "110110", X509KeyStorageFlags.Exportable); pfxPrivateKey = x509.PrivateKey.ToXmlString(true); Console.WriteLine(pfxPrivateKey); System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] hashResult = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str)); System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(pfxPrivateKey); System.Security.Cryptography.RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa); formatter.SetHashAlgorithm("sha1"); byte[] data = formatter.CreateSignature(hashResult); return(Convert.ToBase64String(data)); }
public static string GetSha1ByPathName(string pathName) { string strResult = string.Empty; System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1CryptoServiceProvider = new System.Security.Cryptography.SHA1CryptoServiceProvider(); System.IO.FileStream oFileStream = null; try { oFileStream = GetFileStream(pathName); byte[] bytHashValues = oSHA1CryptoServiceProvider.ComputeHash(oFileStream); strResult = System.BitConverter.ToString(bytHashValues) .Replace("-", string.Empty); } catch { } finally { if (oFileStream != null) { //oFileStream.Close(); oFileStream.Dispose(); oFileStream = null; } } return(strResult); }
internal static byte[] TripleDESKeyWrapDecrypt (byte[] rgbKey, byte[] rgbEncryptedWrappedKeyData) { // Check to see whether the length of the encrypted key is reasonable if (rgbEncryptedWrappedKeyData.Length != 32 && rgbEncryptedWrappedKeyData.Length != 40 && rgbEncryptedWrappedKeyData.Length != 48) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_KW_BadKeySize")); TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider(); // Assume no padding, use CBC mode tripleDES.Padding = PaddingMode.None; ICryptoTransform dec1 = tripleDES.CreateDecryptor(rgbKey, s_rgbTripleDES_KW_IV); byte[] temp2 = dec1.TransformFinalBlock(rgbEncryptedWrappedKeyData, 0, rgbEncryptedWrappedKeyData.Length); Array.Reverse(temp2); // Get the IV and temp1 byte[] rgbIV = new byte[8]; Buffer.BlockCopy(temp2, 0, rgbIV, 0, 8); byte[] temp1 = new byte[temp2.Length - rgbIV.Length]; Buffer.BlockCopy(temp2, 8, temp1, 0, temp1.Length); ICryptoTransform dec2 = tripleDES.CreateDecryptor(rgbKey, rgbIV); byte[] rgbWKCKS = dec2.TransformFinalBlock(temp1, 0, temp1.Length); // checksum the key byte[] rgbWrappedKeyData = new byte[rgbWKCKS.Length - 8]; Buffer.BlockCopy(rgbWKCKS, 0, rgbWrappedKeyData, 0, rgbWrappedKeyData.Length); SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); byte[] rgbCKS = sha.ComputeHash(rgbWrappedKeyData); for (int index = rgbWrappedKeyData.Length, index1 = 0; index < rgbWKCKS.Length; index++, index1++) if (rgbWKCKS[index] != rgbCKS[index1]) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_BadWrappedKeySize")); return rgbWrappedKeyData; }
/// <summary> /// Gets the SHA1 hash of a string. /// </summary> /// <param name="str">The string to be hashed.</param> /// <returns>The Base64 hashed value.</returns> public static string Sha1Hash(this string str) { using (var sha1 = new SHA1CryptoServiceProvider()) { return Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(str))); } }
public static string GetSHA1Hash(string pathName, string byteSeporator) { string strResult = ""; string strHashData = ""; byte[] arrbytHashValue; System.IO.FileStream oFileStream = null; System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher = new System.Security.Cryptography.SHA1CryptoServiceProvider(); try { oFileStream = GetFileStream(pathName); arrbytHashValue = oSHA1Hasher.ComputeHash(oFileStream); oFileStream.Close(); strHashData = System.BitConverter.ToString(arrbytHashValue); strHashData = strHashData.Replace("-", byteSeporator); strResult = strHashData; } catch //(System.Exception ex) { //System.Windows.Forms.MessageBox.Show(ex.Message, "Error!", //System.Windows.Forms.MessageBoxButtons.OK, //System.Windows.Forms.MessageBoxIcon.Error, //System.Windows.Forms.MessageBoxDefaultButton.Button1); } return(strResult); }
/// <summary> /// Хэширует текст /// </summary> /// <param name="phrase"></param> /// <returns></returns> public static string Sha1EncryptPassword(string phrase) { var encoder = new UTF8Encoding(); var sha1Hasher = new SHA1CryptoServiceProvider(); var hashedDataBytes = sha1Hasher.ComputeHash(encoder.GetBytes(phrase)); return ByteArrayToString(hashedDataBytes); }
static public string SHA1Encoding(string Data) { SHA1CryptoServiceProvider sp = new SHA1CryptoServiceProvider(); byte[] bdrr = System.Text.Encoding.UTF8.GetBytes(Data); byte[] barr = sp.ComputeHash(bdrr); return Convert.ToBase64String(barr); }
public static string sha1encrypt(string phrase) { UTF8Encoding encoder = new UTF8Encoding(); SHA1CryptoServiceProvider sha1hasher = new SHA1CryptoServiceProvider(); byte[] hashedDataBytes = sha1hasher.ComputeHash(encoder.GetBytes(phrase)); return byteArrayToString(hashedDataBytes); }
/// <summary> /// SHA1加密 使用缺省密钥给字符串加密 /// </summary> /// <param name="sourceString"></param> /// <returns></returns> public static string Sha1Encrypt(string sourceString) { var data = Encoding.Default.GetBytes(sourceString); HashAlgorithm sha = new SHA1CryptoServiceProvider(); var bytes = sha.ComputeHash(data); return BitConverter.ToString(bytes).Replace("-", ""); }
/// <summary> Private method used to calculate the sha1 check summ</summary> private void ComputeChecksum() { try { FileStream hashFile = new FileStream(fileName, FileMode.Open, FileAccess.Read); SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] result = sha1.ComputeHash(hashFile); hashFile.Close(); string buffer = ""; foreach (byte thisByte in result) { if (thisByte < 16) { buffer += "0" + thisByte.ToString("x"); } else { buffer += thisByte.ToString("x"); } } hashResult = buffer; errorFlag = false; } catch { hashResult = "ERROR"; errorFlag = true; } }
/// <summary> ///success url sayfası içerisinde HashParam değerinin doğruluğunu kontrol etmek amacıyla oluşturulan Verilen string'i SHA1 ile hashleyip Base64 formatına çeviren fonksiyondur. /// CreateToken'dan farklı olarak token oluşturmaz sadece hassh hesaplar /// </summary> /// <param name="hashString"></param> /// <returns></returns> public static string ComputeHash(string hashString) { System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] hashbytes = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(hashString); byte[] inputbytes = sha.ComputeHash(hashbytes); return(Convert.ToBase64String(inputbytes)); }
/// <summary> /// 引用证书非对称加/解密RSA-公钥验签【OriginalString:原文;SignatureString:签名字符;pubkey_path:证书路径;CertificatePW:证书密码;SignType:签名摘要类型(1:MD5,2:SHA1)】 /// </summary> public static bool CerRSAVerifySignature(string OriginalString, string SignatureString, string pubkey_path, string CertificatePW, int SignType) { byte[] OriginalByte = System.Text.Encoding.UTF8.GetBytes(OriginalString); byte[] SignatureByte = Convert.FromBase64String(SignatureString); X509Certificate2 x509_Cer1 = new X509Certificate2(pubkey_path, CertificatePW); RSACryptoServiceProvider rsapub = (RSACryptoServiceProvider)x509_Cer1.PublicKey.Key; rsapub.ImportCspBlob(rsapub.ExportCspBlob(false)); RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsapub); byte[] HashData; switch (SignType) { case 1: f.SetHashAlgorithm("MD5");//摘要算法MD5 MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); HashData = md5.ComputeHash(OriginalByte); break; default: f.SetHashAlgorithm("SHA1");//摘要算法SHA1 SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); HashData = sha.ComputeHash(OriginalByte); break; } if (f.VerifySignature(HashData, SignatureByte)) { return true; } else { return false; } }
public static string EncripContra(string password) { SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] input = (new UnicodeEncoding()).GetBytes(password); byte[] hash = sha1.ComputeHash(input); return(Convert.ToBase64String(hash)); }
public static string GetSHA1Checksum(byte[] inBytes) { using (SHA1CryptoServiceProvider _sha1CryptoServiceProvider = new SHA1CryptoServiceProvider()) { return BitConverter.ToString(_sha1CryptoServiceProvider.ComputeHash(inBytes)); } }
public static string EncodePassword(string originalPassword) { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] inputBytes = (new UnicodeEncoding()).GetBytes(originalPassword); byte[] hash = sha1.ComputeHash(inputBytes); return Convert.ToBase64String(hash); }
public string Sha1Hash(string input) { System.Security.Cryptography.SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input); byte[] value = sHA1CryptoServiceProvider.ComputeHash(bytes); return(System.BitConverter.ToString(value).Replace("-", string.Empty).ToLower()); }
private byte[] GetPasswordHash() { var data = Encoding.ASCII.GetBytes(Password); SHA1 sha1 = new SHA1CryptoServiceProvider(); var hashPassword = sha1.ComputeHash(data); return hashPassword; }
public ActionResult Index() { Init(); ViewData["timestamp"] = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; Random random = new Random(); ViewData["nonceStr"] = new string( Enumerable.Repeat("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 16) .Select(s => s[random.Next(s.Length)]) .ToArray()); ; string weaTokenFetchUrl = string.Format(@"https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={0}", weAccessToken.AccessToken); if (jsTicket==null||!jsTicket.IsValid) { using (var webClient = new WebClient()) { string response = webClient.DownloadString(weaTokenFetchUrl); jsTicket = JsonConvert.DeserializeObject<WEAJsApiTicket>(response); } } byte[] hashData = Encoding.Default.GetBytes(string.Format("jsapi_ticket={0}&noncestr={1}×tamp={2}&url={3}", jsTicket.Ticket, ViewData["nonceStr"].ToString(), ViewData["timestamp"].ToString(), Request.Url.AbsoluteUri)); SHA1 sha = new SHA1CryptoServiceProvider(); byte[] hashResult = sha.ComputeHash(hashData); string signature = BitConverter.ToString(hashResult).Replace("-", string.Empty).ToLower(); ViewData["signature"] = signature; return View(); }
public static string EncodePassword(string password) { using (SHA1CryptoServiceProvider Sha = new SHA1CryptoServiceProvider()) { return Convert.ToBase64String(Sha.ComputeHash(Encoding.ASCII.GetBytes(password))); } }
/// <summary> /// Computes the hash for the specified Stream. /// </summary> /// <param name="stream">The stream for the input data.</param> /// <returns>Hash value as a string.</returns> public string ComputeHashFromStream(Stream stream) { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] hash = sha1.ComputeHash(stream); return this.BytesToString(hash); }
static void Main(string[] args) { SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); Console.Write("Enter username: "******"Enter password: "******":" + password; byte[] temp2 = Encoding.ASCII.GetBytes(temp); sha.ComputeHash(temp2, 0, temp2.Length); string hash = String.Empty; for (int i = 0; i < sha.Hash.Length; i++) { hash += sha.Hash[i].ToString("X2"); } Console.WriteLine("Hash: {0}", hash); Console.ReadKey(); }
/// <summary> /// SHA1编码 /// </summary> /// <param name="value">明文</param> /// <param name="bit">位长</param> /// <returns></returns> public static string Get(string value, SHA1Bit bit) { StringBuilder sBuilder = new StringBuilder(); if (bit == SHA1Bit.L160) { System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider(); // This is one implementation of the abstract class SHA1. byte[] result = sha.ComputeHash(Encoding.Default.GetBytes(value)); sBuilder.Append(BitConverter.ToString(result).Replace("-", "")); } if (bit == SHA1Bit.L256) { System.Security.Cryptography.SHA256 sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider(); // This is one implementation of the abstract class SHA1. byte[] result = sha256.ComputeHash(Encoding.Default.GetBytes(value)); sBuilder.Append(BitConverter.ToString(result).Replace("-", "")); } if (bit == SHA1Bit.L384) { System.Security.Cryptography.SHA384 sha384 = new System.Security.Cryptography.SHA384CryptoServiceProvider(); // This is one implementation of the abstract class SHA1. byte[] result = sha384.ComputeHash(Encoding.Default.GetBytes(value)); sBuilder.Append(BitConverter.ToString(result).Replace("-", "")); } return(sBuilder.ToString()); }
/// <summary> /// Computes the hash value for the specified string. /// </summary> /// <param name="text">The text for the input data.</param> /// <returns>Hash value as a string.</returns> public string ComputeHash(string text) { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] hash = sha1.ComputeHash(Encoding.Default.GetBytes(text)); return this.BytesToString(hash); }
public static string GenerateToken(string subdomainName, string ssoKey, Object userAttributes, int valid_for=5*60) { string initVector = "OpenSSL for Ruby"; // DO NOT CHANGE byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector); byte[] keyBytesLong; using( SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider() ) { keyBytesLong = sha.ComputeHash( Encoding.UTF8.GetBytes( ssoKey + subdomainName ) ); } byte[] keyBytes = new byte[16]; Array.Copy(keyBytesLong, keyBytes, 16); var jsonText = JsonConvert.SerializeObject(userAttributes); Dictionary<string, dynamic> dict = JsonConvert.DeserializeObject<Dictionary<string, dynamic> >(jsonText); if (!dict.ContainsKey("expires")) { dict["expires"] = DateTime.UtcNow.AddSeconds(valid_for).ToString("u"); //Console.WriteLine("Setting expires " + dict["expires"]); } byte[] textBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dict)); for (int i = 0; i < 16; i++) { textBytes[i] ^= initVectorBytes[i]; } // Encrypt the string to an array of bytes byte[] encrypted = EncryptStringToBytesWithAES(textBytes, keyBytes, initVectorBytes); string encoded = Convert.ToBase64String(encrypted); return HttpUtility.UrlEncode(encoded); }
public static String Sha1(String s) { char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { //byte[] btInput = System.Text.Encoding.Default.GetBytes(s); byte[] btInput = System.Text.Encoding.UTF8.GetBytes(s);//by voidarea SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] md = sha.ComputeHash(btInput); // 把密文转换成十六进制的字符串形式 int j = md.Length; char[] str = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[(int)(((byte)byte0) >> 4) & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return(new string(str)); } catch (Exception e) { Console.Error.WriteLine(e.StackTrace); return(null); } }
// Slightly modified stackoverflow code for sha1 public static string CalculateSHA1(string text) { Encoding enc = Encoding.GetEncoding(1252); byte[] buffer = enc.GetBytes(text); SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider(); return BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", ""); }
// // internal static methods // // CMS TripleDES KeyWrap as described in "http://www.w3.org/2001/04/xmlenc#kw-tripledes" internal static byte[] TripleDESKeyWrapEncrypt (byte[] rgbKey, byte[] rgbWrappedKeyData) { // checksum the key SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); byte[] rgbCKS = sha.ComputeHash(rgbWrappedKeyData); // generate a random IV RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] rgbIV = new byte[8]; rng.GetBytes(rgbIV); // rgbWKCS = rgbWrappedKeyData | (first 8 bytes of the hash) byte[] rgbWKCKS = new byte[rgbWrappedKeyData.Length + 8]; TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider(); // Don't add padding, use CBC mode: for example, a 192 bits key will yield 40 bytes of encrypted data tripleDES.Padding = PaddingMode.None; ICryptoTransform enc1 = tripleDES.CreateEncryptor(rgbKey, rgbIV); Buffer.BlockCopy(rgbWrappedKeyData, 0, rgbWKCKS, 0, rgbWrappedKeyData.Length); Buffer.BlockCopy(rgbCKS, 0, rgbWKCKS, rgbWrappedKeyData.Length, 8); byte[] temp1 = enc1.TransformFinalBlock(rgbWKCKS, 0, rgbWKCKS.Length); byte[] temp2 = new byte[rgbIV.Length + temp1.Length]; Buffer.BlockCopy(rgbIV, 0, temp2, 0, rgbIV.Length); Buffer.BlockCopy(temp1, 0, temp2, rgbIV.Length, temp1.Length); // temp2 = REV (rgbIV | E_k(rgbWrappedKeyData | rgbCKS)) Array.Reverse(temp2); ICryptoTransform enc2 = tripleDES.CreateEncryptor(rgbKey, s_rgbTripleDES_KW_IV); return enc2.TransformFinalBlock(temp2, 0, temp2.Length); }
public static String Sha1(String s) { char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { byte[] btInput = System.Text.Encoding.Default.GetBytes(s); SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] md = sha.ComputeHash(btInput); // 把密文转换成十六进制的字符串形式 int j = md.Length; char[] str = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[(int)(((byte)byte0) >> 4) & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new string(str); } catch (Exception e) { Console.Error.WriteLine(e.StackTrace); return null; } }
public string SHA1Encrypt(string normalTxt) { var bytes = Encoding.Default.GetBytes(normalTxt); var SHA = new System.Security.Cryptography.SHA1CryptoServiceProvider(); var encryptbytes = SHA.ComputeHash(bytes); return(Convert.ToBase64String(encryptbytes)); }
private static string CalculateSha1(string text, Encoding enc) { byte[] buffer = enc.GetBytes(text); System.Security.Cryptography.SHA1CryptoServiceProvider cryptoTransformSha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); string hash = BitConverter.ToString(cryptoTransformSha1.ComputeHash(buffer)).Replace("-", ""); return(hash); }
public static string Sha1Sum2(string str) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] bytes = encoding.GetBytes(str); var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider(); return(System.BitConverter.ToString(sha.ComputeHash(bytes))); }
/// /// SHA1 加密(不可逆加密) /// /// 要加密的原始字串 /// public static string SHA1Encrypt(string pass) { System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] bytResult = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(pass)); sha1.Clear(); string strResult = BitConverter.ToString(bytResult); strResult = strResult.Replace("-", ""); return(strResult); }
public string HashString(char[] chData, byte[] byData) { for (int i = 0; i < chData.Length; i++) { byData[i] = (byte)chData[i]; } System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); return(HexStringFromBytes(sha1.ComputeHash(byData))); }
private static string Get_SHA1(string strSource) { System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] bytResult = sha.ComputeHash(Encoding.Default.GetBytes(strSource)); //转换成字符串,32位 string strResult = BitConverter.ToString(bytResult); //BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉 strResult = strResult.Replace("-", ""); return(strResult); }
public static String HashText(String TextToHash) { SHA1CryptoServiceProvider SHA1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); Byte[] bytValue = Encoding.UTF8.GetBytes(TextToHash); Byte[] bytHash = SHA1.ComputeHash(bytValue); SHA1.Clear(); //Return a base 64 encoded string of the Hash value return(Convert.ToBase64String(bytHash)); }
/// <summary> /// /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static string GetSha1String(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } System.Security.Cryptography.SHA1CryptoServiceProvider osha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] retVal = osha1.ComputeHash(buffer); osha1.Dispose(); return(BitConverter.ToString(retVal).Replace("-", "")); }
public static string GetSHA1Hash(string password) { SHA1CryptoServiceProvider oSHA1Hasher = new System.Security.Cryptography.SHA1CryptoServiceProvider(); Byte[] hashedBytes = null; UTF8Encoding encoder = new System.Text.UTF8Encoding(); hashedBytes = oSHA1Hasher.ComputeHash(encoder.GetBytes(password)); return(Encoding.Default.GetString(hashedBytes)); }
public static string GetSha1(string input) { System.Security.Cryptography.SHA1CryptoServiceProvider x = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] bs = System.Text.Encoding.UTF8.GetBytes(input); bs = x.ComputeHash(bs); System.Text.StringBuilder s = new System.Text.StringBuilder(); foreach (byte b in bs) { s.Append(b.ToString("x2").ToLower()); } return(s.ToString()); }
/// <summary> /// /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static byte[] GetSha1Bytes(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } System.Security.Cryptography.SHA1CryptoServiceProvider osha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] retVal = osha1.ComputeHash(buffer); osha1.Dispose(); return(retVal); }
/// <summary> /// Return SHA-1 hash for a string. /// </summary> /// <param name="text">Source text to calculate hash from</param> /// <param name="encoding">Text encoding</param> /// <returns>SHA1 hash in hex format</returns> public static string SHA1(string text, Encoding encoding) { if (text == null || encoding == null) { return(null); } using (System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider()) { byte[] array = sha.ComputeHash(encoding.GetBytes(text)); return(Energy.Base.Hex.ArrayToHex(array).ToLower()); } }
public static string GetSHA1Digest(string Message) { byte[] data = System.Text.Encoding.ASCII.GetBytes(Message); System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] result = sha1.ComputeHash(data); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < result.Length; i++) { sb.Append(result[i].ToString("X2")); } return(sb.ToString().ToLower()); }
public static string SHA(byte[] buffer) { System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider(); //计算哈希值 byte[] bytes = sha.ComputeHash(buffer); StringBuilder sbTemp = new StringBuilder(); foreach (byte i in bytes) { sbTemp.AppendFormat("{0:x2}", i); } return(sbTemp.ToString().ToUpper()); }
string GetHashSHA1(string input) { byte[] hash; using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider()) hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)); var sb = new StringBuilder(); foreach (byte b in hash) { sb.AppendFormat("{0:x2}", b); } return(sb.ToString()); }