0

我的对象从数据库中出来后,我需要解密密码,我该如何实现呢?这是我的加密和解密代码:

public class EncryptionHelper {
    public static string Encrypt(string strToEncrypt) {
        try {
            TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
            byte[] byteHash, byteBuff;
            string strTempKey = Settings.Default.Keyword;
            byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
            objHashMD5 = null;
            objDESCrypto.Key = byteHash;
            objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
            byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
            return Convert.ToBase64String(objDESCrypto.CreateEncryptor().
                TransformFinalBlock(byteBuff, 0, byteBuff.Length));
        } catch (Exception ex) {
            return strToEncrypt;
        }
    }

    public static string Decrypt(string strEncrypted) {
        try {
            TripleDESCryptoServiceProvider objDESCrypto =
                new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
            byte[] byteHash, byteBuff;
            string strTempKey = Settings.Default.Keyword;
            byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
            objHashMD5 = null;
            objDESCrypto.Key = byteHash;
            objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
            byteBuff = Convert.FromBase64String(strEncrypted);
            string strDecrypted = ASCIIEncoding.ASCII.GetString
            (objDESCrypto.CreateDecryptor().TransformFinalBlock
            (byteBuff, 0, byteBuff.Length));
            objDESCrypto = null;
            return strDecrypted;
        } catch (Exception ex) {
            return "Wrong Input. " + ex.Message;
        }
    }
}

这是我的实体:

public partial class S0Pin
{
    public int ID { get; set; }
    public string Serialnumber { get; set; }
    public string Pin { get; set; }

    public virtual User Creator { get; set; }
}

这是插入对象的方法

public bool AddS0Pin(S0Pin pin) {
    log.Debug("add s0pin with serialnumber " + pin.Serialnumber);
    var s0pin = S0Pin.SingleOrDefault(pn => pn.Serialnumber == pin.Serialnumber);
    if (s0pin != null) {
        s0pin.Pin = EncryptionHelper.Encrypt(pin.Pin);
    } else {
        this.S0Pin.Add(pin);
    }
    return this.SaveChanges() > 0;
}

取出数据库如何解密数据?最好的方法是在实体中。

4

1 回答 1

1

首先,解密密码根本不是一个好主意。但是,有时您需要这样做,尤其是在构建具有显示密码功能的密码管理器之类的东西时。

其次,据我了解,您希望能够通过实体中的属性访问解密的密码。我将创建另一个名为 DecryptedPassword 的属性,并在 getter 中调用 DecryptPassword。

像这样的东西:

public String DecryptPassword
{
    get
    {
        return Decrypt(this.Pin);
    }
}

更进一步,我将创建实体的一个部分类并将这个属性转储到那里,以确保我不会弄乱任何生成的代码。

希望这符合要求。

于 2013-08-27T00:44:59.697 回答