title: Web3j ECKeyPair to KeyPair
body: <p>I'm trying to make an ECC with the generated key using web3j. I have the <a href="https://github.com/web3j/web3j/blob/master/crypto/src/main/java/org/web3j/crypto/ECKeyPair.java" rel="nofollow noreferrer">ECKeyPair</a> object, but <code>cipher.init()</code> requires 2nd parameter to be <code>Key</code> object. <a href="https://github.com/web3j/web3j/blob/master/crypto/src/main/java/org/web3j/crypto/ECKeyPair.java" rel="nofollow noreferrer">ECKeyPair</a> returns <code>BigInteger</code> of private key and public key, how can I convert them to <code>KeyPair</code> which holds <code>PrivateKey</code> and <code>PublicKey</code> object?</p>
  
  <p>I've tried (reference: <a href="https://www.programcreek.com/java-api-examples/?code=papyrusglobal/state-channels/state-channels-master/channel-node/src/main/java/papyrus/channel/node/server/ethereum/CryptoUtil.java" rel="nofollow noreferrer">CryptoUtil.java</a>):</p>
  
  <pre><code>private fun decodeKeyPair(ecKeyPair: ECKeyPair): KeyPair {
          val xp = getNamedCurveByName("secp256k1")
          val p = ECNamedCurveSpec("secp256k1", xp.curve, xp.g, xp.n, xp.h, null)
          val curve = convertCurve(p.curve)
          val g = EC5Util.convertPoint(curve, p.generator, false)
          val n = p.order
          val h = BigInteger.valueOf(p.cofactor.toLong())
          val dp = ECDomainParameters(curve, g, n, h)
  
          val bytes = Numeric.toBytesPadded(ecKeyPair.publicKey, 64)
          val x = Numeric.toBigInt(Arrays.copyOfRange(bytes, 0, 32))
          val y = Numeric.toBigInt(Arrays.copyOfRange(bytes, 32, 64))
          val q = curve.createPoint(x, y)
          val publicKey = BCECPublicKey(
             "EC",
              ECPublicKeyParameters(q, dp),
              BouncyCastleProvider.CONFIGURATION
          )
          val privateKey = BCECPrivateKey(
              "EC",
              ECPrivateKeyParameters(ecKeyPair.privateKey, dp),
              publicKey,
              p,
              BouncyCastleProvider.CONFIGURATION
          )
          return KeyPair(publicKey, privateKey)
      }
  </code></pre>
  
  <p>but this returns an error:
  <code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.bouncycastle.math.ec.ECCurve org.bouncycastle.jce.spec.ECParameterSpec.getCurve()' on a null object reference</code></p>
  
  <p>Is there any other way to convert Web3j <a href="https://github.com/web3j/web3j/blob/master/crypto/src/main/java/org/web3j/crypto/ECKeyPair.java" rel="nofollow noreferrer">ECKeyPair</a> to <code>KeyPair</code>?</p>