Files
Pilz/Pilz.Cryptography/SimpleStringCrypter.cs
2020-07-14 09:35:33 +02:00

75 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
using Microsoft.VisualBasic.CompilerServices;
namespace Pilz.Cryptography
{
public class SimpleStringCrypter : ICrypter
{
private TripleDESCryptoServiceProvider TripleDes;
public Encoding TextEncoding { get; private set; } = Encoding.Default;
public SimpleStringCrypter() : this(string.Empty)
{
}
public SimpleStringCrypter(string key) : this(key, Encoding.Default)
{
}
public SimpleStringCrypter(string key, Encoding textEncoding)
{
TextEncoding = textEncoding;
TripleDes = new TripleDESCryptoServiceProvider();
TripleDes.Key = TruncateHash(key,TripleDes.KeySize / 8);
TripleDes.IV = TruncateHash(string.Empty, TripleDes.BlockSize / 8);
}
private byte[] TruncateHash(string key, int length)
{
SHA1CryptoServiceProvider sha1CryptoServiceProvider = new SHA1CryptoServiceProvider();
byte[] bytes = TextEncoding.GetBytes(key);
byte[] array = sha1CryptoServiceProvider.ComputeHash(bytes);
return (byte[])Utils.CopyArray(array, new byte[checked(length - 1 + 1)]);
}
private string EncryptData(string plaintext)
{
byte[] bytes = TextEncoding.GetBytes(plaintext);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, TripleDes.CreateEncryptor(), CryptoStreamMode.Write);
cryptoStream.Write(bytes, 0, bytes.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
private string DecryptData(string encryptedtext)
{
byte[] array = Convert.FromBase64String(encryptedtext);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, TripleDes.CreateDecryptor(), CryptoStreamMode.Write);
cryptoStream.Write(array, 0, array.Length);
cryptoStream.FlushFinalBlock();
return TextEncoding.GetString(memoryStream.ToArray());
}
public string Encrypt(string plainValue)
{
return EncryptData(plainValue);
}
public string Decrypt(string encryptedValue)
{
if (string.IsNullOrEmpty(encryptedValue))
return string.Empty;
else
return DecryptData(encryptedValue);
}
}
}