title: Converting EC PublicKey Hex String to PublicKey
body: <p>While performing Elliptic Curve cryptography with <code>secp256k1</code> curve, I noticed that while the code and test cases compile on the Android Studio IDE they do not compile on the android device since the curve isn't defined in the <code>jre/jdk</code> that the mobile device uses. Changing the curve to a <code>prime256v1</code> I seem to be facing difficulties in converting a hex string of the publicKey to <code>PublicKey</code> object.</p>
  
  <p>Given the hex string of a <code>PublicKey.getEncoded()</code> which is in a database. I want an android client to convert the <code>byte[]</code> from converting the <code>hex</code> string into a <code>PublicKey</code> object. I am converting the <code>byte[]</code> using <code>X509EncodedKeySpec()</code> as follows:</p>
  
  <pre><code>public static PublicKey getPublicKey(byte[] pk) throws NoSuchAlgorithmException, InvalidKeySpecException {
      EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pk);
      KeyFactory kf = KeyFactory.getInstance("EC");
      PublicKey pub = kf.generatePublic(publicKeySpec);
      return pub;
  }
  </code></pre>
  
  <p>The conversion from a hex string to a <code>byte[]</code> happens as follows:</p>
  
  <pre><code>public static byte[] hexStringToByteArray(String hexString) {
      byte[] bytes = new byte[hexString.length() / 2];
  
      for(int i = 0; i &lt; hexString.length(); i += 2){
          String sub = hexString.substring(i, i + 2);
          Integer intVal = Integer.parseInt(sub, 16);
          bytes[i / 2] = intVal.byteValue();
          String hex = "".format("0x%x", bytes[i / 2]);
      }
      return bytes;
  }
  </code></pre>
  
  <p>The conversion from a <code>byte[]</code> to Hex string is as follows:</p>
  
  <pre><code>public static String convertBytesToHex(byte[] bytes) {
      char[] hexChars = new char[bytes.length * 2];
      for ( int j = 0; j &lt; bytes.length; j++ ) {
          int v = bytes[j] &amp; 0xFF;
          hexChars[j * 2] = hexArray[v &gt;&gt;&gt; 4];
          hexChars[j * 2 + 1] = hexArray[v &amp; 0x0F];
      }
      return new String(hexChars).toLowerCase();
  }
  </code></pre>
  
  <p>However when I run this on the android app (7.0, API 24) I get the following System Error</p>
  
  <pre><code>W/System.err: java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000b9:ASN.1 encoding routines:OPENSSL_internal:WRONG_TAG
                    at com.android.org.conscrypt.OpenSSLKey.getPublicKey(OpenSSLKey.java:295)
                    at com.android.org.conscrypt.OpenSSLECKeyFactory.engineGeneratePublic(OpenSSLECKeyFactory.java:47)
                    at java.security.KeyFactory.generatePublic(KeyFactory.java:357)
  </code></pre>
  
  <p>What is the recommended approach for converting a Hex string to a PublicKey for EC instance on an android device.</p>
  
  <p>Here's sample code that you can execute:</p>
  
  <h3>ECDSA.java</h3>
  
  <pre><code>public class ECDSA {
  
      public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
          KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
          ECGenParameterSpec ecSpec = new ECGenParameterSpec("prime256v1");
          SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
          keyGen.initialize(ecSpec, random);
          KeyPair pair = keyGen.generateKeyPair();
          return pair;
      }
  
      public static PublicKey getPublicKey(byte[] pk) throws NoSuchAlgorithmException, InvalidKeySpecException {
          EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pk);
          KeyFactory kf = KeyFactory.getInstance("EC");
          PublicKey pub = kf.generatePublic(publicKeySpec);
          return pub;
      }
  
      public static PrivateKey getPrivateKey(byte[] privk) throws NoSuchAlgorithmException, InvalidKeySpecException {
          EncodedKeySpec privateKeySpec = new X509EncodedKeySpec(privk);
          KeyFactory kf = KeyFactory.getInstance("EC");
          PrivateKey privateKey = kf.generatePrivate(privateKeySpec);
          return privateKey;
      }
  }
  </code></pre>
  
  <h3>MainActivity.java</h3>
  
  <pre><code>public class MainActivity extends AppCompatActivity {
  
      KeyPair keyPair = ECDSA.generateKeyPair();
      PublicKey publicKey = keyPair.getPublic();
      PrivateKey privateKey = keyPair.getPrivate();
      // Converting byte[] to Hex
      publicKeyHex = convertBytesToHex(publicKey.getEncoded());
      privateKeyHex = convertBytesToHex(privateKey.getEncoded());
      // Trying to convert Hex to PublicKey/PrivateKey objects
      PublicKey pkReconstructed = ECDSA.getPublicKey(hexStringToByteArray(publicKeyHex));
      PrivateKey skReconstructed = ECDSA.getPrivateKey(hexStringToByteArray(privateKeyHex));
      // This throws an error when running on an android device
      // because there seems to be some library mismatch with 
      // java.security.* vs conscrypt.OpenSSL.* on android.
  }
  </code></pre>