返回

掌握便捷方法, 轻松获取33-bytes Compressed Public Key

Android

轻松获取 Android 和 iOS 设备的 33 字节压缩公钥,解决签名验证难题

困扰已久的难题

在使用 P-256 对 API 请求进行签名并由服务器端进行验证时,开发者经常面临一个难题:如何在 Android 和 iOS 设备上从 KeyPair 和 SecKeyCopyExternalRepresentation 中便捷地获取 33 字节压缩公钥。这篇文章将提供一个简洁明了的解决方案,让你轻松解决这一难题。

Android 和 iOS 上的 ECDSA 公钥压缩

要在 Android KeyStore 和 iOS Secure Enclave 中使用 ECDSA 签名,我们需要将公钥转换为压缩公钥格式。Android 和 iOS 都提供了一些方法来执行此操作。

Android 上获取压缩公钥

  1. 从 KeyPair 中提取公钥:
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyPair.getPublic();
byte[] publicKeyBytes = publicKey.getEncoded();
  1. 将公钥转换为压缩公钥:
byte[] compressedPublicKey = new byte[33];
compressedPublicKey[0] = (byte) 0x02 | (publicKeyBytes[64] & 0x01);
System.arraycopy(publicKeyBytes, 1, 32, compressedPublicKey, 1, 32);

iOS 上获取压缩公钥

  1. 从 SecKeyCopyExternalRepresentation 获取公钥:
CFDataRef publicKeyData = SecKeyCopyExternalRepresentation(publicKey, NULL);
const unsigned char *publicKeyBytes = CFDataGetBytePtr(publicKeyData);
  1. 将公钥转换为压缩公钥:
byte[] compressedPublicKey = new byte[33];
compressedPublicKey[0] = (byte) 0x02 | (publicKeyBytes[64] & 0x01);
System.arraycopy(publicKeyBytes, 1, 32, compressedPublicKey, 1, 32);

验证压缩公钥

获取压缩公钥后,你可以使用以下代码验证签名:

Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initVerify(publicKey);
signature.update(message);
boolean isValid = signature.verify(signatureBytes);

示例代码

为了更深入地了解,我们提供了详细的示例代码,展示了如何在 Android 和 iOS 上获取压缩公钥。

Android 示例代码

iOS 示例代码

常见问题解答

  1. 为什么需要压缩公钥?

压缩公钥可以减少存储和传输大小,同时保持验证的安全性。

  1. 如何知道我的公钥是否已正确压缩?

验证压缩公钥的长度是否为 33 字节,并且第一个字节以 0x02 或 0x03 开头。

  1. 我是否可以使用其他算法来压缩公钥?

目前,ECDSA 签名通常使用压缩公钥格式。

  1. 我可以在哪些其他场景中使用压缩公钥?

压缩公钥广泛用于数字签名、加密和身份验证方案。

  1. 在哪些平台上可以使用这种方法?

本文中介绍的方法适用于 Android 和 iOS 设备。

结语

希望这篇文章让你对如何在 Android 和 iOS 设备上获取 33 字节压缩公钥有了更深入的了解。通过遵循这些步骤,你可以轻松解决困扰已久的签名验证难题,并增强应用程序的安全性。如果你还有任何问题,请随时给我们留言或发送邮件,我们将竭诚为你解答。