Home > Mobile >  How to securely load an image from camera and display it in full size on Android?
How to securely load an image from camera and display it in full size on Android?

Time:08-09

For security, I was advised to avoid using getExternalFilesDir(Environment.DIRECTORY_PICTURES) for storing files and creating insecure temporary files with File.createTempFile.

How can we rewrite this in a secure way?

clTakeBottomSheetCamera.setOnClickListener(v -> {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    if (intent.resolveActivity(getPackageManager()) != null) {
        try {
            profilePhotoFile = createPhotoFile(tag); // FIXME <--

            Uri photoURI = FileProvider.getUriForFile(context, "com.test.test"   ".provider", profilePhotoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

            startActivityForResult(intent, REQUEST_CODE_CAPTURE_PASSPORT_IMAGE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});
 private File createPhotoFile(String tag) throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = custPhoneNumber   "_"   timeStamp   "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); // FIXME: Insecure data storage
        File imgFile = File.createTempFile(imageFileName, ".jpg", storageDir); // FIXME: Insecure temporary file creation

        profilePhotoPath = imgFile.getAbsolutePath();
        return imgFile;
    }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_CAPTURE_PASSPORT_IMAGE && resultCode == RESULT_OK) {
        // Display the captured image in an ImageView with Glide
        Glide.with(activity).load(profilePhotoPath).into(ivCustomerPhotoActivation);
    }
}

CodePudding user response:

File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); // FIXME: Insecure data storage

Instead of getExternalFilesDir(), use getFilesDir() or getCacheDir(), and adjust your FileProvider metadata to match.

File imgFile = File.createTempFile(imageFileName, ".jpg", storageDir); // FIXME: Insecure temporary file creation

If you fix the earlier problem, this should no longer be considered to be insecure.

  • Related