简体   繁体   中英

Encrypting and Decrypting strings in .net core with a machinekey from web.config file

I have an old bit of code that is encrypting and decrypting strings using AES and a machinekey stored in the web.config file. This is a framework 4 application. Here is some code for the class that does the encryption and decryption:

 private static readonly MachineKeySection MachineKeyConfig =
    (MachineKeySection)ConfigurationManager
        .GetSection("system.web/machineKey");

    private readonly byte[] _key;
    private readonly byte[] _iv;


    public AESEncryption()
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(MachineKeyConfig.DecryptionKey, new byte[] { byte values removed });
        _key = pdb.GetBytes(32);
        _iv = pdb.GetBytes(16);
    }

    public AESEncryption(string key)
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, new byte[] { byte value removed });
        _key = pdb.GetBytes(32);
        _iv = pdb.GetBytes(16);
    }

    
    public string Encrypt(string value)
    {
        
        if (string.IsNullOrWhiteSpace(value))
        {
            return value;
        }

        byte[] clearBytes = Encoding.Unicode.GetBytes(value);

        using (Aes encryptor = Aes.Create())
        {
            if (encryptor != null)
            {
                encryptor.Padding = PaddingMode.PKCS7;
                using (MemoryStream ms = new MemoryStream())
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(_key, _iv), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.FlushFinalBlock();
                    value = Convert.ToBase64String(ms.ToArray());
                }
            }
        }
        return value;
    }

    public string Decrypt(string value)
    {
        
        if (string.IsNullOrWhiteSpace(value))
        {
            return value;
        }
        byte[] cipherBytes = Convert.FromBase64String(value);

        using (Aes encryptor = Aes.Create())
        {
            if (encryptor != null)
            {
                encryptor.Padding = PaddingMode.PKCS7;
                using (MemoryStream ms = new MemoryStream())
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(_key, _iv), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.FlushFinalBlock();
                    value = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
        }
       
        return value;
    }

Pretty straight forward for the encryption. I need to use the same machinekey that was used for this encryption/decryption in a .net core 3.1 console application to feed some data into the system that is encrypted using the same machinekey. I have added an App.config file and copied the machinekey from the Framework application to the .net core app. Here is the config:

   <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <machineKey decryption="AES" decryptionKey="[decryptionkey]" validation="AES" validationKey="[validation key]" />
</configuration>

I am having problems pulling out this key from the app.config file. I tried this:

 private static readonly MachineKeySection MachineKeyConfig =
    (MachineKeySection)ConfigurationManager
        .GetSection("system.web/machineKey");

It isn't working. I need to use the same machinekey on the .net core app so the information streaming into the system from this application is able to be read in the older Framework application, and vice versa.

I moved the machinekey values from the old web.config file, and added them as individual key values in the appSettings section of the app.config. Once I did that, I imported System.Configuration and using the configuration manager I pulled the values I need.

private readonly string decryptionKey = ConfigurationManager.AppSettings.Get("decryptionKey");

I could then use this value as before and validated the decryption and encryption values were indeed the same. The problem I had before was there if I included a machineKey in the app config I would get an error that this was an unrecognized section:

ConfigurationErrorsException: Unrecognized configuration section machineKey

So I moved the values out into the Appsettings and pulled them there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM