Search code examples
fileencryptionjava-8password-protectionjava-10

How can I password protect a file regardless of its extension in Java 8 ro Java 10


I have tried doing this by encrypting individual files but I have a lot of data (~20GB) and hence it would take a lot of time. In my test it took 2.28 minutes to encrypt a single file of size 80MB. Is there a quicker way to be able to password protect that would apply to any any file (text/binary/multimedia)?


Solution

  • If you are just trying to hide the file from others, you can try to encrypt the file path instead of encrypting the whole huge file.

    For the path you mentioned: text/binary/multimedia, you can try to encrypt it by a method as:

    private static String getEncryptedPath(String filePath) {
        String[] tokens = filePath.split("/");
        List<String> tList = new ArrayList<>();
        for (int i = 0; i < tokens.length; i++) {
            tList.add(Hashing.md5().newHasher() // com.google.common.hash.Hashing;
                    .putString(tokens[i] + filePath, StandardCharsets.UTF_8).hash().toString()
                    .substring(2 * i, 2 * i + 5)); // to make it impossible to encrypt, add your custom secret here;
        }
        return String.join("/", tList);
    }
    

    and then it becomes an encrypted path as:

    72b12/9cbb3/4a5f3
    

    Once you know the real path text/binary/multimedia, any time you want to access the file, you can just use this method to get the real file path 72b12/9cbb3/4a5f3.