0

I need to add my SSL certificate for Retrofit in Android but I can't find the file using Google's example code for doing this.

Here's the example from Google that I'm using https://developer.android.com/training/articles/security-ssl

When running:

val caInput: InputStream = BufferedInputStream(FileInputStream("rest_of_the_world_production.crt"))

I get the error

 Caused by: java.io.FileNotFoundException: rest_of_the_world_production.crt: open failed: ENOENT (No such file or directory)

and an instant crash when trying to access the file. The file is currently stored as a crt file under res/raw/rest_of_the_world_production.crt so why can't Android find it?

Will Alexander
  • 337
  • 2
  • 16
  • Exception is clear your Input Stream is null!! – R.Coder Nov 11 '19 at 09:00
  • Indeed it is. But given my file is at that directory why can't I find it?! – Will Alexander Nov 11 '19 at 09:22
  • make sure you're having run time permissions take a look at this: https://stackoverflow.com/questions/19871955/java-io-filenotfoundexception-the-system-cannot-find-the-file-specified – R.Coder Nov 11 '19 at 09:33
  • I've tried moving it to the root project directory as that question suggests but I still get the error when it can't find it? How do I check the run time permissions? – Will Alexander Nov 11 '19 at 09:58

2 Answers2

1

Do it as follows:

InputStream cert = context.getResources().openRawResource(R.raw.my_cert); 
// Place your 'my_cert.crt' file in `res/raw`
Muhammad Saad Rafique
  • 3,158
  • 1
  • 13
  • 21
  • Thanks for the answer. But when I try add the R.raw.my_cert, Android Studio doesn't recognise the file in that path despite it showing up in the file/project hierarchy. – Will Alexander Nov 11 '19 at 09:56
  • Make sure the name of the file in raw folder and in above line is same. Cert file type in raw folder should be crt. Try removing previous file and rename the file and move back to the raw folder. Clean and rebuild the project. If nothing works then restart android studio. Hope that helps buddy! – Muhammad Saad Rafique Nov 11 '19 at 09:59
  • Still no luck trying all that sadly. I can access all the other files in other directories under the res folder but nothing in my raw file, even a blank txt. – Will Alexander Nov 11 '19 at 10:08
0

So turns out I had imported

android.R

instead of

com.myApp.R

Changing this allowed me to find my certificate and import it.

Will Alexander
  • 337
  • 2
  • 16