当前位置:网站首页>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
边栏推荐
- Welcome to the markdown editor
- Nat Commun|在生物科学领域应用深度学习的当前进展和开放挑战
- Vite configure proxy proxy to solve cross domain
- Gets the time range of the current week
- 122. The best time to buy and sell stocks II - one-time traversal
- C language implements memcpy, memset, strcpy, strncpy, StrCmp, strncmp and strlen
- Timestamp to formatted date
- 2022 Shanghai safety officer C certificate operation certificate examination question bank and simulation examination
- 一些问题一些问题一些问题一些问题
- 2022年茶艺师(初级)考试模拟100题及模拟考试
猜你喜欢

.105Location

2021 Great Wall Cup WP

Go file operation

关于gcc输出typeid完整名的方法

Auto.js 自定义对话框

Nat Commun|在生物科学领域应用深度学习的当前进展和开放挑战
![Click Cancel to return to the previous page and modify the parameter value of the previous page, let pages = getcurrentpages() let prevpage = pages [pages. Length - 2] / / the data of the previous pag](/img/ed/4d61ce34f830209f5adbddf9165676.png)
Click Cancel to return to the previous page and modify the parameter value of the previous page, let pages = getcurrentpages() let prevpage = pages [pages. Length - 2] / / the data of the previous pag

Go语言JSON包使用

On the problem of V-IF display and hiding

C#的随机数生成
随机推荐
Gaode map search, drag and drop query address
I/O多路复用及其相关详解
394. String decoding - auxiliary stack
Clion installation tutorial
土地覆盖/利用数据产品下载
92. 反转链表 II-字节跳动高频题
Flask项目的部署详解
2022江西储能技术展会,中国电池展,动力电池展,燃料电池展
【Appium】通过设计关键字驱动文件来编写脚本
Sword finger offer 22 The penultimate node in the linked list - speed pointer
2022年广东省安全员A证第三批(主要负责人)特种作业证考试题库及在线模拟考试
关于gcc输出typeid完整名的方法
Uniapp custom search box adaptation applet alignment capsule
239. Maximum value of sliding window (difficult) - one-way queue, large top heap - byte skipping high frequency problem
209. Minimum length subarray - sliding window
Arithmetic expression
cartographer_ There is no problem compiling node, but running the bug that hangs directly
Detailed deployment of flask project
Type judgment in [untitled] JS
Timestamp to formatted date