尝试使用getServletContext()。getRealPath()读取文件时,FileNotFound异常

时间:2018-11-09 20:04:16

标签: java jsp servlets filepath filenotfoundexception

我的程序能够使用路径文件创建和写入文件:

private static final String PUBLIC_KEY_FILE = "WebContent/Config/MyPublic.key";
    private static final String PRIVATE_KEY_FILE = "WebContent/Config/MyPrivate.key";

然后根据上面声明的路径在文件夹中生成正确的文件。

但是当我尝试使用路径文件从那些文件中读取时,会出现 FileNotFoundException 错误:

private String REAL_PUBLIC_PATH = getServletContext().getRealPath("/WebContent/Config/MyPublic.key");
    private String REAL_PRIVATE_PATH = getServletContext().getRealPath("/WebContent/Config/MyPrivate.key");

这是导致错误的代码行:

PublicKey pubKey = readPublicKeyFromFile(this.REAL_PUBLIC_PATH);
PrivateKey privKey = readPrivateKeyFromFile(this.REAL_PRIVATE_PATH);

哪个与变量REAL_PUBLIC_PATHREAL_PUBLIC_PATH相关联。这意味着路径文件的读取方式有问题。

我的文件夹结构是:

> MyProject
   >Web-Content
     >Config
        >MyPublic.key
        >MyPrivate.key
     >WEB-INF
     >META-INF

我的完整班级代码如下所示:

public class RSAEncryptionHelper extends HttpServlet {


    private static final String PUBLIC_KEY_FILE = "WebContent/Config/MyPublic.key";
    private static final String PRIVATE_KEY_FILE = "WebContent/Config/MyPrivate.key";

    private String REAL_PUBLIC_PATH = getServletContext().getRealPath("/WebContent/Config/MyPublic.key");
    private String REAL_PRIVATE_PATH = getServletContext().getRealPath("/WebContent/Config/MyPrivate.key");

    public static void main(String[] args) throws IOException{
        try 
        {
            System.out.println("--GENERATE PUBLIC and PRIVATE KEY --");
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048); //1024 for normal securities
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            System.out.println("\n--PULLING OUT PARAMETERS WHICH MAKES KEYPAIR--\n");
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
            RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);

            System.out.println("\n--SAVING PUBLIC KEY AND PRIVATE KEY TO FILES--\n");

            RSAEncryptionHelper rsaObj = new RSAEncryptionHelper();

            rsaObj.saveKeys(PUBLIC_KEY_FILE, rsaPubKeySpec.getModulus(), rsaPubKeySpec.getPublicExponent());
            rsaObj.saveKeys(PRIVATE_KEY_FILE, rsaPrivKeySpec.getModulus(), rsaPrivKeySpec.getPrivateExponent());

        }

        catch (NoSuchAlgorithmException | InvalidKeySpecException e)
        {
            System.out.println(e);
        }
    }

    private void saveKeys(String fileName, BigInteger mod, BigInteger exp) throws IOException {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try
        {
            System.out.println("Generating: " + fileName + "...");
            fos = new FileOutputStream(fileName);
            oos = new ObjectOutputStream(new BufferedOutputStream(fos));
            oos.writeObject(mod);
            oos.writeObject(exp);
            System.out.println(fileName + "generated successfully");;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (oos!=null)
            {
                oos.close();
                if (fos!= null)
                {
                    fos.close();
                }
            }
        }
    }

    public PublicKey readPublicKeyFromFile(String fileName) throws IOException{
        FileInputStream fis = null;
        ObjectInputStream ois = null;

        PublicKey publicKey = null;

        try
        {
            fis = new FileInputStream(new File(fileName));
            ois = new ObjectInputStream(fis);
            BigInteger modulus = (BigInteger) ois.readObject();
            BigInteger exponent = (BigInteger) ois.readObject();

            //Get Public Key
            RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
            KeyFactory fact = KeyFactory.getInstance("RSA");
            publicKey = fact.generatePublic(rsaPublicKeySpec);
            return publicKey;
        }       
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (InvalidKeySpecException e)
        {
            e.printStackTrace();
        }
        finally 
        {
            if (ois != null)
            {
                ois.close();
                if (fis != null)
                {
                    fis.close();
                }
            }
        }
        return publicKey;
    }

    public PrivateKey readPrivateKeyFromFile(String fileName) throws IOException{
        FileInputStream fis = null;
        ObjectInputStream ois = null;

        PrivateKey privateKey = null;

        try
        {
            fis = new FileInputStream(new File(fileName));
            ois = new ObjectInputStream(fis);
            BigInteger modulus = (BigInteger) ois.readObject();
            BigInteger exponent = (BigInteger) ois.readObject();

            //Get Public Key
            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
            KeyFactory fact = KeyFactory.getInstance("RSA");
            privateKey = fact.generatePrivate(rsaPrivateKeySpec);
            return privateKey;
        }       
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (InvalidKeySpecException e)
        {
            e.printStackTrace();
        }
        finally 
        {
            if (ois != null)
            {
                ois.close();
                if (fis != null)
                {
                    fis.close();
                }
            }
        }
        return privateKey;
    }

    public byte[] encryptData(String data) throws IOException {
        System.out.println("\n--ENCRYPTION STARTED--");
        System.out.println("Data Before Encryption: " + data);
        byte[] dataToEncrypt = data.getBytes();
        byte[] encryptedData = null;

        try
        {
            PublicKey pubKey = readPublicKeyFromFile(this.REAL_PUBLIC_PATH);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            encryptedData = cipher.doFinal(dataToEncrypt);
            System.out.println("Encrypted Data: " + encryptedData);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (InvalidKeyException e)
        {
            e.printStackTrace();
        }
        catch (IllegalBlockSizeException e)
        {
            e.printStackTrace();
        }
        catch (BadPaddingException e)
        {
            e.printStackTrace();
        } 
        catch (NoSuchPaddingException e) 
        {           
            e.printStackTrace();
        } 

        System.out.println("--ENCRYPTION COMPLETED--");
        return encryptedData;
    }

    public String decryptData(byte[] data) throws IOException {
        System.out.println("\n--DECRYPTION STARTED--");
        byte[] decryptedData = null;

        String decData = "";

        try
        {
            PrivateKey privateKey = readPrivateKeyFromFile(this.REAL_PRIVATE_PATH);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            decryptedData = cipher.doFinal(data);

            decData = new String(decryptedData);
            System.out.println("Decrypted Data: " + decData);


            return decData;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (NoSuchPaddingException e)
        {
            e.printStackTrace();
        }
        catch (InvalidKeyException e)
        {
            e.printStackTrace();
        }
        catch ( IllegalBlockSizeException e)
        {
            e.printStackTrace();
        }
        catch (BadPaddingException e)
        {
            e.printStackTrace();
        } 

        System.out.println("--DECRYPTION COMPLETED--");
        return decData;
    }
}

1 个答案:

答案 0 :(得分:0)

在运行程序之前,您的密钥是否已经存在?如果不是这样,则将getRealPath转到不存在的文件将无法正常工作。

但这没关系,因为如果您可以使用私有静态最终字符串PUBLIC_KEY_FILE访问文件,为什么不使用同一路径读取文件。

所以代替这个:

  PrivateKey privateKey = readPrivateKeyFromFile(this.REAL_PRIVATE_PATH);

为什么不这样做?

  PrivateKey privateKey = readPrivateKeyFromFile(this.PRIVATE_KEY_FILE);

如果您已成功使用PRIVATE_KEY_FILE路径写入文件,则也可以从同一路径读取。