Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

java - 如何生成MD5哈希?(How can I generate an MD5 hash?)

是否有任何方法可以在Java中生成字符串的MD5哈希?

  ask by Akshay translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The MessageDigest class can provide you with an instance of the MD5 digest.

(MessageDigest类可以为您提供MD5摘要的实例。)

When working with strings and the crypto classes be sure to always specify the encoding you want the byte representation in. If you just use string.getBytes() it will use the platform default.

(使用字符串和crypto类时,请务必始终指定要使用字节表示形式的编码。如果仅使用string.getBytes() ,它将使用平台默认值。)

(Not all platforms use the same defaults)

((并非所有平台都使用相同的默认值))

import java.security.*;

..

byte[] bytesOfMessage = yourString.getBytes("UTF-8");

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);

If you have a lot of data take a look at the .update(byte[]) method which can be called repeatedly.

(如果您有大量数据,请查看.update(byte[])方法,该方法可以重复调用。)

Then call .digest() to obtain the resulting hash.

(然后调用.digest()以获取结果哈希。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...