1

Sorry if it's an amateur question. I cant seem to find the right answer to it. What is the android (java) equivalent of swift's:

"somestring".data(using:.utf8)

method?

Thanks a lot

EDIT:

I am creating a java version of the following method:

guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }

let credential = data.base64EncodedString(options: [])

return (key: "Authorization", value: "Basic \(credential)")
MetaSnarf
  • 5,857
  • 3
  • 25
  • 41

1 Answers1

1

Okay so I was playing a bit. Then I remembered on Obj-c that string is madeup of NSData and nsdata's java equivalent would be byte[] so what I did was convert string to byte array before converting it back to string:

byte[] data = (user+":"+password).getBytes("utf-8");
String credential = Base64.encodeToString(data,Base64.DEFAULT);
return new KeyValue("Authorization", "Basic "+credential);

Thanks a lot. Hope this helps anyone.

MetaSnarf
  • 5,857
  • 3
  • 25
  • 41
  • 1
    Don't use String for passwords, keys and other security-sensative stuff in Java. Objects remain alive even after they're no longer used, for some indefinite amount of time until the GC does its next sweep. During this time, this sensitive data is unnecessarily kept in memory and is vulnerable to memory dumps. The correct approach would be to manually zero-out the data when you're done with it, but since `String` is immutable, that's impossible. See https://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords – Alexander Dec 05 '17 at 15:29