gpt4 book ai didi

java - RC4 算法的 KeyGenerator 异常

转载 作者:行者123 更新时间:2023-11-30 06:31:07 31 4
gpt4 key购买 nike

代码非常简单明了,但是在

处抛出了异常
KeyGenerator keyGen = KeyGenerator.getInstance("RC4");

Cipher aesCipher = Cipher.getInstance("RC4");

异常(exception)是:未报告的异常 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);
}

}
}

最佳答案

代码可以正常工作,就目前而言,您只需要再添加一个 catch 即可捕获 NoSuchAlgorithmException - 这永远不会出现在您的程序中。

因为算法名称作为字符串传递,方法 getInstance() 可能会在名称错误时抛出 NoSuchAlgorithmException。它只是不知道如何处理未知算法。这不是你的情况,但编译器必须确保满意。

关于java - RC4 算法的 KeyGenerator 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9907052/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com