您如何使用 java 中的密钥文件加密数据?

How do you encrypt data using a key file in java?

我正在尝试制作一个程序,该程序使用 RSA 加密来加密和解密发送到多台计算机和从多台计算机发送的数据。我的计算机上有一个文件夹,用于存储其他计算机的 public 密钥。但是,我似乎无法加载此密钥文件并创建指向它的 publicKey 对象。我目前的尝试如下所示,但我想知道其他人使用什么方法来做到这一点?

      //Returns the key of a friend (given as input)

  public PublicKey getFriendsKey(String friend){
    try{ObjectInputStream friendsKeyInput = new ObjectInputStream(new fileInputStream(programLocation + "/Text Files/encryptionKeys/" + friend + "PublicKey.key"));
    PublicKey friendsKey = friendsKeyInput.readObject();
    }
    catch(Exception e){e.printStackTrace();}
    return friendsKey;
  }

为什么要使用 ObjectInputStream?您的密钥很可能不是 serializable java object。 看到这个答案。 Load RSA public key from file