1

Well guys I am trying to encrypt (actually sign) data using Public and Private exponent and modulus, It is in C#.NET and I can't use RSACryptoServiceProvider because it needs also both prime numbers and other CRT stuff.

So I am trying to do following:

private Byte[] signData()
{
  BigInteger biPrivEx = new BigInteger(this.privEx); // Those are byte[]
  BigInteger biPubEx = new BigInteger(this.pubEx);
  BigInteger biMod = new BigInteger(this.mod);          

  BigInteger cyph = BigInteger.ModPow(new BigInteger(pkcs11), biPrivEx, biMod); // This raise exception

  return cyph.ToByteArray();;
}

But the problem is I am getting Out Of Range Exception because my private exponent is negative number.

What am I doing wrong? Or is possible to easily recovery CRT from this? Or maybe is there any better way how to do it? In different program I am able to this with data I am using, so I have got reference to verify it.

Johny
  • 13
  • 3

1 Answers1

1

The problem is that you got a negative private exponent in the first place. Depending on how you got this broken exponent try:

  1. Adding n to it
  2. Concating a 00 byte to the array, to make it parse correctly.

You should also be careful about endianness issues. .net's BigInteger uses little endian, other binary formats might use big endian.


Try:

BigInteger ParseBinaryLE(byte[] raw)
{
   return new BigInteger(raw.Concat(new byte[]{0}).ToArray());
}

BigInteger ParseBinaryBE(byte[] raw)
{
   return new BigInteger(raw.Reverse().Concat(new byte[]{0}).ToArray());
}

AFAIK it is also possible to recover P and Q (and from those the rest of the parameters) when you know e, d and n.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • My input looks like `Byte[] PrivateEx = StringToByteArray("FFAABBCC`)` (just example) and I do not think it is negative, there is no minus sing anywhere. May this be caused by BigInteger? – Johny Feb 24 '12 at 12:15
  • @Johny BigInteger assumes the last bit is a sign bit. So you need to append `00`. You might also need to reverse the array first. I've added two candidate functions. – CodesInChaos Feb 24 '12 at 12:16
  • Okay, no it finally calculate, but result is still wrong, anyway why it might be necessary to reverse array? – Johny Feb 24 '12 at 12:32
  • @Johny if the binary key was big-endian, you need to reverse it, so `BigInteger` which assumed little-endian reads it correctly. – CodesInChaos Feb 24 '12 at 13:18