-1

I used -13 as private key in bitcoin but the private key is not valid. How can I get the positive private key from -13 or any other negative numbers using Bitcoinj or java and generate the same address?

val params = MainNetParams.get()

val b = BigInteger("-13")
val key = ECKey.fromPrivate(b, false)
println(LegacyAddress.fromKey(params, key)) // 122Vo9PeKd4j8zSGBeQHdmks6GnkpycXNz
Mehranjp73
  • 341
  • 6
  • 20
  • Short answer: take the integer mod the order of group generated by the base point. Shorter answer: add `0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141` to it. – President James K. Polk Sep 14 '21 at 15:54
  • I don't get the math. Is it works for every negative number or just for -13? Can you please provide me with Java code? – Mehranjp73 Sep 14 '21 at 15:59
  • 1
    First of all, it's completely unclear why you even have a negative number to begin with. But it works with any integer. `b.mod(new BigInteger("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16));` should give you the answer you seek, if I understand you correctly. – President James K. Polk Sep 14 '21 at 16:02
  • These magical constants are taken from the [SECG paper, section 2.7.1](https://www.secg.org/SEC2-Ver-1.0.pdf) – President James K. Polk Sep 14 '21 at 16:03
  • A complete tutorial on elliptic curve cryptography is off-topic here. There are a lot of off-site tutorials available however. – President James K. Polk Sep 14 '21 at 16:07
  • Thanks a lot. It works. I don't need to understand how the whole thing works for now, I'll come back to it when I'm good in math in the future. I just needed the code. You commented the answer, if you want you can post it so I can accept it. – Mehranjp73 Sep 14 '21 at 16:13
  • 1
    These are operations on groups of numbers, which are mapped to ranges such as [0..N). So say that N = 17 then -13 is equivalent to 4 as `-13 mod 17 = 4`. James just posted a *slightly larger value* for N, specific to the curve seck256r1 used by BitCoin :P – Maarten Bodewes Sep 14 '21 at 22:28

1 Answers1

-1
b.mod(new BigInteger("115792089237316195423570985008687907852837564279074904382605163141518161494337"))

Thanks to president-james-k-polk in the comments

Mehranjp73
  • 341
  • 6
  • 20