【问题标题】:RSA Encryption ErrorRSA 加密错误
【发布时间】:2015-02-04 05:32:24
【问题描述】:

我用 puttygen 生成了一个公共和私有代码,私钥导出为 openssl,pey 的名称是 public_key.der , private_key.pem 但是当我尝试使用 java 对其进行加密时,我收到此错误:

java.io.FileNotFoundException: public_key.der

代码是:

    public static String RSAPublicEncryptuion(String text){
    DataInputStream dis = null;
    try {
        File pubKeyFile = new File("public_key.der");
        dis = new DataInputStream(new FileInputStream(pubKeyFile));
        byte[] keyBytes = new byte[(int) pubKeyFile.length()];
        dis.readFully(keyBytes);
        dis.close();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        String textoEncryptado = new String(cipher.doFinal(text.getBytes()), "UTF-8");
        return textoEncryptado;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(RSAEncrypt.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException ex) {
        Logger.getLogger(RSAEncrypt.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        Logger.getLogger(RSAEncrypt.class.getName()).log(Level.SEVERE, null, ex);
    }
   return "Error";
}

public_key 与这个类(testras.ras)在同一个包中,我做错了什么? 谢谢大家! 对不起我的英语不好

【问题讨论】:

  • public_key.der 文件在哪里?
  • 与.java在同一个包中,当我编译它时,它会在.class所在的同一个地方

标签: java encryption rsa


【解决方案1】:

您当前的方法(使用相对文件路径)取决于运行时密钥文件相对于工作目录的位置,这可能不明显。

但是,您提到公钥文件“在 .class 文件所在的同一位置”——您可以利用这一事实来获得更灵活的解决方案。尝试使用Class.getResourceAsStream,如下图:

InputStream is = RSAEncrypt.class.getResourceAsStream("public_key.der");

【讨论】:

  • 现在我有这个错误:java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format 密钥是正确的,有什么问题?
  • 调试它需要更多关于你的执行环境的信息(例如,我看到 Maven 损坏了一个 PKCS 12 密钥,可能是试图缩小它或其他东西)。不过,如果您还没有,不妨查看this question 的答案,该答案链接到有关该主题的另一个答案...
  • 现在它的工作,谢谢它的格式不正确,再次感谢大家!
  • 是的忘记了抱歉,谢谢大家!
猜你喜欢
  • 2017-06-20
  • 2020-11-03
  • 2011-02-24
  • 1970-01-01
  • 2018-10-27
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多