Cryptography newbie here... I'm trying to do 128-bit encryption using BouncyCastle with the code below.
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSEnvelopedDataStreamGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Test {
public static void main(String[] args) throws Throwable {
Security.addProvider(new BouncyCastleProvider());
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream keyStoreFile = new FileInputStream("test.p12");
try {
keyStore.load(keyStoreFile, "test12".toCharArray());
} finally {
keyStoreFile.close();
}
X509Certificate certificate = (X509Certificate) keyStore
.getCertificate(keyStore.aliases().nextElement());
OutputStream output = new BufferedOutputStream(new FileOutputStream(
"test.out"));
try {
InputStream input = new FileInputStream("test.in");
try {
CMSEnvelopedDataStreamGenerator generator = new CMSEnvelopedDataStreamGenerator();
generator.addKeyTransRecipient(certificate);
OutputStream encryptedOutput = generator.open(output,
CMSEnvelopedDataGenerator.AES128_WRAP, 128,
BouncyCastleProvider.PROVIDER_NAME);
try {
IOUtils.copy(input, encryptedOutput);
} finally {
encryptedOutput.close();
}
} finally {
input.close();
}
} finally {
output.close();
}
}
}
But I get this error:
Exception in thread "main" org.bouncycastle.cms.CMSException: key inappropriate for algorithm.
at org.bouncycastle.cms.CMSEnvelopedDataStreamGenerator.open(Unknown Source)
at org.bouncycastle.cms.CMSEnvelopedDataStreamGenerator.open(Unknown Source)
at org.bouncycastle.cms.CMSEnvelopedDataStreamGenerator.open(Unknown Source)
at hk.gov.gld.etb.uploading.pkcs7.Test.main(Test.java:45)
Caused by: java.security.InvalidKeyException: Illegal key size or default parameters
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at org.bouncycastle.cms.CMSEnvelopedGenerator$RecipientInf.toRecipientInfo(Unknown Source)
... 4 more
The certificate I used was generated using the JDK's keytool program as follows:
keytool -genkeypair -dname "cn=test" -alias test -keystore test.p12 -storepass test12 -validity 180 -storetype pkcs12 -keyalg rsa
The JDK version I use is 6 and the BouncyCastle version I used is 141.
Am I doing it the right way? Do I still need to install the unlimited strength policy files to do 128-bit encryption?
Help is very much appreciated.
Thanks!