ElGamal加密算法异常
public static final String bcElGamal(String sourceChars) {
// 公钥加密,私钥解密
Security.addProvider(new BouncyCastleProvider());
try {
// 初始化密钥
AlgorithmParameterGenerator algorithmParameterGenerator
= AlgorithmParameterGenerator.getInstance("ElGamal");
algorithmParameterGenerator.init(256);
AlgorithmParameters algorithmParameters
= algorithmParameterGenerator.generateParameters();
DHParameterSpec dhParameterSpec
= algorithmParameters.getParameterSpec(DHParameterSpec.class);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ElGamal");
keyPairGenerator.initialize(dhParameterSpec, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey elGamalPublicKey = keyPair.getPublic();
PrivateKey elGamalPriveKey = keyPair.getPrivate();
System.out.println("Public key :" + Base64.encodeBase64String(elGamalPublicKey.getEncoded()));
System.out.println("Private key :" + Base64.encodeBase64String(elGamalPriveKey.getEncoded()));
// 公钥加密,私钥解密——加密
X509EncodedKeySpec x509EncodedKeySpec
= new X509EncodedKeySpec(elGamalPublicKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("ElGamal");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Cipher cipher = Cipher.getInstance("ElGamal");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(sourceChars.getBytes());
System.out.println("bc elGamal encrypt :" + Base64.encodeBase64String(result));
// 公钥加密,私钥解密——解密
PKCS8EncodedKeySpec pKCS8EncodedKeySpec
= new PKCS8EncodedKeySpec(elGamalPriveKey.getEncoded());
keyFactory = KeyFactory.getInstance("ElGamal");
PrivateKey privateKey = keyFactory.generatePrivate(pKCS8EncodedKeySpec);
cipher = Cipher.getInstance("ElGamal");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
result = cipher.doFinal(result);
System.out.println("bc elGamal decrypt :" + new String(result));
return null;
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
} catch (IllegalStateException ex) {
throw new RuntimeException(ex);
} catch (InvalidParameterSpecException ex) {
throw new RuntimeException(ex);
} catch (InvalidAlgorithmParameterException ex) {
throw new RuntimeException(ex);
} catch (InvalidKeyException ex) {
throw new RuntimeException(ex);
} catch (NoSuchPaddingException ex) {
throw new RuntimeException(ex);
} catch (IllegalBlockSizeException ex) {
throw new RuntimeException(ex);
} catch (BadPaddingException ex) {
throw new RuntimeException(ex);
} catch (InvalidKeySpecException ex) {
throw new RuntimeException(ex);
}
}
此方法一直抛出异常:java.security.InvalidKeyException: Illegal key size or default parameters