使用WebApi和SQL Server存储敏感数据

时间:2017-06-05 16:23:01

标签: c# encryption asp.net-web-api cryptography

我知道这是关于密码学的常见问题,在某些情况下,它与应该的方式相关。我不是加密的专业知识,但我试图创建一些需要操纵信用卡信息和个人信息的东西。目前我正在使用WebApi并在对其进行研究后,我发现这种方法至少看起来是可靠的#34;那么这可能是我的主要加密基于你在这件事上的经验?这是Rijndael!

这是我的代码:

public class Encryption
{
    internal const string Inputkey = "A GUID";

    public static string EncryptRijndael(string text, string salt)
    {
        if (string.IsNullOrEmpty(text))
            throw new ArgumentNullException("text");

        var aesAlg = NewRijndaelManaged(salt);

        var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
        var msEncrypt = new MemoryStream();
        using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
        using (var swEncrypt = new StreamWriter(csEncrypt))
        {
            swEncrypt.Write(text);
        }

        return Convert.ToBase64String(msEncrypt.ToArray());
    }
    public static bool IsBase64String(string base64String)
    {
        base64String = base64String.Trim();
        return (base64String.Length % 4 == 0) &&
               Regex.IsMatch(base64String, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
    }
    public static string DecryptRijndael(string cipherText, string salt)
    {
        if (string.IsNullOrEmpty(cipherText))
            throw new ArgumentNullException("cipherText");

        if (!IsBase64String(cipherText))
            throw new Exception("The cipherText input parameter is not base64 encoded");

        string text;

        var aesAlg = NewRijndaelManaged(salt);
        var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
        var cipher = Convert.FromBase64String(cipherText);

        using (var msDecrypt = new MemoryStream(cipher))
        {
            using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (var srDecrypt = new StreamReader(csDecrypt))
                {
                    text = srDecrypt.ReadToEnd();
                }
            }
        }
        return text;
    }
    private static RijndaelManaged NewRijndaelManaged(string salt)
    {
        if (salt == null) throw new ArgumentNullException("salt");
        var saltBytes = Encoding.ASCII.GetBytes(salt);
        var key = new Rfc2898DeriveBytes(Inputkey, saltBytes);

        var aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
        aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

        return aesAlg;
    }
}

对于盐,我总是传递一个新的Guid。

var SALT = Guid.NewGuid().toString();
Security.Encryption.Encryption.Encrypt(DATA, SALT)

谢谢!

0 个答案:

没有答案