1

I have a very large prime number (for RSA purposes) that needs to be converted to a byte array. The number however is currently stored as a string. I'm OK with storing it as a byte[] but either way the number is a string and I have to get it into a byte array.

Now to be clear I have used the RSA encryption and decryption sample data provided on MSDN and everything works so I have a high degree of confidence that the encryption portion is fine. Further the samples provided by MSDN provide prime numbers that have already been turned into byte[]. Thus I have a high degree of confidence that the breakdown is in MY conversion of the string representation of the number to a byte[].

I currently do this:

private static string _publicKeyExponent = "12345...310 digits......9876";
private static string _publicKeyModulus = "654782....620 digits.....4576";

_rsaPublicKey.Exponent = CoreHelpers.GetBytes(_publicKeyExponent);

And here is my GetBytes method that I suspect is causing the issue as it is getting the bytes of STRING characters NOT digits.

    public static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

Now if I have already identified the problem fixing should be straight forward no? Well for me yes and no. I don't know of any strong type in c# that I can parse a number of this size into. The best idea I can come up with is to break up the string into smaller chunks of say 10 chars which would then easily parse to INT32 and then getbytes of that. Add it to some master byte array and do it again.

3
  • 1
    Why not use the BigInteger struct? It contains the Parse and the ToByteArray methods. Commented Nov 12, 2014 at 17:09
  • The problem is that you're copying the digits' character codes into your byte array, not the numeric value of the number. You should specify what output format you need (endianness etc). Commented Nov 12, 2014 at 17:11
  • @Dmitry PERFECT....Like I said in the OP. I don't know of a type but now thanks to you I do. Make it an answer and I will gladly accept. Commented Nov 12, 2014 at 17:13

1 Answer 1

2

You could use the BigInteger struct.
It contains numerous Parse static methods and the ToByteArray method.
Sample code:

public static byte[] GetBytes(string str)
{
    BigInteger number;
    return BigInteger.TryParse(str, out number) ? number.ToByteArray() : null;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.