How to calculate hash sum of a string (using java)?

63 ビュー (過去 30 日間)
Sebastian Holmqvist
Sebastian Holmqvist 2012 年 8 月 6 日
回答済み: Oliver Woodford 2016 年 5 月 5 日
Couldn't find this very easily (without including a bunch of c-mex files etc) so I thought I'd post it here for future reference. I prefer using java methods to avoid dependencies.
Question:
Using java, how to create a MD5 (or SHA1 etc) hash sum of a string?

採用された回答

Sebastian Holmqvist
Sebastian Holmqvist 2012 年 8 月 6 日
編集済み: Sebastian Holmqvist 2012 年 8 月 6 日
Solution:
The trick here is to input an ascii representation of your string (hence, the double(string) call). MessageDigest outputs 16 bytes which represents 32 chars. So we use BigInteger to convert the bytes to that radix.
import java.security.*;
import java.math.*;
md = MessageDigest.getInstance('MD5');
hash = md.digest(double('Your string.'));
bi = BigInteger(1, hash);
char(bi.toString(16))
ans =
b99e5935368933bafefed10b99bb0489
  1 件のコメント
Nick Hilton
Nick Hilton 2015 年 10 月 14 日
I found a bug, BigInteger.toString(16) won't fill with zeros. For example, if the BigInter's hex representation was '0abc', toString(16) will only return 'abc'.
Fixing this requires using the java.lang.String.format method:
import java.lang.String;
char(String.format('%032x', bi));
MD5 returns 32 hex values, but if one were to change the message digest to 'SHA-256', then one needs to use:
char(String.format('%064x', bi));
This will guarantee a fixed width hash filled with '0'.

サインインしてコメントする。

その他の回答 (1 件)

Oliver Woodford
Oliver Woodford 2016 年 5 月 5 日
A similar solution:
%STRING2HASH Convert a string to a 64 char hex hash string (256 bit hash)
%
% hash = string2hash(string)
%
%IN:
% string - a string!
%
%OUT:
% hash - a 64 character string, encoding the 256 bit SHA hash of string
% in hexadecimal.
function hash = string2hash(string)
persistent md
if isempty(md)
md = java.security.MessageDigest.getInstance('SHA-256');
end
hash = sprintf('%2.2x', typecast(md.digest(uint8(string)), 'uint8')');
end

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by