【发布时间】:2017-03-21 16:21:39
【问题描述】:
我有 SQL Server 2012,但我无法迁移到 SQL Server 2016。
我正在使用加密,以这种方式与实体框架代码优先。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace x.y.Api.Models
{
[Table("Tbl_Naturalezas")]
public class Naturalezas: EncryptDecrypt
{
public Naturalezas()
{
_locked = true;
}
[Key]
public int idNaturaleza { get; set; }
string _naturaleza;
[StringLength(350)]
public string naturaleza
{
get { return locked ? Decrypt(_naturaleza, ConfigurationManager.AppSettings["appKeyPassword"]) : naturaleza; }
set { _naturaleza = IsEncrypted(value) ? value : Encrypt(value, ConfigurationManager.AppSettings["appKeyPassword"]) ; }
}
public virtual ICollection<Contactos> Contactos { get; set; }
}
}
继承自这个类:
public class EncryptDecrypt
{
public bool _locked;
public const string EncryptedStringPrefix = "X";
private const int Keysize = 256;
private const int DerivationIterations = 1000;
public string Encrypt(string atributoClase, string passPhrase)
{
string plainText = atributoClase.ToUpper();
if (plainText != null)
{
var saltStringBytes = Generate256BitsOfRandomEntropy();
var ivStringBytes = Generate256BitsOfRandomEntropy();
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 256;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
else
{
return plainText;
}
}
public string Decrypt(string atributoClase, string passPhrase)
{
string cipherText = atributoClase.ToUpper();
if (cipherText != null)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 256;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
else
{
return cipherText;
}
}
private static byte[] Generate256BitsOfRandomEntropy()
{
var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
using (var rngCsp = new RNGCryptoServiceProvider())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
public void Lock()
{
_locked = true;
}
public void Unlock()
{
_locked = false;
}
public bool IsEncrypted(string atributosClases)
{
if (atributosClases != null)
{
if(atributosClases.Length > 50)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
}
在 POST api 控制器中,我这样做:
// POST: api/Naturalezas
[ResponseType(typeof(Naturalezas))]
public IHttpActionResult PostNaturaleza(Naturalezas naturaleza)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
naturaleza.Unlock();
db.Naturalezas.Add(naturaleza);
db.SaveChanges();
naturaleza.Lock();
return CreatedAtRoute("DefaultApi", new { id = naturaleza.idNaturaleza }, naturaleza);
}
我基于这篇博文进行了加密:
现在,这仅适用于一个表,但在另一个表中,我们有 20 个字段,所有字段都必须加密,但是我们需要能够使用 LIKE、= 等搜索这 20 个字段。
什么是最好的解决方案(引导我找到代码解决方案),以便能够:
- 在不使用 SQL 2016 Always Encrypted 的情况下加密数据库中的所有字段。
- 做搜索。
- 保持性能。
【问题讨论】:
-
如果数据是加密的,而且密码不在数据库中,你就不能真正做
like这样的操作。即使始终加密,您也无法做到like。 -
我找到了这个,但它没有说它是否适用于 LIKE。 blogs.msdn.microsoft.com/sqlsecurity/2015/08/27/…
标签: c# .net sql-server entity-framework linq