This commit is contained in:
schedpas
2021-10-27 10:04:43 +02:00
12 changed files with 136 additions and 25 deletions

View File

@@ -11,20 +11,19 @@ namespace Pilz.Cryptography
public class SecureString
{
public static ICrypter DefaultCrypter { get; set; }
[JsonIgnore]
public ICrypter Crypter { get; set; }
[JsonProperty]
public string EncryptedValue { get; set; }
[JsonIgnore]
public string Value
{
get => GetCrypter().Decrypt(EncryptedValue);
get => GetCrypter()?.Decrypt(EncryptedValue);
set => EncryptedValue = GetCrypter().Encrypt(value);
}
[JsonConstructor]
private SecureString(JsonConstructorAttribute dummyAttribute)
{
}
public SecureString() :
this(string.Empty, true)
{
@@ -73,7 +72,7 @@ namespace Pilz.Cryptography
public static implicit operator string(SecureString value) => value?.Value;
public static implicit operator SecureString(string value) => new SecureString(value, false);
public static bool operator ==(SecureString left, SecureString right) => left.EncryptedValue == right.EncryptedValue;
public static bool operator !=(SecureString left, SecureString right) => left.EncryptedValue != right.EncryptedValue;
public static bool operator ==(SecureString left, SecureString right) => left?.EncryptedValue == right?.EncryptedValue;
public static bool operator !=(SecureString left, SecureString right) => left?.EncryptedValue != right?.EncryptedValue;
}
}

View File

@@ -22,12 +22,13 @@ namespace Pilz.Json.Converters
var idString = serializer.Deserialize<string>(reader);
SecureString id;
if (existingValue is object)
if (existingValue is SecureString)
{
id = (SecureString)existingValue;
id.EncryptedValue = idString;
}
else
id = new SecureString();
id.EncryptedValue = idString;
id = new SecureString(idString, true);
return id;
}

View File

@@ -35,10 +35,13 @@ namespace Pilz.Cryptography
byte[] bytes = TextEncoding.GetBytes(key);
byte[] array = sha1CryptoServiceProvider.ComputeHash(bytes);
var output = new byte[checked(length - 1 + 1)];
array.CopyTo(output, 0);
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 array;
return output;
}
private string EncryptData(string plaintext)
@@ -63,7 +66,7 @@ namespace Pilz.Cryptography
public string Encrypt(string plainValue)
{
return EncryptData(plainValue);
return EncryptData(plainValue ?? string.Empty);
}
public string Decrypt(string encryptedValue)