SpiderCode
SpiderCode

Reputation: 10122

CryptographicException was unhandled by user code

While Decrypting Key I am getting error :

CryptographicException was unhandled by user code.
Length of the data to decrypt is invalid.

Now what I want to do is, I want to check whether the given string is able to decrypt or not. If it is able to decrypt than only I want to execute below code. So that I cannot get an error.

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

Is there any way to check it ?

Upvotes: 2

Views: 1439

Answers (2)

SpiderCode
SpiderCode

Reputation: 10122

I found Solution. Have to check for valid base64 string :

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));
}

Upvotes: 0

slepox
slepox

Reputation: 812

I think a followed question could be: if it is not able to decrypt, what does your code want to do. Anyway with that considered, you can always use try...catch like:

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

Upvotes: 1

Related Questions