Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用户代码未处理加密异常_C#_Encryption - Fatal编程技术网

C# 用户代码未处理加密异常

C# 用户代码未处理加密异常,c#,encryption,C#,Encryption,解密密钥时,我遇到错误: 用户代码未处理加密异常。 要解密的数据长度无效 现在我想做的是,我想检查给定的字符串是否能够解密。如果它能够解密,我只想执行下面的代码。这样我就不会出错了 var byteBuff = Convert.FromBase64String(value); var strDecrypted = Encoding.ASCII.GetString( objDesCrypto.CreateDecryptor().TransformFinalBl

解密密钥时,我遇到错误:

用户代码未处理加密异常。
要解密的数据长度无效

现在我想做的是,我想检查给定的字符串是否能够解密。如果它能够解密,我只想执行下面的代码。这样我就不会出错了

var byteBuff = Convert.FromBase64String(value);
var strDecrypted = Encoding.ASCII.GetString(
                   objDesCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));

有没有办法检查一下

我想接下来的问题可能是:如果它无法解密,您的代码想做什么。无论如何,考虑到这一点,您可以始终使用try…catch,例如:

try { /* your code */ }
catch (CryptographicException e) { /* whatever you need to if it is not able to */ }

我找到了解决办法。必须检查有效的base64字符串:

if ((value.Length % 4 == 0) && Regex.IsMatch(value, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None))
{
    var byteBuff = Convert.FromBase64String(value);
    decryptedString =
        Encoding.ASCII.GetString(
            objDesCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
}

我已经在使用try-catch块。在TryCatch博客中,我们生成了异常日志并发送了一封电子邮件。这是我不想要的。因此,有必要检查字符串是否为有效的base64字符串。我找到了相同问题的解决方案,并用解决方案更新了问题。顺便说一句,谢谢你的建议