'Fast checking for encrypted values by X509Certificate2

I have many different string values in a collection.

Some values were encrypted by X509Certificate2. All other values are numbers, non encrypted strings, dates, etc.

My goal to filter possible candidates for decryption. So I want to use a function that can implement first fast filtration of values that were encrypted.

I use this simple check:

private bool IsEncryptedValue(string value)
{
    var result = !string.IsNullOrEmpty(value) && IsBase64String(value);
    return result;
}

Please advise more correct (more strong) rules for checking encrypted value.

Thanks for any suggestions.



Solution 1:[1]

Ciphertext of any modern cipher is binary. If the ciphertext is in a string I would expect that it has been encoded using base 64 (or a dialect) or hexadecimals. Once you've decoded that it should be exactly be the key size if direct RSA encryption has been used. If a hybrid cryptosystem has been used then it should be at least the key size.

Of course, you will have to find out which RSA encryption scheme was used, and in the case of hybrid encryption you'd have to find out which symmetric encryption scheme was used as well. It might be that the encryption uses a known container format such as CMS or PGP, so you could scan for that as well.

Finally, although it is unlikely: in principle the outcome of RSA encryption is a number. If that number is stored in decimals then it should have keysize / 3.32192809 or fewer digits.


In principle the outcome of a cipher is randomized, so we don't have much to separate it from any other encoding. You can try and validate that it is randomized, but if you've only a small ciphertext then estimating the amount of randomness is relatively tricky - so I've not included that in my answer.

This is a strange endeavor though, generally you'd know if something is a ciphertext or not.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maarten Bodewes