Convert.FromBase64String行为异常,附RSA解密代码求助
Convert.FromBase64String Issues in Your RSA Decryption Code Hey, let's figure out why Convert.FromBase64String is acting up with your decrypted content. I'll walk through the most likely problems and how to fix them, based on the code and sample payload you shared.
First, let's recap what your code is doing: you split incoming data into chunks, decrypt each with RSA, concatenate the results into a string sb, then try to convert that Base64 string to bytes—something's breaking here.
Common Culprits & Solutions
Invalid Characters Sneaking Into Your Concatenated String
When you decrypt chunks and mash them together, it's easy to end up with hidden whitespace, null bytes, or weird non-printable characters that Base64 doesn't tolerate. Base64 only accepts A-Z, a-z, 0-9,+,/, and=(for padding). Any other character will throw offConvert.FromBase64String.Fix this by cleaning the string first:
// Strip out any characters that aren't valid Base64 var cleanSb = new string(sb.Where(c => char.IsLetterOrDigit(c) || c == '+' || c == '/' || c == '=').ToArray()); // Now use the cleaned string for conversion var payloadBytes = Convert.FromBase64String(cleanSb);Broken Decryption or Chunk Splitting
If even one chunk fails to decrypt properly (wrong private key, truncated chunk during transmission) or yourSplit('|')is cutting chunks incorrectly, your finalsbwill be invalid Base64.Debug this with a few quick checks:
- Log each individual decrypted chunk before concatenation—make sure each piece looks like part of a valid Base64 string (no garbage characters).
- Double-check that
globals.serverPrivateKeyis correctly loaded (confirm it's in the right format for yourCryptography.RSA.decryptmethod—XML, PEM, etc.). - Verify that the original data doesn't contain any
|characters within chunks (if it does, your delimiter is bad and you'll split content incorrectly).
Missing Base64 Padding
Base64 strings need to be padded to a length divisible by 4 using=characters. If yoursbis missing this padding,Convert.FromBase64Stringmight throw an error or return garbage data.Add padding manually if needed:
int paddingNeeded = sb.Length % 4; if (paddingNeeded != 0) { sb += new string('=', 4 - paddingNeeded); } var payloadBytes = Convert.FromBase64String(sb);Your Payload is GZIP Compressed
The samplesbyou shared starts withH4sI—that's the Base64 representation of GZIP's magic bytes. If you're expecting plain text, you need to decompress it after converting from Base64:var payloadBytes = Convert.FromBase64String(sb); using (var gzipStream = new GZipStream(new MemoryStream(payloadBytes), CompressionMode.Decompress)) using (var reader = new StreamReader(gzipStream)) { var plainText = reader.ReadToEnd(); Debug.Log("Decompressed content: " + plainText); }
Quick Debugging Tips
- Log the length of
sb—valid Base64 strings are always a multiple of 4 (unless padding is missing, which we can fix). - Test with your sample
sbdirectly: hardcode that string and runConvert.FromBase64Stringon it. If it works, the problem is in your decryption or chunk-splitting step, not the conversion itself.var testSb = "H4sIAAAAAAAAAG2MywrCQAxF/yXrUqjuulMXUlwI/kGcibU4L5IUkdJ/N1oXCq4mc+69ZwIXUARayNzXifSaRWuXY8Tkpd6TdkrxRFJyEoIKPpENetLBMmPvp53+qjwq1t3S8ySOh6JDTtZqVusX41zwHAjaCwYhk5m7qSBhNAab7c5KhQdnv6axQBTdbVkojzZQRk8/4FHsXlVwJ+Qv91wBk4xBzXs8wPwEOn1v+/wAAAA="; var testBytes = Convert.FromBase64String(testSb); // This should run without errors—if it does, your decryption flow is the issue
内容的提问来源于stack exchange,提问作者Martin Kørvel

