Question

I know this cannot be as hard as I am making it.. I've built a structure to encode things into Asn1 (using BouncyCastle, C#), no problem.

Trying to extract an integer back out is easy enough (BouncyCastle: (DerInteger) object.Value.IntValue ), but DerOctetStrings doesn't seem to have direct functionality - likely because it can represent ascii strings AND byte[].

So {04 02 46 45} represents both the byte[] { 0x46, 0x45 } and the string "FE"

... and I can't figure out how to get either, short of manually stripping off the tag and using the length to grab the bytes that follow. All the BouncyCastle methods seem to shoot back out all the octets ( 04 02 46 45 ) or encode them again ( 04 06 04 02 46 45 )

I'd really like to stick to BouncyCastle just to keep it parallel to the encoder I wrote, and because it has built-in checking of the length field that throws properly. .NET is fine if I have to go that route and it is easier. And worse case I'll do it all manually but.. that's ugly.

Main question: How do you use built-in functionality to extract the content bytes out of a DerOctetString (without the tag and length)? Secondary question: What is the easiest way to take those output bytes into a normal C# string?

-- Aside: I have only managed to find two posts similar to this on here: How do I decode a DER encoded string in Java? Which goes directly to the string version, can't just grab the bytes out

And BouncyCastle Java - Decoding DER encoded OCTET strings But that only talks about a java library so it doesn't help me

======================================================== Edit: Resolved the main portion of the question. It was the .GetOctets (so accepting that answer), the underlying issue was just an unclear constructor from BouncyCastle.

So to add to that, if anyone wants to feed Asn.1 into BouncyCastle don't use:

DerOctetString(byte[] asn1ByteArray);

use the inherited

Asn1Object.FromByteArray(byte[] asn1ByteArray);

If I figure out the string bit I'll edit again with that solution, though for now I'll just deal with the clearer UTF8 strings

Was it helpful?

Solution

I just use the java version so I am not sure if this helps you in c# but have you tried to get the content of the DEROctetString with getOctets()?

It does exactly what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top