C#常用字符串加解密方法封装
C#中常用的字符串加密、解密方法封装,包含只加密但不解密的方法。收藏起来备用。
//方法一
//须添加对System.Web的引用
//using System.Web.Security;
/// <summary>
/// SHA1加密字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>加密后的字符串</returns>
public string SHA1(string source)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1");
}
/// <summary>
/// MD5加密字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>加密后的字符串</returns>
public string MD5(string source)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");;
} //方法二(可逆加密解密):
//using System.Security.Cryptography;
public string Encode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer(), , (int)ms.Length);
}
public string Decode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(byEnc);
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst); //方法三(MD5不可逆):
//using System.Security.Cryptography;
//MD5不可逆加密
//32位加密
public string GetMD5_32(string s, string _input_charset)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
StringBuilder sb = new StringBuilder();
for (int i = ; i < t.Length; i++)
{
sb.Append(t[i].ToString("x").PadLeft(, ''));
}
return sb.ToString();
}
//16位加密
public static string GetMd5_16(string ConvertString)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), , );
t2 = t2.Replace("-", "");
return t2;
} //方法四(对称加密):
//using System.IO;
//using System.Security.Cryptography;
private SymmetricAlgorithm mobjCryptoService;
private string Key;
/// <summary>
/// 对称加密类的构造函数
/// </summary>
public SymmetricMethod()
{
mobjCryptoService = new RijndaelManaged();
Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
}
/// <summary>
/// 获得密钥
/// </summary>
/// <returns>密钥</returns>
private byte[] GetLegalKey()
{
string sTemp = Key;
mobjCryptoService.GenerateKey();
byte[] bytTemp = mobjCryptoService.Key;
int KeyLength = bytTemp.Length;
if (sTemp.Length > KeyLength)
sTemp = sTemp.Substring(, KeyLength);
else if (sTemp.Length < KeyLength)
sTemp = sTemp.PadRight(KeyLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary>
/// 获得初始向量IV
/// </summary>
/// <returns>初试向量IV</returns>
private byte[] GetLegalIV()
{
string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
mobjCryptoService.GenerateIV();
byte[] bytTemp = mobjCryptoService.IV;
int IVLength = bytTemp.Length;
if (sTemp.Length > IVLength)
sTemp = sTemp.Substring(, IVLength);
else if (sTemp.Length < IVLength)
sTemp = sTemp.PadRight(IVLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary>
/// 加密方法
/// </summary>
/// <param name="Source">待加密的串</param>
/// <returns>经过加密的串</returns>
public string Encrypto(string Source)
{
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
MemoryStream ms = new MemoryStream();
mobjCryptoService.Key = GetLegalKey();
mobjCryptoService.IV = GetLegalIV();
ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
cs.Write(bytIn, , bytIn.Length);
cs.FlushFinalBlock();
ms.Close();
byte[] bytOut = ms.ToArray();
return Convert.ToBase64String(bytOut);
}
/// <summary>
/// 解密方法
/// </summary>
/// <param name="Source">待解密的串</param>
/// <returns>经过解密的串</returns>
public string Decrypto(string Source)
{
byte[] bytIn = Convert.FromBase64String(Source);
MemoryStream ms = new MemoryStream(bytIn, , bytIn.Length);
mobjCryptoService.Key = GetLegalKey();
mobjCryptoService.IV = GetLegalIV();
ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
} //方法五:
//using System.IO;
//using System.Security.Cryptography;
//using System.Text;
//默认密钥向量
private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
/**//**//**//// <summary>
/// DES加密字符串 keleyi.com
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string EncryptDES(string encryptString, string encryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, , inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch
{
return encryptString;
}
}
/**//**//**//// <summary>
/// DES解密字符串 keleyi.com
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string DecryptDES(string decryptString, string decryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, , inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return decryptString;
}
} //方法六(文件加密):
//using System.IO;
//using System.Security.Cryptography;
//using System.Text;
//加密文件
private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
{
//Create the file streams to handle the input and output files.
FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength();
//Create variables to help with read and write.
byte[] bin = new byte[]; //This is intermediate storage for the encryption.
long rdlen = ; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, , );
encStream.Write(bin, , len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
}
//解密文件
private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)
{
//Create the file streams to handle the input and output files.
FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength();
//Create variables to help with read and write.
byte[] bin = new byte[]; //This is intermediate storage for the encryption.
long rdlen = ; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, , );
encStream.Write(bin, , len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
return sr.ReadToEnd();
}
http://www.cnblogs.com/sosoft/
C#常用字符串加解密方法封装的更多相关文章
- C# 常用字符串加密解密方法
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Sec ...
- ASP.NET(C#)常用数据加密和解密方法汇总
一. 数据加密的概念 1. 基本概念 2. 基本功能 3. 加密形式 二. 数据加密的项目应用和学习 1. 媒体加密:DRM 2. 文件加密:文本 ...
- C#开发中常用的加密解密方法
转载自:https://www.cnblogs.com/bj981/p/11203711.html C#开发中常用的加密解密方法 相信很多人在开发过程中经常会遇到需要对一些重要的信息进行加密处理,今天 ...
- android中使用jni对字符串加解密实现分析
android中使用jni对字符串加解密实现分析 近期项目有个需求.就是要对用户的敏感信息进行加密处理,比方用户的账户password,手机号等私密信息.在java中,就对字符串的加解密我们能够使用A ...
- PHP 加解密方法大全
最近看见一篇文章讲的是PHP的加解密方法,正好也自己学习下,顺便以后有用到的地方也好能快速用上,仅供自己学习和复习,好了不多BB,上代码. 基于这几个函数可逆转的加密为:base64_encode() ...
- C#中常用的字符串加密,解密方法封装,包含只加密,不解密的方法
//方法一//须添加对System.Web的引用//using System.Web.Security;/// <summary>/// SHA1加密字符串/// </summary ...
- iOS - (base64对字符串加解密)
今天公司让做支付系统,为了安全起见,需要对一些数据进行加密,然而我首想到的就是 base64 ,严格来说这不是一种加密方式,这只是将原有的一些字符串或者其它的一些文本进行一个转化而已,就是转化成数字, ...
- 华为OJ:字符串加解密
题目描述 1.对输入的字符串进行加解密,并输出. 2加密方法为: 当内容是英文字母时则用该英文字母的后一个字母替换,同时字母变换大小写,如字母a时则替换为B:字母Z时则替换为a: 当内容是数字时则把该 ...
- Java Des加解密方法(c#加密Java解密)
最近我们用Java把一个用.net编写的老系统重新做了翻版,但是登录还是用.net的登录.这样就会遇到一个比较棘手的问题,我们登录用的cookie信息都是.net用des加密的,但我们不得不用Java ...
随机推荐
- 常用的HTML5、CSS3新特性能力检测写法
伴随着今年10月底HTML5标准版的发布,未来使用H5的场景会越来越多,这是令web开发者欢欣鼓舞的事情.然而有一个现实我们不得不看清,那就是IE系列浏览器还占有一大部分市场份额,以IE8.9为主,w ...
- Linux tr命令
介绍 tr命令可以对来自标准输入的字符进行替换.压缩和删除.tr只能接收来自标准的输入流,不能接收参数. 语法 tr [OPTION]... SET1 [SET2] 注意:SET2是可选项 OPTIO ...
- IOS Animation-CABasicAnimation、CAKeyframeAnimation详解&区别&联系
1.先看看网上流传的他们的继承图: 从上面可以看出CABasicAnimation与CAKeyframeAnimation都继承于CAPropertyAnimation.而CAPropertyAnim ...
- java.util.Properties
1 Properties文件中分隔符及空格的处理 因为 Properties 继承于 Hashtable,所以可对 Properties 对象应用 put 和 putAll 方法.但强烈反对使用这两个 ...
- Redis教程(十二):服务器管理命令总结
转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/140.html 一.概述: Redis在设计之初就被定义为长时间不间断运行 ...
- Java程序员的日常——存储过程知识普及
存储过程是保存可以接受或返回用户提供参数的SQL语句集合.在日常的使用中,经常会遇到复杂的业务逻辑和对数据库的操作,使用存储过程可以进行封装.可以在数据库中定义子程序,然后把子程序存储在数据库服务器, ...
- 关于js中的同步和异步
最近看到前端面试问到js中的同步和异步,这个问题该怎么回答? 梳理一下,js对于异步的处理,很多人的第一反应是ajax,这只能说是对了一半. 1.个人觉得,js中,最基础的异步是setTimeout和 ...
- hadoop本地库与系统版本不一致引起的错误解决方法
hadoop本地库与系统版本不一致引起的错误解决方法 部署hadoop的集群环境为 操作系统 centos 5.8 hadoop版本为cloudera hadoop-0.20.2-cdh3u3 集 ...
- 转【】浅谈sql中的in与not in,exists与not exists的区别_
浅谈sql中的in与not in,exists与not exists的区别 1.in和exists in是把外表和内表作hash连接,而exists是对外表作loop循环,每次loop循环再对内表 ...
- KnockoutJS 3.X API 第三章 计算监控属性(1) 使用计算监控属性
计算监控属性(Computed Observables) 如果你有一个监控属性firstName,和另一个lastName,你要显示的全名?可以使用计算监控属性来实现-它依赖于一个或多个其他监控属性, ...