在使用crypto ++时,如何读取从Java bouncycastle生成的ECC公共密钥

问题描述

我用以下代码从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类型:此对象包含无效值

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

解决方法

您应该使用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()