Reputation: 414
I have to convert a string into binary using UTF-8, but i am unable to do that. I have tried
String encodedName=URLEncoder.encode(name, "UTF-8");
but it doesn't gave me the binary format, it just returned me the same string with slight changes, please help.
EDIT:
what i have to do: I have a string suppose "HelloWorld" I have to convert it to binary using "UTF-8" and then use SHA1 hashing algorithm and from this i will get the hashkey and this is what i need "a hashkey".
I found this one for SHA1 hashing.
public class AeSimpleSHA1 {
private String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
public String SHA1(String text)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
byte[] sha1hash = new byte[40];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
sha1hash = md.digest();
return convertToHex(sha1hash);
}
}
Upvotes: 2
Views: 11602
Reputation: 1504092
It's not really clear what you mean, but you'd usually use:
byte[] data = name.getBytes("UTF-8");
I'm not sure why you've used URLEncoder
in your attempt - or what your "desired result" is.
EDIT: Converting the binary data back to text so you can then call getBytes()
on it in your SHA1
method makes no sense. Just change your hashing method do:
public String hashSha1(byte[] data) throws NoSuchAlgorithmException,
UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(data, 0, data.length);
return convertToHex(md.digest());
}
Upvotes: 2
Reputation: 68187
why dont you simply use string's getBytes()
method to convert into UTF-8 bytes array? see below:
String s = "this is my string";
byte[] bytes = s.getBytes(); // default: UTF-8
the default encoding is UTF-8 in android, though you may further define your own encoding in the same method
Upvotes: 0