首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RC4算法的KeyGenerator异常

RC4算法的KeyGenerator异常
EN

Stack Overflow用户
提问于 2012-03-28 20:00:37
回答 5查看 4.6K关注 0票数 2

代码非常简单和清晰,但它在

代码语言:javascript
复制
KeyGenerator keyGen = KeyGenerator.getInstance("RC4");

代码语言:javascript
复制
Cipher aesCipher = Cipher.getInstance("RC4");

异常是:未报告的异常java.security.NoSuchAlgorithmException;必须被捕获或声明为抛出

代码语言:javascript
复制
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);
        }

}
   }
EN

回答 5

Stack Overflow用户

发布于 2012-03-28 20:15:41

代码运行良好,你只需要再添加一个catch来捕获NoSuchAlgorithmException --这在你的程序中是不会发生的。

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

票数 4
EN

Stack Overflow用户

发布于 2012-03-28 20:06:20

实际上,跟随this link会告诉您KeyGenerator确实支持RC4,但是指定"ARCFOUR“作为算法名称

票数 1
EN

Stack Overflow用户

发布于 2012-03-28 20:13:14

尝试使用ARCFOUR而不是RC4 documentation is here

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9907052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档