当前位置:网站首页>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
边栏推荐
- Clion installation tutorial
- 122. 买卖股票的最佳时机 II-一次遍历
- SQL optimization for advanced learning of MySQL [insert, primary key, sort, group, page, count]
- Transfer learning of five categories of pictures based on VGg
- Leak detection and vacancy filling (6)
- Detailed deployment of flask project
- Eigen learning summary
- ros常用的函数——ros::ok(),ros::Rate,ros::spin()和ros::spinOnce()
- JS forms the items with the same name in the array object into the same array according to the name
- Vite configure proxy proxy to solve cross domain
猜你喜欢
102. 二叉树的层序遍历
48. Rotate image
SQL optimization for advanced learning of MySQL [insert, primary key, sort, group, page, count]
Cloud native Virtualization: building edge computing instances based on kubevirt
Clion installation tutorial
Go的Gin框架学习
编译原理 求first集 follow集 select集预测分析表 判断符号串是否符合文法定义(有源码!!!)
JS forms the items with the same name in the array object into the same array according to the name
Gets the time range of the current week
92. 反转链表 II-字节跳动高频题
随机推荐
198. Looting - Dynamic Planning
470. Rand10() is implemented with rand7()
I/O多路复用及其相关详解
MySQL进阶学习之SQL优化【插入,主键,排序,分组,分页,计数】
This point in JS
402. Remove K digits - greedy
C# 网络相关操作
587. 安装栅栏 / 剑指 Offer II 014. 字符串中的变位词
41. The first missing positive number
Open source key component multi_ Button use, including test engineering
470. 用 Rand7() 实现 Rand10()
2022 Shanghai safety officer C certificate operation certificate examination question bank and simulation examination
20222 return to the workplace
102. Sequence traversal of binary tree
云原生虚拟化:基于 Kubevirt 构建边缘计算实例
Dry goods | how to extract thumbnails quickly?
Remember using Ali Font Icon Library for the first time
Compilation principle first set follow set select set prediction analysis table to judge whether the symbol string conforms to the grammar definition (with source code!!!)
undefined reference to `Nabo::NearestNeighbourSearch
2022 Jiangxi energy storage technology exhibition, China Battery exhibition, power battery exhibition and fuel cell Exhibition