The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.
For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.
static String getBase64EncodedCipherText(String cipherText) {
byte[] cText = cipherText.getBytes();
// return an ISO-8859-1 encoded String
return Base64.getEncoder().encodeToString(cText);
}
static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
return new String((Base64.getDecoder().decode(encodedCipherText)));
}
public static void main(String[] args) {
try {
String cText = getRawCipherText(null, "Hello World of Encryption...");
System.out.println("Text to encrypt/encode: Hello World of Encryption...");
// This output is a simple sanity check to display that the text
// has indeed been converted to a cipher text which
// is unreadable by all but the most intelligent of programmers.
// It is absolutely inhuman of me to do such a thing, but I am a
// rebel and cannot be trusted in any way. Please look away.
System.out.println("RAW CIPHER TEXT: " + cText);
cText = getBase64EncodedCipherText(cText);
System.out.println("BASE64 ENCODED: " + cText);
// There he goes again!!
System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText));
System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
} catch (Exception e) {
e.printStackTrace();
}
}
The output looks like:
Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED: q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...