2015-04-01 85 views
0

我想使用非对称加密算法来加密和解密字符串,这是我想要在加密和解密函数中传递不同的密钥。错误:“填充无效且无法移除”使用非对称算法

我的代码如下:

public ActionResult Encrypt(string clearText) 
{ 
    string EncryptionKey = "ABKV2SPBNI99212"; 
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); 
    using (Aes encryptor = Aes.Create()) 
    { 
     Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
     encryptor.Key = pdb.GetBytes(32); 
     encryptor.IV = pdb.GetBytes(16); 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) 
      { 
       cs.Write(clearBytes, 0, clearBytes.Length); 
       cs.Close(); 
      } 
      clearText = Convert.ToBase64String(ms.ToArray()); 
     } 
    } 

    Decrypt(clearText); 

    return View(clearText); 
} 

public string Decrypt(string cipherText) 
{ 
    string EncryptionKey = "MAKV2SPBNI99212"; 
    byte[] cipherBytes = Convert.FromBase64String(cipherText); 
    using (Aes encryptor = Aes.Create()) 
    { 
     Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
     encryptor.Key = pdb.GetBytes(32); 
     encryptor.IV = pdb.GetBytes(16); 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) 
      { 

       cs.Write(cipherBytes, 0, cipherBytes.Length); 
       cs.Close(); 
      } 
      cipherText = Encoding.Unicode.GetString(ms.ToArray()); 
     } 
    } 
    return cipherText ; 
} 

这里是加密功能,我使用链接 如下

<a href="@Url.Action("Encrypt", "Home", new {@clearText="5"})">Bid Buddy</a> 

在这里,我想如发送不同的键值发送的值。

+0

确保'encrypt/decrypt'键是一样的。 – user01928374655647382910019283 2015-04-01 12:33:02

+0

你的代码*不*使用非对称加密。 AES是一种对称算法,这意味着你需要使用相同的密钥 – 2015-04-01 12:42:29

回答

2

AES是一种对称分组密码。解密仅限于如果在加密期间显示相同的密钥,则可以使用。这是没有办法的。

你还有什么是密码散列函数。所有散列函数都有冲突,但是对于像你这样的加密散列函数,这些散列函数的使用可以忽略不计。因此,找到两个映射到相同密钥的密码片(这会使其在技术上不对称)的成本太高。

您需要生成一个公私密钥对。做这个的选项是例如RSA。然后您将使用随机AES密钥对数据进行加密,然后使用RSA公钥对AES密钥进行加密。这被称为hybrid encryption

+0

这是真的......但是有什么解决办法可以使用这些函数使用不同的密钥。 – SantyEssac 2015-04-01 12:41:18

+1

你的意思是不同的对称密钥(AES)?根据定义,没有。 – 2015-04-01 12:42:05

+1

@SantyEssac你想做什么?你试图解决什么是真正的问题?混合算法和“解决方法”是削弱安全性的可靠方法。硬编码的字符串键也是一个非常糟糕的主意。 – 2015-04-01 12:44:09

2

你的encrpt/decrpyt是不同的,并且会导致你得到这个错误。

Padding is invalid and cannot be removed

务必保持encrpt/decrpt相同