RSA 加密错误

RSA Encryption Error

我已经用 puttygen 生成了 public 和私有代码,私钥导出为 openssl,peys 的名称是 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 与 class (testras.ras) 在同一个包中,我做错了什么? 谢谢大家! 抱歉我的英语不好

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

但是,您提到 public 密钥文件是 "in the same place where the .class" 文件 - 您可以利用这一事实获得更灵活的解决方案。尝试使用 Class.getResourceAsStream,如下图所示:

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