这里的密码学新手......我正在尝试使用BouncyCastle进行128位加密,代码如下。
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();
}
}
}
但是我收到了这个错误:
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
我使用的证书是使用JDK的keytool程序生成的,如下所示:
keytool -genkeypair -dname "cn=test" -alias test -keystore test.p12 -storepass test12 -validity 180 -storetype pkcs12 -keyalg rsa
我使用的JDK版本是6,我使用的BouncyCastle版本是141。
我是以正确的方式做到的吗?我是否仍需要安装无限强度策略文件来进行128位加密?
非常感谢帮助。
谢谢!
答案 0 :(得分:3)
我相信 - 你需要US_export_policy.jar和local_policy.jar。我们需要在项目中做同样的事情,并修复它。
我认为生成和使用的密钥应该没问题,否则。将这两个罐子添加到jre / lib / security中,这应该会立即解决你的问题。
答案 1 :(得分:3)
似乎BouncyCastle库的141版有错误。当我升级到最新版本(143)时,完全相同的代码工作。