using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace RG3.PF.AbstractionsBasis
{
/// <summary>
/// DES加密 解密
/// 1.Java密钥为8字节,或8的倍数。2.只支持加密字符串为128位以内的字符加密,如果超过128位要分段进行加密
/// </summary>
public static class DESUtil
{
#region DES加密 ECB
/// <summary>
/// DES加密 ECB 密钥8位
/// </summary>
/// <param name="encryptString"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string EncryptEcb(string encryptString, string sKey)
{
try
{
string key;
//密钥为8位
if (sKey.Length <= 8)
{
key = sKey.PadRight(8, '0');
}
else
{
key = sKey.Substring(0, 8);
}
byte[] keyBytes = Encoding.Default.GetBytes(key);
byte[] keyIV = keyBytes;
byte[] encryptBytes = Encoding.Default.GetBytes(encryptString);
var desProvider = DES.Create();
// 使用ECB方式
desProvider.Mode = CipherMode.ECB;
// PKCS7padding
desProvider.Padding = PaddingMode.PKCS7;
MemoryStream memStream = new MemoryStream();
//CreateEncryptor(keyBytes, keyIV)类似于OpenSSL中的密钥置换
CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
crypStream.Write(encryptBytes, 0, encryptBytes.Length);
crypStream.FlushFinalBlock();
byte[] cipherBytes = memStream.ToArray();
return Convert.ToBase64String(cipherBytes);
}
catch
{
return encryptString;
}
}
#endregion DES加密 ECB
#region DEC解密 ECB
/// <summary>
/// DEC解密 ECB 密钥8位
/// </summary>
/// <param name="decryptString"></param>
/// <param name="sKey"></param>
/// <returns></returns>
public static string DecryptEcb(string decryptString, string sKey)
{
//key为8位
string key;
if (sKey.Length <= 8)
{
key = sKey.PadRight(8, '0');
}
else
{
key = sKey.Substring(0, 8);
}
byte[] keyBytes = Encoding.Default.GetBytes(key);
byte[] keyIV = keyBytes;// Encoding.Default.GetBytes(iv);// keyBytes;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
var desProvider = DES.Create();
desProvider.Mode = CipherMode.ECB;
MemoryStream memStream = new MemoryStream();
CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
crypStream.Write(inputByteArray, 0, inputByteArray.Length);
crypStream.FlushFinalBlock();
return Encoding.Default.GetString(memStream.ToArray());
}
#endregion DEC解密 ECB
}
}
文档更新时间: 2023-04-05 22:47 作者:admin