当前位置:网站首页>Data stream encryption and decryption of C
Data stream encryption and decryption of C
2022-04-23 17:56:00 【It technology ape】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
using System.Globalization;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
/// <summary>
/// Password encryption and decryption operation related classes
/// </summary>
public static class PassWordHelper
{
#region MD5 encryption
/// <summary>
/// MD5 encryption
/// </summary>
public static string Md532(this string source)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
MD5 md5 = MD5.Create();
return HashAlgorithmBase(md5, source, encoding);
}
/// <summary>
/// Add salt MD5 encryption
/// </summary>
public static string Md532Salt(this string source, string salt)
{
return String.IsNullOrEmpty(salt) ? source.Md532() : (source + "『" + salt + "』").Md532();
}
#endregion
#region SHA encryption
/// <summary>
/// SHA1 encryption
/// </summary>
public static string Sha1(this string source)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
SHA1 sha1 = new SHA1CryptoServiceProvider();
return HashAlgorithmBase(sha1, source, encoding);
}
/// <summary>
/// SHA256 encryption
/// </summary>
public static string Sha256(this string source)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
SHA256 sha256 = new SHA256Managed();
return HashAlgorithmBase(sha256, source, encoding);
}
/// <summary>
/// SHA512 encryption
/// </summary>
public static string Sha512(this string source)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
SHA512 sha512 = new SHA512Managed();
return HashAlgorithmBase(sha512, source, encoding);
}
#endregion
#region HMAC encryption
/// <summary>
/// HmacSha1 encryption
/// </summary>
public static string HmacSha1(this string source, string keyVal)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
byte[] keyStr = encoding.GetBytes(keyVal);
HMACSHA1 hmacSha1 = new HMACSHA1(keyStr);
return HashAlgorithmBase(hmacSha1, source, encoding);
}
/// <summary>
/// HmacSha256 encryption
/// </summary>
public static string HmacSha256(this string source, string keyVal)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
byte[] keyStr = encoding.GetBytes(keyVal);
HMACSHA256 hmacSha256 = new HMACSHA256(keyStr);
return HashAlgorithmBase(hmacSha256, source, encoding);
}
/// <summary>
/// HmacSha384 encryption
/// </summary>
public static string HmacSha384(this string source, string keyVal)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
byte[] keyStr = encoding.GetBytes(keyVal);
HMACSHA384 hmacSha384 = new HMACSHA384(keyStr);
return HashAlgorithmBase(hmacSha384, source, encoding);
}
/// <summary>
/// HmacSha512 encryption
/// </summary>
public static string HmacSha512(this string source, string keyVal)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
byte[] keyStr = encoding.GetBytes(keyVal);
HMACSHA512 hmacSha512 = new HMACSHA512(keyStr);
return HashAlgorithmBase(hmacSha512, source, encoding);
}
/// <summary>
/// HmacMd5 encryption
/// </summary>
public static string HmacMd5(this string source, string keyVal)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
byte[] keyStr = encoding.GetBytes(keyVal);
HMACMD5 hmacMd5 = new HMACMD5(keyStr);
return HashAlgorithmBase(hmacMd5, source, encoding);
}
/// <summary>
/// HmacRipeMd160 encryption
/// </summary>
public static string HmacRipeMd160(this string source, string keyVal)
{
if (String.IsNullOrEmpty(source)) return null;
var encoding = Encoding.UTF8;
byte[] keyStr = encoding.GetBytes(keyVal);
HMACRIPEMD160 hmacRipeMd160 = new HMACRIPEMD160(keyStr);
return HashAlgorithmBase(hmacRipeMd160, source, encoding);
}
#endregion
#region AES Encryption and decryption
/// <summary>
/// AES encryption
/// </summary>
/// <param name="source"> Fields to be encrypted </param>
/// <param name="keyVal"> Key value </param>
/// <param name="ivVal"> Encrypt auxiliary vectors </param>
/// <returns></returns>
public static string AesStr(this string source, string keyVal, string ivVal)
{
var encoding = Encoding.UTF8;
byte[] btKey = keyVal.FormatByte(encoding);
byte[] btIv = ivVal.FormatByte(encoding);
byte[] byteArray = encoding.GetBytes(source);
string encrypt;
Rijndael aes = Rijndael.Create();
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(btKey, btIv), CryptoStreamMode.Write))
{
cStream.Write(byteArray, 0, byteArray.Length);
cStream.FlushFinalBlock();
encrypt = Convert.ToBase64String(mStream.ToArray());
}
}
aes.Clear();
return encrypt;
}
/// <summary>
/// AES Decrypt
/// </summary>
/// <param name="source"> Fields to be encrypted </param>
/// <param name="keyVal"> Key value </param>
/// <param name="ivVal"> Encrypt auxiliary vectors </param>
/// <returns></returns>
public static string UnAesStr(this string source, string keyVal, string ivVal)
{
var encoding = Encoding.UTF8;
byte[] btKey = keyVal.FormatByte(encoding);
byte[] btIv = ivVal.FormatByte(encoding);
byte[] byteArray = Convert.FromBase64String(source);
string decrypt;
Rijndael aes = Rijndael.Create();
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(btKey, btIv), CryptoStreamMode.Write))
{
cStream.Write(byteArray, 0, byteArray.Length);
cStream.FlushFinalBlock();
decrypt = encoding.GetString(mStream.ToArray());
}
}
aes.Clear();
return decrypt;
}
/// <summary>
/// AES Byte type encryption
/// </summary>
/// <param name="data"> Plaintext to be encrypted </param>
/// <param name="keyVal"> Key value </param>
/// <param name="ivVal"> Encrypt auxiliary vectors </param>
/// <returns></returns>
public static byte[] AesByte(this byte[] data, string keyVal, string ivVal)
{
byte[] bKey = new byte[32];
Array.Copy(Encoding.UTF8.GetBytes(keyVal.PadRight(bKey.Length)), bKey, bKey.Length);
byte[] bVector = new byte[16];
Array.Copy(Encoding.UTF8.GetBytes(ivVal.PadRight(bVector.Length)), bVector, bVector.Length);
byte[] cryptograph;
Rijndael aes = Rijndael.Create();
try
{
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write))
{
cStream.Write(data, 0, data.Length);
cStream.FlushFinalBlock();
cryptograph = mStream.ToArray();
}
}
}
catch
{
cryptograph = null;
}
return cryptograph;
}
/// <summary>
/// AES Byte type Decrypt
/// </summary>
/// <param name="data"> Plaintext to be decrypted </param>
/// <param name="keyVal"> Key value </param>
/// <param name="ivVal"> Encrypt auxiliary vectors </param>
/// <returns></returns>
public static byte[] UnAesByte(this byte[] data, string keyVal, string ivVal)
{
byte[] bKey = new byte[32];
Array.Copy(Encoding.UTF8.GetBytes(keyVal.PadRight(bKey.Length)), bKey, bKey.Length);
byte[] bVector = new byte[16];
Array.Copy(Encoding.UTF8.GetBytes(ivVal.PadRight(bVector.Length)), bVector, bVector.Length);
byte[] original;
Rijndael aes = Rijndael.Create();
try
{
using (MemoryStream mStream = new MemoryStream(data))
{
using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read))
{
using (MemoryStream originalMemory = new MemoryStream())
{
byte[] buffer = new byte[1024];
int readBytes;
while ((readBytes = cStream.Read(buffer, 0, buffer.Length)) > 0)
{
originalMemory.Write(buffer, 0, readBytes);
}
original = originalMemory.ToArray();
}
}
}
}
catch
{
original = null;
}
return original;
}
#endregion
#region RSA Encryption and decryption
// Key pair , Please use it with the key generation tool 『 http://download.csdn.net/detail/downiis6/9464639 』
private const string PublicRsaKey = @"pubKey";
private const string PrivateRsaKey = @"priKey";
/// <summary>
/// RSA encryption
/// </summary>
public static string Rsa(this string source)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(PublicRsaKey);
var cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(source), true);
return Convert.ToBase64String(cipherbytes);
}
/// <summary>
/// RSA Decrypt
/// </summary>
public static string UnRsa(this string source)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(PrivateRsaKey);
var cipherbytes = rsa.Decrypt(Convert.FromBase64String(source), true);
return Encoding.UTF8.GetString(cipherbytes);
}
#endregion
#region DES Encryption and decryption
/// <summary>
/// DES encryption
/// </summary>
public static string Des(this string source, string keyVal, string ivVal)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(source);
var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
var desencrypt = des.CreateEncryptor();
byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return BitConverter.ToString(result);
}
catch { return " Conversion error !"; }
}
/// <summary>
/// DES Decrypt
/// </summary>
public static string UnDes(this string source, string keyVal, string ivVal)
{
try
{
string[] sInput = source.Split("-".ToCharArray());
byte[] data = new byte[sInput.Length];
for (int i = 0; i < sInput.Length; i++)
{
data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
}
var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
var desencrypt = des.CreateDecryptor();
byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return Encoding.UTF8.GetString(result);
}
catch { return " Decryption error !"; }
}
#endregion
#region TripleDES Encryption and decryption
/// <summary>
/// DES3 encryption
/// </summary>
public static string Des3(this string source, string keyVal)
{
try
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
{
Key = keyVal.FormatByte(Encoding.UTF8),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
using (MemoryStream ms = new MemoryStream())
{
byte[] btArray = Encoding.UTF8.GetBytes(source);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(btArray, 0, btArray.Length);
cs.FlushFinalBlock();
}
return ms.ToArray().Bytes2Str();
}
catch { return source; }
}
}
catch
{
return "TripleDES Encryption error ";
}
}
/// <summary>
/// DES3 Decrypt
/// </summary>
public static string UnDes3(this string source, string keyVal)
{
try
{
byte[] byArray = source.Str2Bytes();
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
{
Key = keyVal.FormatByte(Encoding.UTF8),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(byArray, 0, byArray.Length);
cs.FlushFinalBlock();
cs.Close();
ms.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
catch
{
return "TripleDES Decryption error ";
}
}
#endregion
#region BASE64 Encryption and decryption
/// <summary>
/// BASE64 encryption
/// </summary>
/// <param name="source"> Fields to be encrypted </param>
/// <returns></returns>
public static string Base64(this string source)
{
var btArray = Encoding.UTF8.GetBytes(source);
return Convert.ToBase64String(btArray, 0, btArray.Length);
}
/// <summary>
/// BASE64 Decrypt
/// </summary>
/// <param name="source"> Fields to be decrypted </param>
/// <returns></returns>
public static string UnBase64(this string source)
{
var btArray = Convert.FromBase64String(source);
return Encoding.UTF8.GetString(btArray);
}
#endregion
#region Internal methods
/// <summary>
/// Turn it into an array
/// </summary>
private static byte[] Str2Bytes(this string source)
{
source = source.Replace(" ", "");
byte[] buffer = new byte[source.Length / 2];
for (int i = 0; i < source.Length; i += 2) buffer[i / 2] = Convert.ToByte(source.Substring(i, 2), 16);
return buffer;
}
/// <summary>
/// Convert to string
/// </summary>
private static string Bytes2Str(this IEnumerable<byte> source, string formatStr = "{0:X2}")
{
StringBuilder pwd = new StringBuilder();
foreach (byte btStr in source) { pwd.AppendFormat(formatStr, btStr); }
return pwd.ToString();
}
private static byte[] FormatByte(this string strVal, Encoding encoding)
{
return encoding.GetBytes(strVal.Base64().Substring(0, 16).ToUpper());
}
/// <summary>
/// HashAlgorithm Unified encryption method
/// </summary>
private static string HashAlgorithmBase(HashAlgorithm hashAlgorithmObj, string source, Encoding encoding)
{
byte[] btStr = encoding.GetBytes(source);
byte[] hashStr = hashAlgorithmObj.ComputeHash(btStr);
return hashStr.Bytes2Str();
}
#endregion
}
}
版权声明
本文为[It technology ape]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231753552227.html
边栏推荐
- Transfer learning of five categories of pictures based on VGg
- Halo open source project learning (II): entity classes and data tables
- Leak detection and vacancy filling (VIII)
- Amount input box, used for recharge and withdrawal
- Oil monkey website address
- 2022 Shanghai safety officer C certificate operation certificate examination question bank and simulation examination
- Summary of floating point double precision, single precision and half precision knowledge
- 41. The first missing positive number
- 2022年流动式起重机司机国家题库模拟考试平台操作
- 2021长城杯WP
猜你喜欢
Implementation of image recognition code based on VGg convolutional neural network
干货 | 快速抽取缩略图是怎么练成的?
Go's gin framework learning
土地覆盖/利用数据产品下载
Transfer learning of five categories of pictures based on VGg
1217_ Generating target files using scons
cv_ Solution of mismatch between bridge and opencv
The JS timestamp of wechat applet is converted to / 1000 seconds. After six hours and one day, this Friday option calculates the time
2022年上海市安全员C证操作证考试题库及模拟考试
Halo open source project learning (II): entity classes and data tables
随机推荐
Applet learning notes (I)
2022 tea artist (primary) examination simulated 100 questions and simulated examination
Comparison between xtask and kotlin coroutine
列錶的使用-增删改查
2022江西储能技术展会,中国电池展,动力电池展,燃料电池展
Arithmetic expression
C# 的数据流加密与解密
Go file operation
干货 | 快速抽取缩略图是怎么练成的?
undefined reference to `Nabo::NearestNeighbourSearch
Open source key component multi_ Button use, including test engineering
油猴网站地址
Laser slam theory and practice of dark blue College Chapter 3 laser radar distortion removal exercise
ros常用的函数——ros::ok(),ros::Rate,ros::spin()和ros::spinOnce()
Implementation of object detection case based on SSD
Land cover / use data product download
Tell the truth of TS
394. String decoding - auxiliary stack
2022制冷与空调设备运行操作判断题及答案
Sword finger offer 03 Duplicate number in array