public static string convertEncoding(string src, System.Text.Encoding srcEncode, System.Text.Encoding destEncode) { if (src == null) { return null; } if (srcEncode == null || destEncode == null) { return src; } try { byte[] srcBytes = srcEncode.GetBytes(src); byte[] destBytes = System.Text.Encoding.Convert(destEncode, srcEncode, srcBytes); char[] destChars = new char[destEncode.GetCharCount(destBytes, 0, destBytes.Length)]; destEncode.GetChars(destBytes, 0, destBytes.Length, destChars, 0); string destString = new string(destChars); return destString; } catch (Exception ex) { log.Error("convert encoding failed:", ex); } return src; }
static public void WriteAllText(string path, string text, System.Text.Encoding encoding = null) { if (encoding == null) encoding = System.Text.Encoding.UTF8; WriteAllBytes(path, encoding.GetBytes(text)); }
public void Add (string data, System.Text.Encoding enc = null) { if (enc == null) { enc = System.Text.Encoding.UTF8; } Add (new MemoryStream (enc.GetBytes (data))); }
private unsafe void CreateFirstSubstData(string s, IIS7WorkerRequest iis7WorkerRequest, System.Text.Encoder encoder) { IntPtr ptr; int num = 0; int length = s.Length; if (length > 0) { fixed (char* str = ((char*) s)) { char* chars = str; int size = encoder.GetByteCount(chars, length, true); ptr = iis7WorkerRequest.AllocateRequestMemory(size); if (ptr != IntPtr.Zero) { num = encoder.GetBytes(chars, length, (byte*) ptr, size, true); } } } else { ptr = iis7WorkerRequest.AllocateRequestMemory(1); } if (ptr == IntPtr.Zero) { throw new OutOfMemoryException(); } this._firstSubstData = ptr; this._firstSubstDataSize = num; }
public string ConvertEncoding(string _src , System.Text.Encoding _srcEncoding , System.Text.Encoding _destEncoding) { byte[] srcBytes = _srcEncoding.GetBytes(_src); return _destEncoding.GetString(srcBytes); }
private static void ValidateImage(System.Web.Helpers.WebImage image) { if (image.Width < MaxWidth || image.Height < MaxHeight) throw new Exception("The uploaded image must have a width and height larger than 48px."); if (image.GetBytes().Length > MaxBytes) throw new Exception("The file you are uploading is too large, please upload a file that is 1MB or smaller in size."); }
public static string Base64Encoding(string EncodingText, System.Text.Encoding oEncoding = null) { if (oEncoding == null) oEncoding = System.Text.Encoding.UTF8; byte[] arr = oEncoding.GetBytes(EncodingText); return System.Convert.ToBase64String(arr); }
/// <summary> /// 使用MD5加密字符串(指定编码) /// </summary> /// <param name="data">要加密的字符串</param> /// <param name="encode">要使用的编码</param> /// <returns>返回加密后的字符</returns> public static string EncryptString(string data, System.Text.Encoding encode) { byte[] bytes=encode.GetBytes(data); bytes = EncryptBytes(bytes); System.Text.StringBuilder sb = new System.Text.StringBuilder(bytes.Length * 2); bytes.ToList().ForEach(b=> sb.Append(b.ToString("X2"))); return sb.ToString(); }
public static string ConvertStringToHex(String input, System.Text.Encoding encoding) { Byte[] stringBytes = encoding.GetBytes(input); StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2); foreach (byte b in stringBytes) { sbBytes.AppendFormat("{0:X2}", b); } return sbBytes.ToString(); }
/// <summary> /// 编码字符串 /// </summary> /// <param name="inputString">输入文本</param> /// <param name="encoding">字符编码</param> /// <returns></returns> public static string EncryptString(string inputString, System.Text.Encoding encoding) { byte[] bInput = encoding.GetBytes(inputString); try { return System.Convert.ToBase64String(bInput, 0, bInput.Length); } catch { throw; } }
// // HttpUtility を使わないUrlEncodeの実装 // From http://d.hatena.ne.jp/kazuv3/20080605/1212656674 // public static string UrlEncode(string s, System.Text.Encoding enc) { System.Text.StringBuilder rt = new System.Text.StringBuilder(); foreach (byte i in enc.GetBytes(s)) if (i == 0x20) rt.Append('+'); else if (i >= 0x30 && i <= 0x39 || i >= 0x41 && i <= 0x5a || i >= 0x61 && i <= 0x7a) rt.Append((char)i); else rt.Append("%" + i.ToString("X2")); return rt.ToString(); }
private string EncodeHmac(string input, byte[] key, System.Text.Encoding encoding) { // City uses SHA-256 HMACSHA256 hmacSha = new HMACSHA256(key); byte[] byteArray = encoding.GetBytes(input); MemoryStream stream = new MemoryStream(byteArray); byte[] hashValue = hmacSha.ComputeHash(stream); string hashValueString = encoding.GetString(hashValue); //return BitConverter.ToString(hashValue); return hashValueString; }
public static string HashString(this System.Security.Cryptography.HashAlgorithm algo, string value, System.Text.Encoding encoding = null) { if (encoding == null) encoding = System.Text.Encoding.Default; algo.Initialize(); byte[] hashBytes = algo.ComputeHash(encoding.GetBytes(value)); StringBuilder sbHash = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { sbHash.Append(hashBytes[i].ToString("x").ToLower().PadLeft(2, '0')); } return sbHash.ToString(); }
static bool IsEncodable(String s, System.Text.Encoding e) { bool result = false; try { byte[] b = e.GetBytes(s); var s2 = e.GetString(b); result = (s == s2); } catch { result = false; } return result; }
/// <summary> /// 读取最新文件内容,只管读就是了,FileWatch会自动加载最新的文件 /// </summary> /// <param name="file"> </param> /// <param name="encoding"> </param> /// <param name="afterHander"> </param> /// <param name="preHander"> </param> /// <returns> </returns> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="NullReferenceException"></exception> public static string GetFileCurrentContent(string file, System.Text.Encoding encoding, Func<string, string> preHander, Func<string, string> afterHander) { if (!File.Exists(file)) { throw new FileNotFoundException(file); } var content = FileWatchStorageProvider.Provider.Get(file); if (content == null) { Action readFile = () => { var strFileContent = IOUtility.ReadAsString(file); if (preHander != null) strFileContent = preHander(strFileContent); content = encoding.GetBytes(strFileContent); FileWatchStorageProvider.Provider.AddOrUpdate(file, content); }; readFile(); var fw = new FileWatcher(file) { OnChanged = (o, e) => readFile() }; } if (content == null) throw new NullReferenceException("content"); var strcontent = encoding.GetString(content); if (afterHander != null) { return afterHander(strcontent); } return strcontent; }
/// <summary> /// StingComPressToString /// </summary> /// <param name="str"></param> /// <param name="encoding"></param> /// <returns>string / null</returns> public string StingComPressToString(string str, System.Text.Encoding encoding) { var stringbyte = encoding.GetBytes(str); if (stringbyte.Count() > 0) { var ms = new System.IO.MemoryStream(stringbyte); if (ms.Length > 0) { var bytetobyte = FileStreamComPressToByte(ms); if (bytetobyte != null && bytetobyte.Count() > 0) { var bytestr = encoding.GetString(bytetobyte); if (!string.IsNullOrEmpty(bytestr)) { return bytestr; } } } } return null; }
/// <summary> /// 计算指定字符串的MD5值 /// </summary> /// <param name="key">要计算Hash的字符串</param> /// <param name="encoding">计算Hash的编码方法</param> /// <returns>字符串的Hash</returns> public static string MD5(this string key, System.Text.Encoding encoding) { if (key == null) throw new ArgumentNullException(); var md5 = System.Security.Cryptography.MD5CryptoServiceProvider.Create(); var has = md5.ComputeHash(encoding.GetBytes(key)); return BitConverter.ToString(has).Replace("-", "").ToUpper(); }
public static byte[] GetBytes(string stingMessage, System.Text.Encoding e) { return e.GetBytes(stingMessage); }
/// <summary> /// 文件下载 ,以指定编码下载 /// </summary> /// <param name="encoder">文件编码</param> /// <param name="content">文件内容</param> /// <param name="contentType">文件MiniType</param> /// <param name="downloadFileName">下载名</param> /// <returns></returns> public FileResult File(System.Text.Encoding encoder, string content, string contentType, string downloadFileName) { return File(encoder.GetBytes(content), contentType, downloadFileName); }
/// <summary> /// ��ָ�������String����MD5, ���ؾ��������String /// </summary> /// <param name="data"></param> /// <param name="encoding"></param> /// <returns></returns> public static string ToString(string data, System.Text.Encoding encoding) { return BitConverter.ToString( provider.ComputeHash( encoding.GetBytes( data))).Replace("-", ""); }
/// <summary> /// ��ָ�������String����MD5, ����ԭʼ��MD5�ֽ����� /// </summary> /// <param name="data"></param> /// <param name="encoding"></param> /// <returns></returns> public static byte[] ToBytes(string data, System.Text.Encoding encoding) { return provider.ComputeHash( encoding.GetBytes( data)); }
private static byte[] GenCentralDirectoryFooter(long StartOfCentralDirectory, long EndOfCentralDirectory, Zip64Option zip64, int entryCount, string comment, System.Text.Encoding encoding) { int j = 0; int bufferLength = 22; byte[] block = null; Int16 commentLength = 0; if ((comment != null) && (comment.Length != 0)) { block = encoding.GetBytes(comment); commentLength = (Int16)block.Length; } bufferLength += commentLength; byte[] bytes = new byte[bufferLength]; int i = 0; // signature byte[] sig = BitConverter.GetBytes(ZipConstants.EndOfCentralDirectorySignature); Array.Copy(sig, 0, bytes, i, 4); i+=4; // number of this disk // (this number may change later) bytes[i++] = 0; bytes[i++] = 0; // number of the disk with the start of the central directory // (this number may change later) bytes[i++] = 0; bytes[i++] = 0; // handle ZIP64 extensions for the end-of-central-directory if (entryCount >= 0xFFFF || zip64 == Zip64Option.Always) { // the ZIP64 version. for (j = 0; j < 4; j++) bytes[i++] = 0xFF; } else { // the standard version. // total number of entries in the central dir on this disk bytes[i++] = (byte)(entryCount & 0x00FF); bytes[i++] = (byte)((entryCount & 0xFF00) >> 8); // total number of entries in the central directory bytes[i++] = (byte)(entryCount & 0x00FF); bytes[i++] = (byte)((entryCount & 0xFF00) >> 8); } // size of the central directory Int64 SizeOfCentralDirectory = EndOfCentralDirectory - StartOfCentralDirectory; if (SizeOfCentralDirectory >= 0xFFFFFFFF || StartOfCentralDirectory >= 0xFFFFFFFF) { // The actual data is in the ZIP64 central directory structure for (j = 0; j < 8; j++) bytes[i++] = 0xFF; } else { // size of the central directory (we just get the low 4 bytes) bytes[i++] = (byte)(SizeOfCentralDirectory & 0x000000FF); bytes[i++] = (byte)((SizeOfCentralDirectory & 0x0000FF00) >> 8); bytes[i++] = (byte)((SizeOfCentralDirectory & 0x00FF0000) >> 16); bytes[i++] = (byte)((SizeOfCentralDirectory & 0xFF000000) >> 24); // offset of the start of the central directory (we just get the low 4 bytes) bytes[i++] = (byte)(StartOfCentralDirectory & 0x000000FF); bytes[i++] = (byte)((StartOfCentralDirectory & 0x0000FF00) >> 8); bytes[i++] = (byte)((StartOfCentralDirectory & 0x00FF0000) >> 16); bytes[i++] = (byte)((StartOfCentralDirectory & 0xFF000000) >> 24); } // zip archive comment if ((comment == null) || (comment.Length == 0)) { // no comment! bytes[i++] = (byte)0; bytes[i++] = (byte)0; } else { // the size of our buffer defines the max length of the comment we can write if (commentLength + i + 2 > bytes.Length) commentLength = (Int16)(bytes.Length - i - 2); bytes[i++] = (byte)(commentLength & 0x00FF); bytes[i++] = (byte)((commentLength & 0xFF00) >> 8); if (commentLength != 0) { // now actually write the comment itself into the byte buffer for (j = 0; (j < commentLength) && (i + j < bytes.Length); j++) { bytes[i + j] = block[j]; } i += j; } } // s.Write(bytes, 0, i); return bytes; }
public virtual int Load(string data, System.Text.Encoding encoding) { byte[] blob = encoding.GetBytes(data); return Load(blob, 0, blob.Length); }
internal override void AppendEncodedChars(char[] data, int offset, int size, System.Text.Encoder encoder, bool flushEncoder) { int num = encoder.GetBytes(data, offset, size, this._data, base._size - base._free, flushEncoder); base._free -= num; }
/// /// <summary> /// SHA (1-256-384-512)位 Byte -> String /// </summary> /// <param name="toEn"></param> /// <param name="size"></param> /// <param name="toLower"></param> /// <param name="time"></param> /// <param name="encoding"></param> /// <returns>string / null </returns> public static string ByteShaToString(byte[] toEn, int size, bool toLower, int time, System.Text.Encoding encoding) { #region SHA (1-256-384-512)位 Byte -> String // 执行多次 for (var i = 1; i < time; i++) { toEn = encoding.GetBytes(ByteShaToString(toEn, size, false, i, encoding)); } // 判断输入正确 if (toEn.IsEmptyBytes()) return null; // 进行MD5计算 var bytebyte = ByteShaToByte(toEn, size); if (bytebyte.IsEmptyBytes()) return null; var bitstring = toLower ? System.BitConverter.ToString(bytebyte).Replace("-", "").ToLower() : System.BitConverter.ToString(bytebyte).Replace("-", ""); return bitstring.ToSafeValue(); #endregion }
/////////////////////////////////////////////////////////////////////////////////////////////////// // // EnDecryptHelper .Net加密解密算法辅助类 // By CraigTaylor LastModify At 2013.1.14 // http://msdn.microsoft.com/zh-cn/library/9eat8fht.aspx // /////////////////////////////////////////////////////////////////////////////////////////////////// // // 在.NET Framework中,可以使用System.Security.Cryptography命名空间中的类来加密。 // 它实现了几个对称和非对称算法。从.NET 3.5开始, // 一些新类以Cng作为前缀或后缀,表示Cryptography Next Generation, // 用于采用Windows NT 6.0或更高内核版本的操作系统(Vista、Win7、Win2008、Win8)。 // 这个API可以使用基于提供程序的模型,编写独立于算法的程序 // 没有Cng、Managed或CryptoServiceProvider后缀的类是抽象基类, // 例如MD5。Managed后缀表示这个算法用托管代码实现, // 其他类可能封装了内部的Windows API调用。 // CryptoServiceProvider后缀用于实现了抽象基类的类, // Cng后缀用于利用新Cryptography CNG API的类, // 它只能用于指定版本的操作系统。 // 关于性能方面,就同一种算法, // 有CryptoServiceProvider、Managed、Cng三种实现方式, // 我现在测试了散列中的方法,其中MD5是没有Managed实现的 // Cng算法的速度是最差的,而Csp居中水平, // Managed实现则速度非常快,另外, // 如果加大SHA算法的位数的话,当到384位时差别就不再明显, // 而且Csp算法所需时间成为了最少的方式, // 这个我认为是操作系统API调用所形成的优势 // /////////////////////////////////////////////////////////////////////////////////////////////////// /// #region 以字节形式读取并还原实例 ////-----------------------以字节形式读取并还原实例-------------------------// // // var fileInfo = new FileInfo(fileName); // // Creat Key && IV // var enckey = EnDecryptHelper.StringMd5ShaToString(false, string.Format("<{0}/>{1}</{2}>", _companyname, fileInfo.Name, _companyname), 16, false, 1, Encoding.UTF8); // var enciv = EnDecryptHelper.StringMd5ShaToString(false, string.Format("[{0}/]{1}[/{2}]", _companyname, fileInfo.Name, _companyname), 16, false, 1, Encoding.UTF8); // // File -> Origin // var filestring = File.ReadAllBytes(fileInfo.FullName); // if (!Directory.Exists(_lastDirPath + @"\SafeDir\")) // { // Directory.CreateDirectory(_lastDirPath + @"\SafeDir\"); // } // var orginsavepath = _lastDirPath + @"\SafeDir\" + fileInfo.Name + ".Ori"; // File.WriteAllBytes(orginsavepath, filestring); // // Origin -> Encrypt // var encstring = EnDecryptHelper.ByteAesToByte(false, filestring, enckey, enciv); // var encsavepath = _lastDirPath + @"\SafeDir\" + fileInfo.Name + ".Enc"; // File.WriteAllBytes(encsavepath, encstring); // // Encrypt -> Decrypt // var decresult = EnDecryptHelper.ByteAesToByte(true, File.ReadAllBytes(encsavepath), enckey, enciv); // var decsavepath = _lastDirPath + @"\SafeDir\" + fileInfo.Name + ".Dec"; // File.WriteAllBytes(decsavepath, decresult); // // SHA1 : Origin == Decrypt // var orginsha = EnDecryptHelper.FileMd5ShaToString(true, orginsavepath, 1); // var decsha = EnDecryptHelper.FileMd5ShaToString(true, decsavepath, 1); // var shasavepath = _lastDirPath + @"\SafeDir\" + fileInfo.Name + ".Sha"; // if (orginsha == decsha) // { // File.WriteAllText(shasavepath, decsha); // } // ////-----------------------以字节形式读取并还原实例-------------------------// #endregion /// #region 以文本形式读取并还原实例 ////-------------------以文本形式读取并还原实例------------------------// // // // File -> Origin // var filestring = File.ReadAllText(fileInfo.FullName,Encoding.Default); // if (!Directory.Exists(_lastDirPath + @"\SafeDir\")) // { // Directory.CreateDirectory(_lastDirPath + @"\SafeDir\"); // } // var orginsavepath = _lastDirPath + @"\SafeDir\" + fileInfo.Name + ".Ori"; // File.WriteAllText(orginsavepath, filestring); // // Origin -> Encrypt // var encstring = EnDecryptHelper.StringAesEncToByte(filestring, enckey, enciv); // var encsavepath = _lastDirPath + @"\SafeDir\" + fileInfo.Name+ ".Enc"; // File.WriteAllBytes(encsavepath, encstring); // // Encrypt -> Decrypt // var decresult = EnDecryptHelper.ByteAesDecToString(File.ReadAllBytes(encsavepath), enckey, enciv); // var decsavepath = _lastDirPath + @"\SafeDir\" + fileInfo.Name + ".Dec"; // File.WriteAllText(decsavepath, decresult); // // SHA1 : Origin == Decrypt // var orginsha = EnDecryptHelper.FileMd5ShaToString(true, orginsavepath, 1); // var decsha = EnDecryptHelper.FileMd5ShaToString(true, decsavepath, 1); // var shasavepath = _lastDirPath + @"\SafeDir\" + fileInfo.Name + ".Sha"; // if (orginsha == decsha ) // { // File.WriteAllText(shasavepath, decsha); // } // ////-------------------以文本形式读取并还原实例------------------------// #endregion /// /////////////////////////////////////////////////////////////////////////////////////////////////// // // 公共调用代码 // /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // // MD5、SHA 系列算法调用 // /////////////////////////////////////////////////////////////////////////////////////////////////// /// /// <summary> /// MD5 (16-32)位 / SHA (1-256-384-512)位 String -> String /// </summary> /// <param name="isSha"></param> /// <param name="toEn"></param> /// <param name="size"></param> /// <param name="toLower"></param> /// <param name="time"></param> /// <param name="encoding"></param> /// <returns>string / null</returns> public static string StringMd5ShaToString(bool isSha, string toEn, int size, bool toLower, int time, System.Text.Encoding encoding) { #region MD5 (16-32)位 / SHA (1-256-384-512)位 String -> String // 判断输入正确 if (toEn.IsNullOrEmptyOrSpace()) return null; // 得到Byte[] var stringbyte = encoding.GetBytes(toEn); if (stringbyte.IsEmptyBytes()) return null; // 得到Sting var stringstring = isSha == false ? ByteMd5ToString(stringbyte, size, toLower, time, encoding) : ByteShaToString(stringbyte, size, toLower, time, encoding); // 返回值 return stringstring.ToSafeValue(); #endregion }
/// /// <summary> /// MD5 (16-32)位 Byte -> String /// </summary> /// <param name="toEn"></param> /// <param name="size"></param> /// <param name="toLower"></param> /// <param name="time"></param> /// <param name="encoding"></param> /// <returns>string / null </returns> public static string ByteMd5ToString(byte[] toEn, int size, bool toLower, int time, System.Text.Encoding encoding) { #region MD5 (16-32)位 Byte -> String // 执行多次 for (var i = 1; i < time; i++) { toEn = encoding.GetBytes(ByteMd5ToString(toEn, size, false, i, encoding)); } // 判断输入正确 if (toEn.IsEmptyBytes()) return null; // 进行MD5计算 var bytebyte = ByteMd5ToByte(toEn); if (bytebyte.IsEmptyBytes()) return null; // 核对MD5结果 var result = string.Empty; // 16 位 / 32 位 switch (size) { case 16: { // 转换大小写,默认值大写 result = toLower ? System.BitConverter.ToString(bytebyte, 4, 8).Replace("-", "").ToLower() : System.BitConverter.ToString(bytebyte, 4, 8).Replace("-", ""); } break; case 32: { // 转换大小写,默认值大写 result = toLower ? System.BitConverter.ToString(bytebyte).Replace("-", "").ToLower() : System.BitConverter.ToString(bytebyte).Replace("-", ""); } break; } return result.ToSafeValue(); #endregion }
internal static byte[] StringToByteArray(string value, System.Text.Encoding encoding) { byte[] a = encoding.GetBytes(value); return a; }
private string file_get_contents(string url, System.Text.Encoding encode) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); WebResponse response = request.GetResponse(); using (MemoryStream ms = new MemoryStream()) { using (Stream stream = response.GetResponseStream()) { int readc; byte[] buffer = encode.GetBytes(url);// new byte[1024]; while ((readc = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, readc); } } return encode.GetString(ms.ToArray()); } }
/// <summary>Creates a stream that can read the specified text as encoded bytes.</summary> /// <param name='text'>Text to read.</param> /// <param name='encoding'>Encoding to convert text into bytes.</param> /// <returns>A new stream.</returns> public static Stream CreateStream(string text, System.Text.Encoding encoding) { CheckArgumentNotNull(text, "text"); CheckArgumentNotNull(encoding, "encoding"); return new MemoryStream(encoding.GetBytes(text)); }