0

I'm trying to preserve the password as char[] but in the second step, I'm converting it to a String again. Is there a way to to this in a better way?

char[] password = {'g', 'r', 'e'};
String toEncode = username + new String(password);
byte[] encoding = Base64.encodeBase64(toEncode.getBytes(Charset.forName(StandardCharsets.UTF_8.name())));

One option would be:

char[] toEncode = username.toCharArray() + password;
byte[] encoding = Base64.encodeBase64(new String(toEncode).getBytes(Charset.forName(StandardCharsets.UTF_8.name())));

What I'm asking is is there a better way to achieve it without using new String()

S.Dan
  • 1,826
  • 5
  • 28
  • 55
  • @Michael it's more: how to turn a char array to byte array without an intermediate step turning it to String – jhamon Jul 10 '18 at 08:40
  • @jhamon that's what I'm suggesting, I'm asking is there a better way to do it? – S.Dan Jul 10 '18 at 08:40
  • What I'm asking is is there a better way to achieve it without using `new String()` – S.Dan Jul 10 '18 at 08:42
  • The 2nd answer is what you want: https://stackoverflow.com/questions/5513144/converting-char-to-byte/9670279#9670279 – jhamon Jul 10 '18 at 08:44
  • @Michael I know, I reported the dupe. But it looks like OP didn't read the correct answer – jhamon Jul 10 '18 at 08:45
  • @SachiDangalla Why did you remove the Java tag? It's objectively related to Java. – Michael Jul 10 '18 at 08:57
  • Yes, the second answer best describes the solution to my question, but that question is too broad. – S.Dan Jul 10 '18 at 08:58

0 Answers0