【问题标题】:SQL CLR stored procedure for encryption用于加密的 SQL CLR 存储过程
【发布时间】:2011-11-02 16:25:49
【问题描述】:

背景:我有一个 SSIS 包,它从系统 A 加载配置文件数据并在系统 B 中创建相应的配置文件和成员资格用户。系统 B 使用一个自定义的 ASP.NET 成员资格提供程序,它必须能够解密 SSIS 包生成的密码。我为 SSIS 包使用的盐生成和加密创建了 CLR 存储过程。

问题: 为了使 ASP.NET 成员资格提供程序能够解密加密的密码,我需要设置 CLR 存储过程使用的 MachineKey。我不知道该怎么做,或者是否有可能。

我使用 Reflector 从 System.Membership dll 中提取所需的加密代码。经过一番重构,它看起来像这样:

private static byte[] PerformEncryption(byte[] input, 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;
}

问题是SymmetricAlgorithm.Create() 使用 MachineKey 定义的初始向量创建默认对称算法。

感谢任何帮助。另外,如果有更好/不同的方法可能更容易,请告诉我。

谢谢。

【问题讨论】:

    标签: c# .net encryption asp.net-membership clrstoredprocedure


    【解决方案1】:

    无论如何,请考虑一下:

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

    这是相当可读的。不是吗?

    还有一件事——using 块可以嵌套,所以不需要额外的缩进。

    【讨论】:

    • 是的,string.format 的可读性不是很强,但我喜欢尽可能避免附加字符串。我打算把它分成两行,但我想为什么要为异常消息而烦恼。它不是我试图使其可读的复杂业务逻辑。要么就是让消息总是说“加密”。无论如何,我喜欢省略花括号的技巧,我会尝试一下。
    【解决方案2】:

    我最终将密钥放入代码中。当然不是最好的解决方案,但它确实有效。无论如何,我不再使用这种方法了。我正在实现一个完全不同的场景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 2011-06-01
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多