Files
Pilz/Pilz.Cryptography/SimpleStringCrypter.cs
2024-04-15 09:01:22 +02:00

81 lines
2.7 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;
namespace Pilz.Cryptography
{
public class SimpleStringCrypter : ICrypter
{
private readonly TripleDES 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 = TripleDES.Create();
TripleDes.Key = TruncateHash(key,TripleDes.KeySize / 8);
TripleDes.IV = TruncateHash(string.Empty, TripleDes.BlockSize / 8);
}
private byte[] TruncateHash(string key, int length)
{
SHA1 sha1CryptoServiceProvider = SHA1.Create();
var bytes = TextEncoding.GetBytes(key);
var array = sha1CryptoServiceProvider.ComputeHash(bytes);
var output = new byte[length];
var lowerLength = Math.Min(array.Length, output.Length);
for (int i = 0; i < lowerLength; i++)
output[i] = array[i];
return output;
}
private string EncryptData(string plaintext)
{
var bytes = TextEncoding.GetBytes(plaintext);
using var memoryStream = new MemoryStream();
using var 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)
{
var array = Convert.FromBase64String(encryptedtext);
using var memoryStream = new MemoryStream();
using var 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 ?? string.Empty);
}
public string Decrypt(string encryptedValue)
{
if (string.IsNullOrEmpty(encryptedValue))
return string.Empty;
else
return DecryptData(encryptedValue);
}
}
}