I'm trying to sign a String in PKCS#7 format with SpongyCastle (using these dependencies "com.madgag.spongycastle:core:1.58.0.0"
and
"com.madgag.spongycastle:pkix:1.54.0.0"
) in Android.
Here is my key pair generation code:
KeyPairGenerator keyPairGenerator;
try {
Calendar start = GregorianCalendar.getInstance();
Calendar end = GregorianCalendar.getInstance();
end.add(Calendar.YEAR, 10);
keyPairGenerator = KeyPairGenerator.getInstance("RSA", ANDROID_KEY_STORE);
keyPairGenerator.initialize(new KeyPairGeneratorSpec.Builder(context)
.setAlias(ALIAS)
.setSerialNumber(BigInteger.valueOf(1))
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.setSubject(new X500Principal(""))
.build());
keyPairGenerator.generateKeyPair();
} catch (Exception e) {
try {
throw e;
} catch (InvalidAlgorithmParameterException ex) {
ex.printStackTrace();
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
} catch (NoSuchProviderException ex) {
ex.printStackTrace();
}
}
and copied signing code from solution provided here :
CMSSignedDataGenerator setUpProvider(final KeyStore keystore) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Certificate[] certchain = keystore.getCertificateChain(ALIAS);
final List<Certificate> certlist = new ArrayList<>();
for (int i = 0, length = certchain == null ? 0 : certchain.length; i < length; i++) {
certlist.add(certchain[i]);
}
Store certstore = new JcaCertStore(certlist);
Certificate cert = keystore.getCertificate(ALIAS);
ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").
build((PrivateKey) (keystore.getKey(ALIAS, null)));
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").
build()).build(signer, (X509Certificate) cert));
generator.addCertificates(certstore);
return generator;
}
but I'm getting cannot create signer: no such algorithm: SHA1WITHRSA for provider BC
exception.
any hints or sloutions?
There's no need to setProvider("BC")
. It doesn't crash after removing setProvider("BC")
from both JcaContentSignerBuilder
and JcaDigestCalculatorProviderBuilder