how to read an ECC public key which had been generated from java bouncycastle when using crypto++

239 views Asked by At

I create an ECC public key from bouncycastle with below code:

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());

then I copy the public key and read using below code in 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());

I get the error

libc++abi.dylib: terminating with uncaught exception of type CryptoPP::CryptoMaterial::InvalidMaterial: CryptoMaterial: this object contains invalid values

could anyone help me for this issue?

1

There are 1 answers

0
kabayaba On

You should use 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();
  }

Then your public key is generateEcKeyPair().getPublic().