You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
2.4 KiB
C#
85 lines
2.4 KiB
C#
10 months ago
|
using System;
|
||
|
using System.IO;
|
||
|
using System.Security.Cryptography;
|
||
|
using System.Text;
|
||
|
using Org.BouncyCastle.Crypto;
|
||
|
using Org.BouncyCastle.Crypto.IO;
|
||
|
using Org.BouncyCastle.Security;
|
||
|
|
||
|
namespace DS.Module.Core.Helpers
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 3DES加密 解密
|
||
|
/// </summary>
|
||
|
public static class EncrypteHelper
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 加密
|
||
|
/// </summary>
|
||
|
/// <param name="input"></param>
|
||
|
/// <param name="key"></param>
|
||
|
/// <returns></returns>
|
||
|
public static string EncryptData(string input, string key)
|
||
|
{
|
||
|
var inCipher = CreateCipher(true, key);
|
||
|
|
||
|
var inputArray = Encoding.UTF8.GetBytes(input);
|
||
|
|
||
|
byte[] cipherData = inCipher.DoFinal(inputArray);
|
||
|
|
||
|
return Convert.ToBase64String(cipherData);
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// 解密
|
||
|
/// </summary>
|
||
|
/// <param name="input"></param>
|
||
|
/// <param name="key"></param>
|
||
|
/// <returns></returns>
|
||
|
public static string DecryptData(string input, string key)
|
||
|
{
|
||
|
var inputArrary = Convert.FromBase64String(input);
|
||
|
|
||
|
var outCipher = CreateCipher(false, key);
|
||
|
|
||
|
var encryptedDataStream = new MemoryStream(inputArrary, false);
|
||
|
|
||
|
var dataStream = new MemoryStream();
|
||
|
|
||
|
var outCipherStream = new CipherStream(dataStream, null, outCipher);
|
||
|
|
||
|
int ch;
|
||
|
while ((ch = encryptedDataStream.ReadByte()) >= 0)
|
||
|
{
|
||
|
outCipherStream.WriteByte((byte)ch);
|
||
|
}
|
||
|
|
||
|
outCipherStream.Close();
|
||
|
encryptedDataStream.Close();
|
||
|
|
||
|
var dataBytes = dataStream.ToArray();
|
||
|
|
||
|
return Encoding.UTF8.GetString(dataBytes);
|
||
|
}
|
||
|
|
||
|
static IBufferedCipher CreateCipher(bool forEncryption, string key,
|
||
|
string cipMode = "DESede/ECB/PKCS5Padding")
|
||
|
{
|
||
|
var algorithmName = cipMode;
|
||
|
if (cipMode.IndexOf('/') >= 0)
|
||
|
{
|
||
|
algorithmName = cipMode.Substring(0, cipMode.IndexOf('/'));
|
||
|
}
|
||
|
|
||
|
var cipher = CipherUtilities.GetCipher(cipMode);
|
||
|
|
||
|
var keyBytes = Encoding.UTF8.GetBytes(key);
|
||
|
|
||
|
var keyParameter = ParameterUtilities.CreateKeyParameter(algorithmName, keyBytes);
|
||
|
|
||
|
cipher.Init(forEncryption, keyParameter);
|
||
|
|
||
|
return cipher;
|
||
|
}
|
||
|
}
|
||
|
}
|