MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Verschlüsseln/Entschlüsseln der Eigenschaft beim Schreiben/Lesen in c# mongo db

Meine Lösung:

Modell:

public class Patient
{
    //comes from the client as XXXXXXXXX, RegEx: "([0-9]{9})"
    public EncryptedString SocialSecurityNumber { get; set; }  
}

Benutzerdefinierter Typ:

public class EncryptedString
{
    private readonly string _value;

    public EncryptedString(string value)
    {
        _value = value;
    }

    public static implicit operator string(EncryptedString s)
    {
        return s._value;
    }

    public static implicit operator EncryptedString(string value)
    {
        if (value == null)
            return null;

        return new EncryptedString(value);
    }
}

Serializer (unter Verwendung von Deterministische Verschlüsselung ). ):

public interface IEncryptedStringSerializer : IBsonSerializer<EncryptedString> {} 

public class EncryptedStringSerializer : SerializerBase<EncryptedString>, IEncryptedStringSerializer
{
    private readonly IDeterministicEncrypter _encrypter;
    private readonly string _encryptionKey;

    public EncryptedStringSerializer(IConfiguration configuration, IDeterministicEncrypter encrypter)
    {
        _encrypter = encrypter;
        _encryptionKey = configuration.GetSection("MongoDb")["EncryptionKey"];
    }

    public override EncryptedString Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var encryptedString = context.Reader.ReadString();
        return _encrypter.DecryptStringWithPassword(encryptedString, _encryptionKey);
    }

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, EncryptedString value)
    {
        var encryptedString = _encrypter.EncryptStringWithPassword(value, _encryptionKey);
        context.Writer.WriteString(encryptedString);
    }
}

Registrierung des Serialisierers:

collection.AddScoped<IEncryptedStringSerializer, EncryptedStringSerializer>();
//then later...
BsonSerializer.RegisterSerializer<EncryptedString>(sp.GetService<IEncryptedStringSerializer>());