我正在创建一个生成密钥对的方法。我需要使用密码保护私钥。我的代码工作正常,除了它给我java.security.InvalidKeyException:非法密钥大小或默认参数错误。当我搜索错误的原因时,它说要用jre / lib / security文件夹替换相同的无限访问文件中的策略jar。我安装了jdk7并且我下载了策略文件并替换了lib / security文件夹。但错误仍然相同。这就是代码。
// generate a key pair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512, Utils.createFixedRandom());
KeyPair pair = kpg.generateKeyPair();
for (Object obj : java.security.Security.getAlgorithms("Cipher")) {
System.out.println(obj);
}
// wrapping step
char[] password = "hello".toCharArray();
byte[] salt = new byte[20];
int iCount = 100;
String pbeAlgorithm = "PBEWITHMD5ANDTRIPLEDES";
PBEKeySpec pbeKeySpec = new PBEKeySpec(password, salt, iCount);
SecretKeyFactory secretKeyFact = SecretKeyFactory.getInstance(pbeAlgorithm/*, "BC"*/);
Cipher cipher = Cipher.getInstance(pbeAlgorithm/*, "BC"*/);
cipher.init(Cipher.WRAP_MODE, secretKeyFact.generateSecret(pbeKeySpec));
byte[] wrappedKey = cipher.wrap(pair.getPrivate());
// System.out.println(ASN1Dump.dumpAsString(new ASN1InputStream(cipher.getParameters().getEncoded()).readObject()));
// create carrier
EncryptedPrivateKeyInfo pInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(), wrappedKey);
// unwrapping step - note we only use the password
pbeKeySpec = new PBEKeySpec(password);
cipher = Cipher.getInstance(pInfo.getAlgName()/*, "BC"*/);
cipher.init(Cipher.DECRYPT_MODE, secretKeyFact.generateSecret(pbeKeySpec), pInfo.getAlgParameters());
PKCS8EncodedKeySpec pkcs8Spec = pInfo.getKeySpec(cipher);
KeyFactory keyFact = KeyFactory.getInstance("RSA"/*, "BC"*/);
PrivateKey privKey = keyFact.generatePrivate(pkcs8Spec);
ASN1InputStream aIn = new ASN1InputStream(pkcs8Spec.getEncoded());
PrivateKeyInfo info = PrivateKeyInfo.getInstance(aIn.readObject());
System.out.println(ASN1Dump.dumpAsString(info));
System.out.println(ASN1Dump.dumpAsString(info.getPrivateKey()));
if (privKey.equals(pair.getPrivate()))
{
System.out.println("key recovery successful");
}
else
{
System.out.println("key recovery failed");
}
先谢谢。