开发者

SQL CLR stored procedure for encryption

Background: I have an SSIS package that loads profile data from system A and creates corresponding profiles and membership users in system B. System B uses a custom ASP.NET Membership Provider that must be able to decrypt the passwords generated by the SSIS package. I've created CLR stored procedures for salt generation and encryption to be used by the SSIS package.

Problem: In order for the encrypted passwords to be decryptable by the ASP.NET Membership Provider I need to set the MachineKey used by the CLR stored procedures. I have no idea how to do this, or if it's even possible.

I used Reflector to pull out the required encryption code from the System.Membership dll. After a bit of refactoring it looks like this:

private static byte[] PerformEncryption(byte[] i开发者_开发知识库nput, bool encryptFlag)
{
    if (input == null)
        return null;

    byte[] inputBuf = input;
    byte[] outputBuf;

    try
    {
        using (MemoryStream targetStream = new MemoryStream())
        using (SymmetricAlgorithm algo = SymmetricAlgorithm.Create())
        using (ICryptoTransform cryptoTransform = CreateCryptoTransform(algo, encryptFlag))
        using (CryptoStream cryptoStream = new CryptoStream(targetStream, cryptoTransform, CryptoStreamMode.Write))
        {
            int start = 0;
            int length = input.Length;

            // Write the input buffer to the cryptoStream passing the byte stream through the cryptoTransform
            cryptoStream.Write(inputBuf, start, length);
            cryptoStream.FlushFinalBlock();
            outputBuf = targetStream.ToArray();
        }
    }
    catch (Exception ex)
    {
        throw new InvalidOperationException("Unable to " + (encryptFlag ? "en" : "de") + "crypt data. See inner exception for more detail.", ex);
    }
    return outputBuf;
}

The problem is SymmetricAlgorithm.Create() creates the default symmetric algorithm with init vectors as defined by the MachineKey.

Any help is appreciated. Also, please let me know if there is a better/different approach that might be easier.

Thanks.


Anyway, take into accout this:

throw new InvalidOperationException(String.Format("Unable to {0}crypt data. See inner exception for more detail.", encryptFlag ? "en" : "de"), ex);

which is rather readable. Isn't it?

And another thing - using blocks can be nested, so no additional indent is required.


I wound up putting the key into the code. Certainly not the best solution, but it worked. Anyways, I am not using this method anymore. I am implementing a completely different scenario.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜