将 EC PublicKey 十六进制字符串转换为 PublicKey

Converting EC PublicKey Hex String to PublicKey

在使用 secp256k1 曲线执行椭圆曲线加密时,我注意到虽然代码和测试用例在 Android Studio IDE 上编译,但它们不会在 [=49] 上编译=] 设备,因为曲线未在移动设备使用的 jre/jdk 中定义。将曲线更改为 prime256v1 我似乎在将 publicKey 的十六进制字符串转换为 PublicKey 对象时遇到困难。

给定数据库中 PublicKey.getEncoded() 的十六进制字符串。我希望 android 客户端将 byte[]hex 字符串转换为 PublicKey 对象。我正在使用 X509EncodedKeySpec() 转换 byte[],如下所示:

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;
}

从十六进制字符串到 byte[] 的转换如下:

public static byte[] hexStringToByteArray(String hexString) {
    byte[] bytes = new byte[hexString.length() / 2];

    for(int i = 0; i < 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;
}

byte[]到十六进制字符串的转换如下:

public static String convertBytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars).toLowerCase();
}

然而,当我在 android 应用程序(7.0,API 24)上 运行 时,出现以下系统错误

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)

在 android 设备上将十六进制字符串转换为 EC 实例的公钥的推荐方法是什么。

这是您可以执行的示例代码:

ECDSA.java

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;
    }
}

MainActivity.java

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.
}

最后 我们得到了一个真正的 MCVE,我们现在可以看到您没有使用正确的 class 来编码私钥。 X509EncodedKeySpec 仅适用于 public 键。来自 javadocs(强调我的):

This class represents the ASN.1 encoding of a public key, encoded according to the ASN.1 type SubjectPublicKeyInfo.

对于私钥,正确的编码通常是PKCS8EncodedKeySpec。可以通过检查 Key.getFormat() 的输出来确定编码。因此,将 ECDSA 的方法 getPrivateKey 更改为

public static PrivateKey getPrivateKey(byte[] privk) throws NoSuchAlgorithmException, InvalidKeySpecException {
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privk);
        KeyFactory kf = KeyFactory.getInstance("EC");
        PrivateKey privateKey = kf.generatePrivate(privateKeySpec);
        return privateKey;
    }