Creating ASN1 encoded signature in C# to send to J

2019-05-16 22:26发布

问题:

I have a private/public secure cert. My Java counterparts have the public key. I have the need to take a string, sign it, and send it along to Java to then verify the data and signature.

There appears to be a well known issue with how Microsoft and the rest of the world encodes/signs data, something about the way bytes are handled. It's so well known, that I can't find a solution. If they take my string and the private key, they can obviously sign it correctly, and verify it. If I take my string, I can sign and verify it within .Net fine. I have seen a slew of methods for converting from ASN1 to Microsoft's format (I think P1363), but not converting from Microsoft, C#, to ASN1 for Java. I don't what is going on well enough to understand how to reverse engineer.

I've explored http://www.codeproject.com/Articles/25487/Cryptographic-Interoperability-Keys but the final result wasn't what the java side needed. I can sign a string, and I get a signature, but Java guys are telling me it needs to start with MC, first bytes are indicators. I am not seeing this.

Thanks!

回答1:

A solution has been found, and looks like some of the other examples I've been seeing, but for some reason this works better: (method named after the guy who solved it for me ;)

            private static byte[] Rays(byte[] sigBytes)
            {
                bool highMsbR = (sigBytes[0] & 0x80) != 0;
                bool highMsbS = (sigBytes[20] & 0x80) != 0;  

                MemoryStream stream = new MemoryStream();
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    writer.Write((byte)0x30);
                    int len = 44 + (highMsbR ? 1 : 0) + (highMsbS ? 1 : 0);
                    writer.Write((byte)len);

                    // r
                    writer.Write((byte)0x02);
                    writer.Write((byte)(highMsbR ? 21 : 20));
                    if (highMsbR)
                        writer.Write((byte)0); 
                    for (int i = 0; i < 20; i++)
                        writer.Write(sigBytes[i]); 

                    // s
                    writer.Write((byte)0x02);
                    writer.Write((byte)(highMsbS ? 21 : 20));
                    if (highMsbS)
                        writer.Write((byte)0);
                    for (int i = 20; i < 40; i++)
                        writer.Write(sigBytes[i]);
                }

                byte[] bytes = stream.ToArray();
                return bytes;
            }