This question already has answers here:
What does & 0xff do And MD5 Structure?
(2 answers)
Closed 7 years ago.
I've found this java function that encrypt a string in MD5, but I fail to understand how it works:
public static String makeMD5(String text){
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
md.update(text.getBytes());
byte byteData[] = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++)
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
text = sb.toString();
return text;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
I don't understand the line just after the for loop..
Thanks a lot!
The line after the for loop is a frankly overcomplicated way to convert a byte array into hexadecimal. An equivalent, simpler approach might be
sb.append(String.format("%02x", b & 0xff));
though if you can use third-party libraries there are even simpler solutions. How to convert a byte array to a hex string in Java? has a number of suggestions.
(If third party libraries are available, Guava will let you do this whole method in the one line Hashing.md5().hashString(text, Charset.defaultCharset()).toString().)
Related
I have a strange problem in getting equivalent hash code from C# code translated into Java. I don't know, what MessageDigest update method do. It should only update the contents of digest and should compute hash after calling digest.
Same thing I am doing in C# with SHAManaged512.ComputeHash(content). But I am not getting same hash code.
Following is the Java code.
public static String hash(String body, String secret) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(body.getBytes("UTF-8"));
byte[] bytes = md.digest(secret.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
} catch (Exception e) {
throw new RuntimeException();
}
}
Following is C# Code
private byte[] ComputeContentHash(string contentBody)
{
using (var shaM = new SHA512Managed())
{
var content = string.Concat(contentBody, Options.SecretKey);
var hashedValue = shaM.ComputeHash(ToJsonStream(content));
return hashedValue;
}
}
public static Stream ToJsonStream(object obj)
{
return new MemoryStream(Encoding.Unicode.GetBytes(obj.ToString()));
}
I had the exact same issue. Its been two years since you asked but just in case someone comes across this question, here's the solution
public static string encryptHash(string APIkey, string RequestBodyJson)
{
var secretBytes = Encoding.UTF8.GetBytes(APIkey);
var saltBytes = Encoding.UTF8.GetBytes(RequestBodyJson);
using (var sHA256 = new SHA256Managed())
{
byte[] bytes = sHA256.ComputeHash(saltBytes.Concat(secretBytes).ToArray());
//convert to hex
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
return builder.ToString();
}
}
The solution was to put first Secret Key and concate it with pay load data.
Encoding.Unicode (which you are using in the C# ToJsonStream method) is not UTF8. It's UTF16. See MSDN. (Also keep in mind that UTF16 can be little or big endian.) You're looking for Encoding.UTF8.
First thing to do is check if the byte array you're hashing is the same.
private String getString(byte[] bytes)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++)
{
byte b = bytes[i];
sb.append(0xFF & b);
}
return sb.toString();
}
public String encrypt(String source)
{
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
}
catch (Exception e)
{
e.printStackTrace(); }
return null;
}
If my text = "test"
The First Part toString()) produces a value of "Encryption$2#6966b26b"
And the second part then gets that and produces a value of "91431072057033211115202222781313839180246"
But why is the md5 a number and not 31f521a06d5060d1f38159c74a1f7cf2 or something similar?
The function "encrypt()" returns a MD5 hash. You should rename it to "hash", because hashing != encrypting.
If you want to encrypt a string, you can look here: https://gist.github.com/bricef/2436364
It's clearly stated in code yuou are using MD5 hashing algorithm
Now your question is why:
But why is the md5 a number and not 31f521a06d5060d1f38159c74a1f7cf2 or something similar?
your answer is simple, look at code which generates you string from your byte array.
byte b = bytes[i];
sb.append(0xFF & b);
you take byte, ie 0x20 then you perform logical and operation with integer 0x255 and then you add decimal representation of result yo your StringBuilder.
What you want to do is more like
sb.append(Integer.toHexString(0xff&b));
I would say MD5 hash, because the code says MessageDigest.getInstance("MD5") :D
This question already has answers here:
convert password encryption from java to php
(4 answers)
Closed 7 years ago.
I have JAVA AES encryption logic
private static byte[] getMD5(String input) {
try {
byte[] bytesOfMessage = input.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
return md.digest(bytesOfMessage);
} catch (Exception e) {
}
return null;
}
What will be the php equivalent of this function?
I have used md5($string) in php but the output is different in both the cases.
In the code that you have posted you get the byte array of the md5 hash. PHP's md5() function returns the md5 hash as a hex.
So, if you want to get the md5 hash as string in java you can like this:
private static String getMD5(String input) {
try {
byte[] bytesOfMessage = input.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
// byte array of md5 hash
byte[] md5 = md.digest(bytesOfMessage);
// we convert bytes to hex as php's md5() would do
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < md5.length; i++) {
stringBuffer.append(Integer.toString((md5[i] & 0xff) + 0x100, 16).substring(1));
}
return stringBuffer.toString();
} catch (Exception e) {
}
return null;
}
From PHP you can get the row md5 binary by doing md5('some string', true). See md5() function documentation about it.
To get the byte array you can do unpack('c*', md5('some string',true)). See unpack() function and the possible formats for more info.
I am using this function to calculate the SHA 256
public static String getSHA1(String plainText) {
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-256");
md.update(plainText.getBytes(Charset.forName("UTF-8")));
StringBuffer hexString = new StringBuffer();
byte[] bytes = md.digest();
for (int i = 0; i < bytes.length; i++) {
hexString.append(Integer.toHexString(0xFF & bytes[i]));
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
And to be sure of my results, I check this online website
http://onlinemd5.com/
the results between my code and the online is almost the same, but you know that it must be equal. for instance
my plain testis:
1234567
the website result
8BB0CF6EB9B17D0F7D22B456F121257DC1254E1F01665370476383EA776DF414
my code result
8bb0cf6eb9b17df7d22b456f121257dc1254e1f1665370476383ea776df414
and this is more examples:
7777777
8C1CDB9CB4DBAC6DBB6EBD118EC8F9523D22E4E4CB8CC9DF5F7E1E499BBA3C10
8c1cdb9cb4dbac6dbb6ebd118ec8f9523d22e4e4cb8cc9df5f7e1e499bba3c10
147258
7A2EC40FF8A1247C532309355F798A779E00ACFF579C63EEC3636FFB2902C1AC
7a2ec4ff8a1247c53239355f798a779e0acff579c63eec3636ffb292c1ac
888888
92925488B28AB12584AC8FCAA8A27A0F497B2C62940C8F4FBC8EF19EBC87C43E
92925488b28ab12584ac8fcaa8a27af497b2c6294c8f4fbc8ef19ebc87c43e
I do know that this is maybe about the encoding. but look i used utf-8 which is what the website used
This is the problem:
hexString.append(Integer.toHexString(0xFF & bytes[i]));
This will lose any leading 0s - in other words, any byte less than 16 will come out as a single hex digit instead of two.
There are plenty of fixes for this. For example:
Manually append 0 if the value is between 0 and 15 (ick)
Use String.format("%02x", bytes[i] & 0xff)
Use a full "byte array to hex conversion" method in a utility library (there are loads around)
Hello everybody I am working on the first piece of communication between server and client of my game. Obviously due to the fact that I am starting from zero, I am projecting each part of the program carefully.
I was looking in Swing API and I found the JPasswordField that is a normal InputField, but for passwords.
It returns as you know a string if the deprecated method getText() is called or an array of chars if is called getPassword.
Reading in SO I understood that is not a good idea to use getText, nor something like
String password = String.valueOf(passwordField.getPassword());
because doing so I am creating a String that can stay in memory for long time.
What I tried to create is something that can convert that password without using strings and I created this:
public static String digest(char[] in) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
ArrayList<Byte> list = new ArrayList<Byte>();
for(int i = 0; i<in.length; i++){
String ch = String.valueOf(in[i]);
byte[] b = ch.getBytes();
for(int j = 0; j<b.length;j++){
list.add(b[j]);
}
}
byte[] inputInByte = new byte[list.size()];
for(int i =0;i<list.size();i++){
inputInByte[i] = list.get(i);
}
md.update(inputInByte);
byte byteData[] = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
String hex = Integer.toHexString(0xff & byteData[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
The question is: is this algorithm correct and good for the security of the password? I had to use a String to convert from char to byte.
Also I return an hashed string, is there any problem in that? It should be quite difficult to find the password starting from the hash ;)
How about database connection? Hsqldb allow me to create query, but each query is a string......
Using SHA-256 digest is a hash method, not a cryptologic one. It is like a fingerprint. Can you get a person from his fingerprints without testing everybody's (6 billions) fingerprint ? No. It used to store password in databases in php, for example. We just store the pass's hash, and when the user want to connect, we compute the newly entered password hash, and compare it with the database's hash.
This prevents users from stealing passwords if the database is hacked. But you cannot get the password from the hash. I hope i answered to your question.
By the way, consider using apache lib for message digest, it is easier and more safe i think
I think your code is quite ok, but you are still working with String to create the byte value, so you maybe better change String.valueOf(in[i]); to something like this:
public static String digest(char[] in) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
ArrayList<Byte> list = new ArrayList<Byte>();
for(int i = 0; i<in.length; i++){
byte b = (byte) in[i]
list.add(b);
}
byte[] inputInByte = new byte[list.size()];
for(int i =0;i<list.size();i++){
inputInByte[i] = list.get(i);
}
md.update(inputInByte);
byte byteData[] = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
String hex = Integer.toHexString(0xff & byteData[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
that is also easier than using that for cycle and two step conversion to byte.