0

我使用以下代码从 bouncycastle 创建 ECC 公钥:

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
keyPairGenerator.initialize(256, new SecureRandom());

KeyPair kp = keyPairGenerator.generateKeyPair();

PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();

String serverPublicKey = Base64.getEncoder().encodeToString(publicKey.getEncoded());

然后我复制公钥并在 iOS 中使用以下代码读取:

NSString *publicKey = @"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWPSEiXPN274aQi0FyG39w05HUu/fVOMlH56SGvCGWRoQ0IcFxJTxBziTHLJ+OC3o+yl7P8h0oz/ChL15hfMbWA==";

StringSource ss(publicKey.UTF8String, true, new CryptoPP::Base64Decoder);

CryptoPP::ECIES<CryptoPP::ECP>::Encryptor encrypto;
encrypto.AccessKey().AccessGroupParameters().Initialize(ASN1::secp256r1());

//get point on the used curve
ECP::Point point;
encrypto.GetKey().GetGroupParameters().GetCurve().DecodePoint(point, ss7, (size_t)ss.MaxRetrievable());

cout << "X: " << std::hex << point.x << endl;
cout << "Y: " << std::hex << point.y << endl;

//set encryptor's public element
encrypto.AccessKey().SetPublicElement(point);

//check whether the encryptor's access key thus formed is valid or not
encrypto.AccessKey().ThrowIfInvalid(prng, 3);
PrintPublicKey(encrypto.GetKey());

我得到错误

libc++abi.dylib:以 CryptoPP::CryptoMaterial::InvalidMaterial 类型的未捕获异常终止: CryptoMaterial:此对象包含无效值

有人可以帮我解决这个问题吗?

4

1 回答 1

0

你应该使用ECGenParameterSpec

private KeyPair generateEcKeyPair() throws InvalidAlgorithmParameterException,
      NoSuchProviderException, NoSuchAlgorithmException {

    KeyPairGenerator kpgen = KeyPairGenerator.getInstance("EC", "BC");
    ECGenParameterSpec spec = new ECGenParameterSpec("secp256r1");
    kpgen.initialize(spec, new SecureRandom());
    return kpgen.generateKeyPair();
  }

那么你的公钥是generateEcKeyPair().getPublic().

于 2020-09-18T15:10:45.497 回答