'How can I create a truststore from a base64 encoded String?

I have a String that is encoded in base64, I need to take this string, decode it and create a truststore file, but when I do that, the final file is not valid. Here is my code:

public static void buildFile() {
    String exampleofencoded = "asdfasdfasdfadfa";
    File file = new File("folder/file.jks");
    try (FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            DataOutputStream dos = new DataOutputStream(bos))
    {
        Base64.Decoder decoder = Base64.getDecoder();
        String decodedString =new String(decoder.decode(exampleofencoded).getBytes());
        dos.writeBytes(decodedString);
    }
    catch (IOException e) {
        System.out.println("Error creating file");
    }
    catch(NullPointerException e) {
        System.out.println(e.getMessage();
    }
}


Solution 1:[1]

The problem is two-fold.

  1. You're converting a byte[] array to String, which is a lossy operation for actual binary data for most character sets (except maybe iso-8859-1).
  2. You're using DataOutputStream, which is not a generic output stream, but intended for a specific serialization format of primitive types. And specifically its writeBytes method comes with an important caveat ("Each character in the string is written out, in sequence, by discarding its high eight bits."), which is one more reason why only using iso-8859-1 will likely work.

Instead, write the byte array directly to the file

public static void buildFile() {
    String exampleofencoded = "asdfasdfasdfadfa";
    File file = new File("folder/file.jks");
    try (FileOutputStream fos = Files.newOutputStream(file.toPath()) {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decodedbytes = decoder.decode(exampleofencoded);
        fos.write(decodedbytes);
    } catch (IOException e) {
        System.out.println("Error creating file");
    }
}

As an aside, you shouldn't catch NullPointerException in your code, it is almost always a problem that can be prevented by careful programming and/or validation of inputs. I would usually also advise against catch the IOException here and only printing it. It is probably better to propagate that exception as well, and let the caller handle it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Rotteveel