javaandroidnativescriptjava-security

java.security.KeyPairGenerator: Can't set .setDigests() and invalid private key


I'm currently developing an Android app using Nativescript-Vue, where I want to generate a private key to sign payloads.

  const KPGen = java.security.KeyPairGenerator;
  const keyP = android.security.keystore.KeyProperties;

  const kpg = KPGen.getInstance(keyP.KEY_ALGORITHM_EC, "AndroidKeyStore");
  const builder = new android.security.keystore.KeyGenParameterSpec.Builder(
      "key1", keyP.PURPOSE_SIGN)
      .setAlgorithmParameterSpec(new java.security.spec.ECGenParameterSpec("secp256r1"))
      .setDigests(keyP.DIGEST_SHA256)
  kpg.initialize(builder.build());
  const kp = kpg.generateKeyPair();

If I keep the .setDigests(keyP.DIGEST_SHA256) the app will throw an error: Error: java.lang.Exception: Failed resolving method setDigests on class android.security.keystore.KeyGenParameterSpec$Builder.

However, if I comment out the line .setDigests(keyP.DIGEST_SHA256), then I get an Error: java.security.InvalidKeyException: Keystore operation failed when I try to initialize the signing on a signature

  const sig = java.security.Signature.getInstance('SHA256withECDSA');
  sig.initSign(kp.getPrivate());

I'm not sure whether these two problems are related, but does anyone know what currently goes wrong?

I'm following the example on: https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec


Solution

  • If you go to the Java Security Documentation, it says that the function setDigests() takes an array of digest types, not comma separated parameters. The example given in the guide you posted has an error in it.