byte与base64string的相互转化以及加密算法
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Globalization;
using System.Xml.Linq;
using System.Collections.Generic;
namespace EncriptSample
{
/// <summary>
/// 加密、解密
/// </summary>
class Encrypter
{
//DES默认密钥向量
private static byte[] DES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
//AES默认密钥向量
public static readonly byte[] AES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
#region MD5
/// <summary>
/// MD5加密为32字符长度的16进制字符串
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string EncryptByMD5(string input)
{
MD5 md5Hasher = MD5.Create();
byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder sBuilder = new StringBuilder();
//将每个字节转为16进制
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
#endregion
#region SHA1
/// <summary>
/// SHA1加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string EncryptBySHA1(string input)
{
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] bytes = Encoding.Unicode.GetBytes(input);
byte[] result = sha.ComputeHash(bytes);
return BitConverter.ToString(result);
}
#endregion
#region DES
/// <summary>
/// 加密方法
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string EncryptByDES(string input, string key)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input); //Encoding.UTF8.GetBytes(input);
byte[] keyBytes = ASCIIEncoding.UTF8.GetBytes(key);
byte[] encryptBytes = EncryptByDES(inputBytes, keyBytes, keyBytes);
//string result = Encoding.UTF8.GetString(encryptBytes); //无法解码,其加密结果中文出现乱码:d\"�e����(��uπ�W��-��,_�\nJn7
//原因:如果明文为中文,UTF8编码两个字节标识一个中文字符,但是加密后,两个字节密文,不一定还是中文字符。
using (DES des = new DESCryptoServiceProvider())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(cs))
{
writer.Write(inputBytes);
}
}
}
}
string result = Convert.ToBase64String(encryptBytes);
return result;
}
/// <summary>
/// DES加密
/// </summary>
/// <param name="inputBytes">输入byte数组</param>
/// <param name="key">密钥,只能是英文字母或数字</param>
/// <param name="IV">偏移向量</param>
/// <returns></returns>
public static byte[] EncryptByDES(byte[] inputBytes, byte[] key, byte[] IV)
{
DES des = new DESCryptoServiceProvider();
//建立加密对象的密钥和偏移量
des.Key = key;
des.IV = IV;
string result = string.Empty;
//1、如果通过CryptoStreamMode.Write方式进行加密,然后CryptoStreamMode.Read方式进行解密,解密成功。
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputBytes, 0, inputBytes.Length);
}
return ms.ToArray();
}
//2、如果通过CryptoStreamMode.Write方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,可以得到正确结果
//3、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Read方式进行解密,无法解密,Error:要解密的数据的长度无效。
//4、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,无法解密,Error:要解密的数据的长度无效。
//using (MemoryStream ms = new MemoryStream(inputBytes))
//{
// using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Read))
// {
// using (StreamReader reader = new StreamReader(cs))
// {
// result = reader.ReadToEnd();
// return Encoding.UTF8.GetBytes(result);
// }
// }
//}
}
/// <summary>
/// 解密
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string DecryptByDES(string input, string key)
{
//UTF8无法解密,Error: 要解密的数据的长度无效。
//byte[] inputBytes = Encoding.UTF8.GetBytes(input);//UTF8乱码,见加密算法
byte[] inputBytes = Convert.FromBase64String(input);
byte[] keyBytes = ASCIIEncoding.UTF8.GetBytes(key);
byte[] resultBytes = DecryptByDES(inputBytes, keyBytes, keyBytes);
string result = Encoding.UTF8.GetString(resultBytes);
return result;
}
/// <summary>
/// 解密方法
/// </summary>
/// <param name="inputBytes"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static byte[] DecryptByDES(byte[] inputBytes, byte[] key, byte[] iv)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//建立加密对象的密钥和偏移量,此值重要,不能修改
des.Key = key;
des.IV = iv;
//通过write方式解密
//using (MemoryStream ms = new MemoryStream())
//{
// using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
// {
// cs.Write(inputBytes, 0, inputBytes.Length);
// }
// return ms.ToArray();
//}
//通过read方式解密
using (MemoryStream ms = new MemoryStream(inputBytes))
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
string result = reader.ReadToEnd();
return Encoding.UTF8.GetBytes(result);
}
}
}
//错误写法,注意哪个是输出流的位置,如果范围ms,与原文不一致。
//using (MemoryStream ms = new MemoryStream(inputBytes))
//{
// using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
// {
// cs.Read(inputBytes, 0, inputBytes.Length);
// }
// return ms.ToArray();
//}
}
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="input"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string EncryptString(string input, string sKey)
{
byte[] data = Encoding.UTF8.GetBytes(input);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = des.CreateEncryptor();
byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return BitConverter.ToString(result);
}
}
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="input"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string DecryptString(string input, string sKey)
{
string[] sInput = input.Split("-".ToCharArray());
byte[] data = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = des.CreateDecryptor();
byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return Encoding.UTF8.GetString(result);
}
}
#endregion
#region AES
/// <summary>
/// AES加密算法
/// </summary>
/// <param name="input">明文字符串</param>
/// <param name="key">密钥</param>
/// <returns>字符串</returns>
public static string EncryptByAES(string input, string key)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 32));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = keyBytes;
aesAlg.IV = AES_IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(input);
}
byte[] bytes = msEncrypt.ToArray();
//return Convert.ToBase64String(bytes);//此方法不可用
return BitConverter.ToString(bytes);
}
}
}
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="input">密文字节数组</param>
/// <param name="key">密钥</param>
/// <returns>返回解密后的字符串</returns>
public static string DecryptByAES(string input, string key)
{
//byte[] inputBytes = Convert.FromBase64String(input); //Encoding.UTF8.GetBytes(input);
string[] sInput = input.Split("-".ToCharArray());
byte[] inputBytes = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 32));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = keyBytes;
aesAlg.IV = AES_IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream(inputBytes))
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srEncrypt = new StreamReader(csEncrypt))
{
return srEncrypt.ReadToEnd();
}
}
}
}
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="inputdata">输入的数据</param>
/// <param name="iv">向量128位</param>
/// <param name="strKey">加密密钥</param>
/// <returns></returns>
public static byte[] EncryptByAES(byte[] inputdata, byte[] key, byte[] iv)
{
////分组加密算法
//Aes aes = new AesCryptoServiceProvider();
////设置密钥及密钥向量
//aes.Key = key;
//aes.IV = iv;
//using (MemoryStream ms = new MemoryStream())
//{
// using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
// {
// using (StreamWriter writer = new StreamWriter(cs))
// {
// writer.Write(inputdata);
// }
// return ms.ToArray();
// }
//}
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(inputdata);
}
byte[] encrypted = msEncrypt.ToArray();
return encrypted;
}
}
}
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="inputdata">输入的数据</param>
/// <param name="key">key</param>
/// <param name="iv">向量128</param>
/// <returns></returns>
public static byte[] DecryptByAES(byte[] inputBytes, byte[] key, byte[] iv)
{
Aes aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
byte[] decryptBytes;
using (MemoryStream ms = new MemoryStream(inputBytes))
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
string result = reader.ReadToEnd();
decryptBytes = Encoding.UTF8.GetBytes(result);
}
}
}
return decryptBytes;
}
#endregion
#region DSA
#endregion
#region RSA
/// <summary>
/// RSA加密
/// </summary>
/// <param name="plaintext">明文</param>
/// <param name="publicKey">公钥</param>
/// <returns>密文字符串</returns>
public static string EncryptByRSA(string plaintext, string publicKey)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(publicKey);
byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false);
return Convert.ToBase64String(encryptedData);
}
}
/// <summary>
/// RSA解密
/// </summary>
/// <param name="ciphertext">密文</param>
/// <param name="privateKey">私钥</param>
/// <returns>明文字符串</returns>
public static string DecryptByRSA(string ciphertext, string privateKey)
{
UnicodeEncoding byteConverter = new UnicodeEncoding();
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(privateKey);
byte[] encryptedData = Convert.FromBase64String(ciphertext);
byte[] decryptedData = RSA.Decrypt(encryptedData, false);
return byteConverter.GetString(decryptedData);
}
}
//public static string signByRSA(string plaintext, string privateKey)
//{
// UnicodeEncoding ByteConverter = new UnicodeEncoding();
// byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
// using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
// {
// RSA.FromXmlString(privateKey);
// byte[] encryptedData = RSA.SignData(dataToEncrypt,);
// return Convert.ToBase64String(encryptedData);
// }
//}
/// <summary>
/// 数字签名
/// </summary>
/// <param name="plaintext">原文</param>
/// <param name="privateKey">私钥</param>
/// <returns>签名</returns>
public static string HashAndSignString(string plaintext, string privateKey)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider())
{
RSAalg.FromXmlString(privateKey);
//使用SHA1进行摘要算法,生成签名
byte[] encryptedData = RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider());
return Convert.ToBase64String(encryptedData);
}
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name="plaintext">原文</param>
/// <param name="SignedData">签名</param>
/// <param name="publicKey">公钥</param>
/// <returns></returns>
public static bool VerifySigned(string plaintext, string SignedData, string publicKey)
{
using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider())
{
RSAalg.FromXmlString(publicKey);
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToVerifyBytes = ByteConverter.GetBytes(plaintext);
byte[] signedDataBytes = Convert.FromBase64String(SignedData);
return RSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(), signedDataBytes);
}
}
/// <summary>
/// 获取Key
/// 键为公钥,值为私钥
/// </summary>
/// <returns></returns>
public static KeyValuePair<string, string> CreateRSAKey()
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
string privateKey = RSA.ToXmlString(true);
string publicKey = RSA.ToXmlString(false);
return new KeyValuePair<string, string>(publicKey, privateKey);
}
#endregion
#region other
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static byte[] GetBytes(string input)
{
string[] sInput = input.Split("-".ToCharArray());
byte[] inputBytes = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
return inputBytes;
}
#endregion
}
}
MD5算法
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Globalization;
using System.Xml.Linq;
using System.Collections.Generic;
namespace EncriptSample
{
/// <summary>
/// 加密、解密
/// </summary>
class Encrypter
{
//DES默认密钥向量
private static byte[] DES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
//AES默认密钥向量
public static readonly byte[] AES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
#region MD5
/// <summary>
/// MD5加密为32字符长度的16进制字符串
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string EncryptByMD5(string input)
{
MD5 md5Hasher = MD5.Create();
byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder sBuilder = new StringBuilder();
//将每个字节转为16进制
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
#endregion
#region SHA1
/// <summary>
/// SHA1加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string EncryptBySHA1(string input)
{
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] bytes = Encoding.Unicode.GetBytes(input);
byte[] result = sha.ComputeHash(bytes);
return BitConverter.ToString(result);
}
#endregion
#region DES
/// <summary>
/// 加密方法
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string EncryptByDES(string input, string key)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input); //Encoding.UTF8.GetBytes(input);
byte[] keyBytes = ASCIIEncoding.UTF8.GetBytes(key);
byte[] encryptBytes = EncryptByDES(inputBytes, keyBytes, keyBytes);
//string result = Encoding.UTF8.GetString(encryptBytes); //无法解码,其加密结果中文出现乱码:d\"�e����(��uπ�W��-��,_�\nJn7
//原因:如果明文为中文,UTF8编码两个字节标识一个中文字符,但是加密后,两个字节密文,不一定还是中文字符。
using (DES des = new DESCryptoServiceProvider())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(cs))
{
writer.Write(inputBytes);
}
}
}
}
string result = Convert.ToBase64String(encryptBytes);
return result;
}
/// <summary>
/// DES加密
/// </summary>
/// <param name="inputBytes">输入byte数组</param>
/// <param name="key">密钥,只能是英文字母或数字</param>
/// <param name="IV">偏移向量</param>
/// <returns></returns>
public static byte[] EncryptByDES(byte[] inputBytes, byte[] key, byte[] IV)
{
DES des = new DESCryptoServiceProvider();
//建立加密对象的密钥和偏移量
des.Key = key;
des.IV = IV;
string result = string.Empty;
//1、如果通过CryptoStreamMode.Write方式进行加密,然后CryptoStreamMode.Read方式进行解密,解密成功。
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputBytes, 0, inputBytes.Length);
}
return ms.ToArray();
}
//2、如果通过CryptoStreamMode.Write方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,可以得到正确结果
//3、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Read方式进行解密,无法解密,Error:要解密的数据的长度无效。
//4、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,无法解密,Error:要解密的数据的长度无效。
//using (MemoryStream ms = new MemoryStream(inputBytes))
//{
// using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Read))
// {
// using (StreamReader reader = new StreamReader(cs))
// {
// result = reader.ReadToEnd();
// return Encoding.UTF8.GetBytes(result);
// }
// }
//}
}
/// <summary>
/// 解密
/// </summary>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string DecryptByDES(string input, string key)
{
//UTF8无法解密,Error: 要解密的数据的长度无效。
//byte[] inputBytes = Encoding.UTF8.GetBytes(input);//UTF8乱码,见加密算法
byte[] inputBytes = Convert.FromBase64String(input);
byte[] keyBytes = ASCIIEncoding.UTF8.GetBytes(key);
byte[] resultBytes = DecryptByDES(inputBytes, keyBytes, keyBytes);
string result = Encoding.UTF8.GetString(resultBytes);
return result;
}
/// <summary>
/// 解密方法
/// </summary>
/// <param name="inputBytes"></param>
/// <param name="key"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static byte[] DecryptByDES(byte[] inputBytes, byte[] key, byte[] iv)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//建立加密对象的密钥和偏移量,此值重要,不能修改
des.Key = key;
des.IV = iv;
//通过write方式解密
//using (MemoryStream ms = new MemoryStream())
//{
// using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
// {
// cs.Write(inputBytes, 0, inputBytes.Length);
// }
// return ms.ToArray();
//}
//通过read方式解密
using (MemoryStream ms = new MemoryStream(inputBytes))
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
string result = reader.ReadToEnd();
return Encoding.UTF8.GetBytes(result);
}
}
}
//错误写法,注意哪个是输出流的位置,如果范围ms,与原文不一致。
//using (MemoryStream ms = new MemoryStream(inputBytes))
//{
// using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
// {
// cs.Read(inputBytes, 0, inputBytes.Length);
// }
// return ms.ToArray();
//}
}
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="input"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string EncryptString(string input, string sKey)
{
byte[] data = Encoding.UTF8.GetBytes(input);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = des.CreateEncryptor();
byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return BitConverter.ToString(result);
}
}
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="input"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string DecryptString(string input, string sKey)
{
string[] sInput = input.Split("-".ToCharArray());
byte[] data = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = des.CreateDecryptor();
byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return Encoding.UTF8.GetString(result);
}
}
#endregion
#region AES
/// <summary>
/// AES加密算法
/// </summary>
/// <param name="input">明文字符串</param>
/// <param name="key">密钥</param>
/// <returns>字符串</returns>
public static string EncryptByAES(string input, string key)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 32));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = keyBytes;
aesAlg.IV = AES_IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(input);
}
byte[] bytes = msEncrypt.ToArray();
//return Convert.ToBase64String(bytes);//此方法不可用
return BitConverter.ToString(bytes);
}
}
}
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="input">密文字节数组</param>
/// <param name="key">密钥</param>
/// <returns>返回解密后的字符串</returns>
public static string DecryptByAES(string input, string key)
{
//byte[] inputBytes = Convert.FromBase64String(input); //Encoding.UTF8.GetBytes(input);
string[] sInput = input.Split("-".ToCharArray());
byte[] inputBytes = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 32));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = keyBytes;
aesAlg.IV = AES_IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream(inputBytes))
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srEncrypt = new StreamReader(csEncrypt))
{
return srEncrypt.ReadToEnd();
}
}
}
}
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="inputdata">输入的数据</param>
/// <param name="iv">向量128位</param>
/// <param name="strKey">加密密钥</param>
/// <returns></returns>
public static byte[] EncryptByAES(byte[] inputdata, byte[] key, byte[] iv)
{
////分组加密算法
//Aes aes = new AesCryptoServiceProvider();
////设置密钥及密钥向量
//aes.Key = key;
//aes.IV = iv;
//using (MemoryStream ms = new MemoryStream())
//{
// using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
// {
// using (StreamWriter writer = new StreamWriter(cs))
// {
// writer.Write(inputdata);
// }
// return ms.ToArray();
// }
//}
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(inputdata);
}
byte[] encrypted = msEncrypt.ToArray();
return encrypted;
}
}
}
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="inputdata">输入的数据</param>
/// <param name="key">key</param>
/// <param name="iv">向量128</param>
/// <returns></returns>
public static byte[] DecryptByAES(byte[] inputBytes, byte[] key, byte[] iv)
{
Aes aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
byte[] decryptBytes;
using (MemoryStream ms = new MemoryStream(inputBytes))
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
string result = reader.ReadToEnd();
decryptBytes = Encoding.UTF8.GetBytes(result);
}
}
}
return decryptBytes;
}
#endregion
#region DSA
#endregion
#region RSA
/// <summary>
/// RSA加密
/// </summary>
/// <param name="plaintext">明文</param>
/// <param name="publicKey">公钥</param>
/// <returns>密文字符串</returns>
public static string EncryptByRSA(string plaintext, string publicKey)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(publicKey);
byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false);
return Convert.ToBase64String(encryptedData);
}
}
/// <summary>
/// RSA解密
/// </summary>
/// <param name="ciphertext">密文</param>
/// <param name="privateKey">私钥</param>
/// <returns>明文字符串</returns>
public static string DecryptByRSA(string ciphertext, string privateKey)
{
UnicodeEncoding byteConverter = new UnicodeEncoding();
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(privateKey);
byte[] encryptedData = Convert.FromBase64String(ciphertext);
byte[] decryptedData = RSA.Decrypt(encryptedData, false);
return byteConverter.GetString(decryptedData);
}
}
//public static string signByRSA(string plaintext, string privateKey)
//{
// UnicodeEncoding ByteConverter = new UnicodeEncoding();
// byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
// using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
// {
// RSA.FromXmlString(privateKey);
// byte[] encryptedData = RSA.SignData(dataToEncrypt,);
// return Convert.ToBase64String(encryptedData);
// }
//}
/// <summary>
/// 数字签名
/// </summary>
/// <param name="plaintext">原文</param>
/// <param name="privateKey">私钥</param>
/// <returns>签名</returns>
public static string HashAndSignString(string plaintext, string privateKey)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider())
{
RSAalg.FromXmlString(privateKey);
//使用SHA1进行摘要算法,生成签名
byte[] encryptedData = RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider());
return Convert.ToBase64String(encryptedData);
}
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name="plaintext">原文</param>
/// <param name="SignedData">签名</param>
/// <param name="publicKey">公钥</param>
/// <returns></returns>
public static bool VerifySigned(string plaintext, string SignedData, string publicKey)
{
using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider())
{
RSAalg.FromXmlString(publicKey);
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToVerifyBytes = ByteConverter.GetBytes(plaintext);
byte[] signedDataBytes = Convert.FromBase64String(SignedData);
return RSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(), signedDataBytes);
}
}
/// <summary>
/// 获取Key
/// 键为公钥,值为私钥
/// </summary>
/// <returns></returns>
public static KeyValuePair<string, string> CreateRSAKey()
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
string privateKey = RSA.ToXmlString(true);
string publicKey = RSA.ToXmlString(false);
return new KeyValuePair<string, string>(publicKey, privateKey);
}
#endregion
#region other
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static byte[] GetBytes(string input)
{
string[] sInput = input.Split("-".ToCharArray());
byte[] inputBytes = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
return inputBytes;
}
#endregion
}
}
byte与base64string的相互转化以及加密算法的更多相关文章
- [转]C#中图片.BYTE[]和base64string的转换
本文转自:http://blog.csdn.net/thebesttome/article/details/6870155 在C#中 图片到byte[]再到base64string的转换: Bitma ...
- C#中图片.BYTE[]和base64string的转换
在C#中 图片到byte[]再到base64string的转换: Bitmap bmp = new Bitmap(filepath); MemoryStream ms = ...
- C++: byte 和 int 的相互转化
原文链接:http://blog.csdn.net/puttytree/article/details/7825709 NumberUtil.h // // NumberUtil.h // MinaC ...
- C# byte[]和文件FileStream相互转化
, pReadByte.Length); } catch { return false; ...
- C# string byte[] Base64 常用互相转换
参考: http://www.cnblogs.com/zxx193/p/3605238.html?utm_source=tuicool http://www.cnblogs.com/freeliver ...
- 廖雪峰Java10加密与安全-4加密算法-5非对称加密算法
1.非对称加密 非对称加密就是加密和解密使用的不是相同的密钥 方法1: * 加密:用自己的私钥加密,然后发送给对方:encrypt(privateKeyA, message)->s * 解密:对 ...
- C#与unity中base64string和图片互转
C#: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst ...
- 提高你的C#程序编码质量
摘自陆敏技之<编写高质量代码:改善C#程序的157个建议>,编写C#程序代码时应考虑代码效率.安全和美观,可参考下述建议.想成为一名合格的搬砖工,牢记吧!! 基本语言要素 1.正确操作字符 ...
- 深入理解String的关键点和方法
String是Java开发中最最常见的,本篇博客针对String的原理和常用的方法,以及String的在开发中常见问题做一个整体性的概括整理.因为之前对String的特性做过一些分析,所以不在详细描述 ...
随机推荐
- 【转载】sizeof()、strlen()、length()、size()详解和区别
c/c++中获取字符串长度.有以下函数:size().sizeof() .strlen().str.length();一.数组或字符串的长度:sizeof().strlen()1.sizeof():返 ...
- python学习第六天--匿名函数、过滤、映射
匿名函数 lambda表达式 过滤器 filter(判断函数,可迭代对象) 会根据提供的函数对指定序列做过滤 映射 map(判断函数,可迭代对象) 会根据提供的函数对指定序列做映射
- Leetcode Lect2 Java 中的 Interface
什么是 Interface Java接口(Interface)是一系列方法的声明,是一些方法特征的集合,一个接口只有方法的特征没有方法的实现,因此这些方法可以在不同的地方被不同的类实现,而这些实现可以 ...
- ELK + Filebeat日志分析系统安装
之前搭建过elk,用于分析日志,无奈服务器资源不足,开了多个Logstash之后发现占用内存过高,于是现在改为Filebeat做日志收集,记录一下搭建过程和遇到问题的解决方案. 第一步 , 安装jdk ...
- YARN的伪分布式安装
前提:安装完HDFS以后 1.修改mapred-site.xml 这个文件初始时是没有的,有的是模板文件,mapred-site.xml.template 所以需要拷贝一份,并重命名为mapred-s ...
- 20180315-Python面向对象编程设计和开发
1.在子类中调用父类的方法 在子类派生出的新方法中,往往需要重用父类的方法,我们有两种实现方式: 方式一:父类名.父类方法() Animal.__init__(self,name) 方式二:super ...
- 2019-9-8-WPF-渲染原理
title author date CreateTime categories WPF 渲染原理 lindexi 2019-9-8 10:40:0 +0800 2018-7-15 16:2:47 +0 ...
- linux设置python虚拟环境的环境变量
针对 linux系统中 python虚拟环境 设置环境变量 2种方法: 1.在建好的虚拟环境的 venv/bin/active 文件中,写入需要的环境变量,再进入虚拟环境: 如 配置文件路径 JERR ...
- URAL - 1486 二维字符串HASH
题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1486 题意:给定一个n*m的字符矩阵,问你是否存在两个不重合(可以有交集)的正方形矩阵完 ...
- CentOS 6.5之SSH 免密码登录
0.说明 这里为了方便说明问题,假设有A和B两台安装了centos6.5的主机.目标是实现A.B两台主机分别能够通过ssh免密码登录到对方主机.不同主机的配置过程一样,这里介绍A主机的配置过程. 事先 ...