加密asp.net中的Decrypt字符串

时间:2017-04-29 16:25:58

标签: c# asp.net encryption

我正在尝试加密asp.net中的解密字符串。加密工作完美,但我在解密方面存在问题。当我试图解密字符串时,我得到空字符串。 这是代码:

private const string Key = "AOF1J2GN-O4K6-P6MW-L0R2-LE6N2V9G1P5A";
public static string Encrypt(string data, string key = null) {
    if (key == null)
        key = Key;
    RijndaelManaged rijndaelCipher = GetRijndaelManaged(key);
    ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
    byte[] plainText = Encoding.UTF8.GetBytes(data);
    var base64String = Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
    return HttpUtility.UrlEncode(base64String);
}
public static string Decrypt(string data, string key = null) {
    if (key == null)
        key = Key;
    RijndaelManaged rijndaelCipher = GetRijndaelManaged(key);
    byte[] encryptedData = Convert.FromBase64String(data);
    byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
    return Encoding.UTF8.GetString(plainText);
}
private static RijndaelManaged GetRijndaelManaged(String key) {
    RijndaelManaged objRijndaelManaged = new RijndaelManaged();
    objRijndaelManaged.Mode = CipherMode.CBC; //remember this parameter
    objRijndaelManaged.Padding = PaddingMode.PKCS7; //remember this parameter
    objRijndaelManaged.KeySize = 128;
    objRijndaelManaged.BlockSize = 128;
    byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
    byte[] keyBytes = new byte[0x10];
    int len = pwdBytes.Length;
    if (len > keyBytes.Length) {
        len = keyBytes.Length;
    }
    Array.Copy(pwdBytes, keyBytes, len);
    objRijndaelManaged.Key = keyBytes;
    objRijndaelManaged.IV = keyBytes;
    return objRijndaelManaged;
}

我也尝试过其他一些示例代码,但结果相同。 “钥匙”可能存在一些问题,但我不确定。 有什么帮助吗?

0 个答案:

没有答案