代码非常简单和清晰,但它在
KeyGenerator keyGen = KeyGenerator.getInstance("RC4");和
Cipher aesCipher = Cipher.getInstance("RC4");异常是:未报告的异常java.security.NoSuchAlgorithmException;必须被捕获或声明为抛出
import java.io.*;
import java.security.*;
import javax.crypto.*;
import sun.misc.BASE64Encoder;
public class RCCC4 {
public static void main(String[] args) {
String strDataToEncrypt = new String();
String strCipherText = new String();
String strDecryptedText = new String();
try{
KeyGenerator keyGen = KeyGenerator.getInstance("RC4");
SecretKey secretKey = keyGen.generateKey();
Cipher aesCipher = Cipher.getInstance("RC4");
aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
strDataToEncrypt = "Hello World of Encryption using RC4 ";
byte[] byteDataToEncrypt = strDataToEncrypt.getBytes();
byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
strCipherText = new BASE64Encoder().encode(byteCipherText);
System.out.println("Cipher Text generated using RC4 is " +strCipherText);
aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters());
byte[] byteDecryptedText = aesCipher.doFinal(byteCipherText);
strDecryptedText = new String(byteDecryptedText);
System.out.println(" Decrypted Text message is " +strDecryptedText);
}
catch (NoSuchPaddingException noSuchPad)
{
System.out.println(" No Such Padding exists " + noSuchPad);
}
catch (InvalidKeyException invalidKey)
{
System.out.println(" Invalid Key " + invalidKey);
}
catch (BadPaddingException badPadding)
{
System.out.println(" Bad Padding " + badPadding);
}
catch (IllegalBlockSizeException illegalBlockSize)
{
System.out.println(" Illegal Block Size " + illegalBlockSize);
}
catch (InvalidAlgorithmParameterException invalidParam)
{
System.out.println(" Invalid Parameter " + invalidParam);
}
}
}发布于 2012-03-28 20:15:41
代码运行良好,你只需要再添加一个catch来捕获NoSuchAlgorithmException --这在你的程序中是不会发生的。
因为算法名称是作为字符串传递的,所以当名称错误时,方法getInstance()可能会抛出NoSuchAlgorithmException。它只是不知道如何处理未知的算法。这不是您的情况,但编译器必须确保令人满意。
发布于 2012-03-28 20:06:20
实际上,跟随this link会告诉您KeyGenerator确实支持RC4,但是指定"ARCFOUR“作为算法名称
发布于 2012-03-28 20:13:14
尝试使用ARCFOUR而不是RC4 documentation is here
https://stackoverflow.com/questions/9907052
复制相似问题