title: Generating ECPublicKey from byte array
body: <p>I get a 64 uncompressed public key and need to run ECDH to generate a shared secret.
  In order to call ECDH I need to convert the byte array to <code>PublicKey</code> and I am using the following code I have found in this forum:</p>
  
  <pre><code>public static void setOtherPublicKey(byte[] publicKeyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException
  {       
  
      try {
          //EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
          KeyFactory generator = KeyFactory.getInstance("EC");
          //PrivateKey privateKey = generator.generatePrivate(privateKeySpec);
  
          EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
          blePubKey = generator.generatePublic(publicKeySpec);
      } catch (Exception e) {
          throw new IllegalArgumentException("Failed to create KeyPair from provided encoded keys", e);
      }
  }
  </code></pre>
  
  <p>This code throws an <code>InvalidKeySpecException</code>.</p>
  
  <p>As example, the public key of the other party is:</p>
  
  <pre class="lang-none prettyprint-override"><code>9b5e9a5a971877530c9cadbbea93c2ee2483d65052678f745bad79f110173520
  54019832e11376537a76c4defd0b3dfdc667a974239147f323cdcfd2baa39892
  </code></pre>
  
  <p>Adding the code after getting the answers below:</p>
  
  <pre><code>public static void setOtherPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException
  {
      // first generate key pair of your own   
      ECPublicKey pubKey = (ECPublicKey) SecPage.g_kpA.getPublic();
      ECParameterSpec params = pubKey.getParams();
      int keySizeBytes = params.getOrder().bitLength() / Byte.SIZE;
  
      // get the other party 64 bytes
      //byte [] otherPub = crypto.getBlePubKeyBytes();
  
      byte[] otherPub = hexStringToByteArray("ac2bdd28fce5c7b181b34f098b0934742281246ed907a5f646940c1edcb724e7c7358356aebea810322a8e324cc77f376df4cabd754110ad41ec178c0a6b8e5f");
      ByteArrayBuffer xBytes = new ByteArrayBuffer(33);
      ByteArrayBuffer yBytes = new ByteArrayBuffer(33);
  
      byte[] zero = {(byte)0x00};
      xBytes.append(zero, 0, 1);
      xBytes.append(otherPub, 0, 32);
      yBytes.append(zero, 0, 1);
      yBytes.append(otherPub, 32, 32);
  
  
      // generate the public key point    
      BigInteger x = new BigInteger(xBytes.buffer());
      BigInteger y = new BigInteger(yBytes.buffer());
  
      ECPoint w  = new ECPoint(x, y);
  
      // generate the key of the other side
      ECPublicKeySpec otherKeySpec = new ECPublicKeySpec(w  , params);
      KeyFactory keyFactory = KeyFactory.getInstance("EC");
      blePubKey = (ECPublicKey) keyFactory.generatePublic(otherKeySpec);
  }
  </code></pre>