'flexiprovider conflicts with bouncycastle when retrieving keys from string
I have been using a solution, provided in bellow, to encrypt/decrypt using Flexiprovider for a while. The solution works on galaxy s5 and s6. However, in s9 it does not work because it conflicts with BouncyCastle. The code that works in s5 and s6:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECIES", "FlexiEC");
CurveParams ecParams = new CurveRegistry.BrainpoolP512r1();
kpg.initialize(ecParams, new SecureRandom());
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pubKey = keyPair.getPublic();
PrivateKey privKey = keyPair.getPrivate();
String STRpubKey = Base64.encodeToString(pubKey.getEncoded(),
Base64.DEFAULT);
byte[] decodedPublicKey = Base64.decode(STRpubKey, Base64.DEFAULT);
X509EncodedKeySpec X509spec = new X509EncodedKeySpec(decodedPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance("ECIES","FlexiEC");
PublicKey pubkey = keyFactory.generatePublic(X509spec);
The above code gives the following error in s9:
java.lang.RuntimeException: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.org.bouncycastle.math.ec.ECCurve com.android.org.bouncycastle.asn1.x9.X9ECParameters.getCurve()' on a null object reference
The exception happens here:
PublicKey pubkey = keyFactory.generatePublic(X509spec);
Solution 1:[1]
This problem is caused by the lack of support for that Brainpool curve in the Android-supplied "BC" provider. One fix is to remove the Android-supplied BC provider and install your own copy of BC provider that does support these curves. For example, I added a jar dependency on the latest bouncycastle jar bcprov-jdk15on-161.jar
to my Android Studio project and added the following lines of code prior to executing your example code:
Security.removeProvider("BC");
Security.addProvider(new BouncyCastleProvider());
Security.addProvider(new FlexiECProvider());
And the code ran without throwing an exception. You might also consider using a less obscure curve, like secp256r1
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | President James K. Polk |