【问题标题】:KeyPairGenerator cannot be resolvedKeyPairGenerator 无法解析
【发布时间】:2015-11-20 19:17:05
【问题描述】:

我正在尝试创建一个使用 RSA 加密消息的小型消息系统,但由于某种原因,代码无法识别 KeyPairGenerator 类,所以我一开始就被卡住了。 到目前为止,我的代码,正如互联网上的许多示例一样,是:

public class RSA {
    private KeyPairGenerator key_par_gen = null;
    private KeyPair kp = null;
    private PublicKey publicKey = null;
    private PrivateKey privateKey = null;
    private KeyFactory factory_rsa = null;
    private RSAPublicKeySpec pub = null;
    private RSAPrivateKeySpec priv = null;

    public RSA(){       
        setKey_par_gen(); 
        setKp(); //No error here
    }

    public void setKey_par_gen() {
        this.key_par_gen = new KeyPairGenerator.getInstance("RSA");
        //Error: Description    Resource    Path    Location    Type
        //       KeyPairGenerator.getInstance cannot be resolved to a type  RSA.java    /RSA - Cloud/src    line 41 Java Problem

    }

    public void setKp() {
        this.kp = getKey_par_gen().genKeyPair();
    }
//....
}

我已经更新到最新的 java 版本,打开 KeyPairGenerator 声明,它就在那里,声明的函数和所有内容。 也不能来自 IDE,因为我尝试过 Intellij、Eclipse 和 Netbeans。 不知道我在这里缺少什么。任何帮助表示赞赏。

【问题讨论】:

  • 去掉new KeyPairGenerator.getInstance("RSA");前面的newKeyPairGenerator 是一个带有静态方法的抽象类getInstance()
  • 请注意,Java 编译器在上面的代码中寻找一个名为KeyPairGenerator.getInstance 的嵌套类,其构造函数为getInstance(String)。它不会找到它(尽管它可能会找到方法声明)并且可能会显示一个相当奇怪的编译器错误(以防有人想知道编译器错误是什么)。
  • 我对“简单的印刷错误”投了赞成票,但由于这是一个错误,会导致复杂的错误消息并且很容易犯,我不介意如果它没有关闭,即使这是一个相当基本的错误。我发现自己仍然不时输入new,当我的大脑告诉我的手指创建一个对象实例而对象应该使用可用的工厂方法创建时。而且我确实认为我对 Java 和加密比较有经验。

标签: java eclipse cryptography rsa


【解决方案1】:

您正在尝试实例化一个不存在的嵌套类 KeyPairGenerator.getInstance

this.key_par_gen = new KeyPairGenerator.getInstance("RSA");
// Error: KeyPairGenerator.getInstance cannot be resolved to a type

相反,您需要调用 KeyPairGenerator 的静态 getInstance() 方法 - 只需删除 new

this.key_par_gen = KeyPairGenerator.getInstance("RSA");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    相关资源
    最近更新 更多