Skip to content

007. CryptService

Jas edited this page Feb 24, 2024 · 2 revisions

Design (Domain)

As defined in the Domain Definition the CryptService implements the ICryptService Interface providing the funtions to encrypt and decrypt data from entities as well as a hash function for the Master Password. Further it can create a Hash, which is used to

public interface ICryptService {
    public void Encrypt(ISecureProperties input, string key);
    public void Decrypt(ISecureProperties input, string key);
    public string Hash(string input, string salt);
    public string DeriveKeyFrom(string input, string salt);
}

Encryption and Decryption (Application)

public string Encrypt(string input, string key) {
    var inputBytes = GetBytesFrom(input);

    using var aes = CreateAesWith(key);
    aes.GenerateIV();
    var iv = aes.IV;

    var cipherBytes = aes.EncryptCfb(inputBytes, iv);
    var cipherWithIvHeading = iv.Concat(cipherBytes).ToArray();

    return Convert.ToBase64String(cipherWithIvHeading);
}

public string Decrypt(string input, string key) {
    var inputBytes = Convert.FromBase64String(input);

    using var aes = CreateAesWith(key);
    var iv = inputBytes[0..16];
    var plainBytes = aes.DecryptCfb(inputBytes[16..], iv);

    return GetStringFrom(plainBytes);
}

ISecureProperties

public interface ISecureProperties {
    public List<(Func<string>, Action<string>)> SecurableProperties();
}

With the ISecureProperties interface it is possible to encrypt and decrypt multiple properties of any entity that implements it by providing the getters and setters of the properties that should be encrypted or decrypted.

public void Encrypt(ISecureProperties input, string key) {
    foreach ((var getter, var setter) in input.SecurableProperties()) {
        var val = Encrypt(getter(), key);
        setter(val);
    }
}

public void Decrypt(ISecureProperties input, string key) {
    foreach ((var getter, var setter) in input.SecurableProperties()) {
        var val = Decrypt(getter(), key);
        setter(val);
    }
}