Spongycastle and InvalidKeySpecException

I’m trying to port an app that uses Spongycastle over to iOS, but I’m getting this exception at runtime:

Caused by: java.security.spec.InvalidKeySpecException: Must use ECPrivateKeySpec or PKCS8EncodedKeySpec; was org.spongycastle.jce.spec.ECPrivateKeySpec
	at com.android.org.conscrypt.OpenSSLECKeyFactory.engineGeneratePrivate(OpenSSLECKeyFactory.java:66)
	at java.security.KeyFactory.generatePrivate(KeyFactory.java:187)
        ... (and on)

My dependency tree resolves to this:

compile - Dependencies for source set 'main'.
+--- multi-os-engine:moe-core:1.2.5
+--- multi-os-engine:moe-ios:1.2.5
\--- my.app.library:library
     +--- com.madgag.spongycastle:pkix:
     |    +--- com.madgag.spongycastle:prov:
     |    |    \--- com.madgag.spongycastle:core:
     |    \--- com.madgag.spongycastle:core:
     +--- com.madgag.spongycastle:prov: (*)
     \--- org.slf4j:slf4j-api:1.7.21

Where ‘my.app.library:library’ is a lib I’ve built. I’m explicitly excluding bouncycastle in my build.gradle file.

Has anyone else had success using Spongycastle in MOE?

Can you provide a test project that can be used to reproduce this issue?

I investigated and found that it’s because Spongycastle uses ClassLoader.loadClass to load its algorithms, but I understand MOE has a known limitation with respect to loading classes dynamically from the classpath at runtime. Spongycastle couldn’t find everything it should have been able to, meaning the system was falling back on the default security provider from the standard library (and thus giving the above exception).

To resolve this, I created my own implementation of the BouncyCastleProvider that extends java.security.Provider and explicitly calls ‘new’ on the algorithm I wanted. I inserted this using the following code (which is the same code that is used to put SpongyCastle into the list of providers on Android devices):

static {
    Security.insertProviderAt(new MOEBouncyCastleProvider(), 1);

Thank you for confirming that SpongyCastle can work with MOE.

MOE is using Android ART internally, so in general you can expect the same runtime features and limitations as on Android.