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)")
4
  • 2
    What is it supposed to do ? Commented Dec 5, 2017 at 14:22
  • updated my question @AxelH Commented Dec 5, 2017 at 14:25
  • 1
    I still don't understand what it is supposed to do... you need to wait for a java/swift dev if you can't explain more than this Commented Dec 5, 2017 at 14:27
  • @AxelH yes. that is exactly what I forgot to implement. God, I can't beleive I spent hours using the URLEncoder thinking I should encode it first. Thanks for the help. Commented Dec 5, 2017 at 14:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 stackoverflow.com/questions/8881291/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.