Search code examples
c#mysqlentity-framework-coreaes

My SQL script to decrypt data encrypted by EF Core


I have some of columns encrypted by ef core:

        var keyBase = System.Text.Encoding.UTF8.GetBytes("xxxxxxxxxxxxxxxxxxxxxxxx");
        var key = Convert.ToBase64String(keyBase);
        _provider = new AesProvider(System.Text.Encoding.UTF8.GetBytes(key));
        modelBuilder.UseEncryption(this._provider);

For testing purposes i want to decrypt it by sql script

SET @keyBase = 'xxxxxxxxxxxxxxxxxxxxxxxx';
SET @encrypted_data = 'some encrypted data from column';

-- Decode the keyBase from Base64 encoding
SET @key = UNHEX(@keyBase);

-- Generate a random IV (Initialization Vector) or use a predetermined one if available
SET @iv = UNHEX(SHA2(UUID(), 128));

-- Decrypt the data using the key and IV
SET @decrypted_data = AES_DECRYPT(FROM_BASE64(@encrypted_data), @key, @iv);

-- Return the decrypted data
SELECT CAST(@decrypted_data AS CHAR) AS decrypted_data;

Unfortunately this returns null


Solution

  • This is answer

    SET @keyBase = 'xxx';
    SET @encrypted_data = 'xxx';
    
    SET @@SESSION.block_encryption_mode = 'aes-256-cbc';
    
    -- Convert the keyBase to binary
    SET @keyBaseBinary = CONVERT(@keyBase USING utf8);
    
    -- Convert the binary keyBase to Base64
    SET @key = TO_BASE64(@keyBaseBinary);
    
    -- Decode the keyBase from Base64 encoding
    SET @binary_encrypted_data = FROM_BASE64(@encrypted_data);
    
    -- Extract the first 16 bytes from the decoded data as the IV
    SET @iv = SUBSTRING(@binary_encrypted_data, 1, 16);
    
    -- Remove the IV from the binary data
    SET @data_without_iv = SUBSTRING(@binary_encrypted_data, 17);
    
    -- Decrypt the data using AES_DECRYPT in MySQL
    SELECT CAST(AES_DECRYPT(@data_without_iv, @key, @iv) AS CHAR) AS decrypted_data;