Need thread safe MessageDigest in Java

为君一笑 提交于 2019-11-29 21:28:53

Create a newMessageDigest instance each time you need one.

All of the instances returned from getInstance() are distinct. They need to be, as they maintain separate digests (and if that's not enough for you, here's a link to the source).

ThreadLocal can provide a performance benefit when used with a threadpool, to maintain expensive-to-construct objects. MessageDigest isn't particularly expensive to construct (again, look at the source).

As an alternative, use DigestUtils, Apache Commons' thread-safe wrapper for MessageDigest.

sha1() does what you need:

byte[] bytes = sha1(key)

DigestUtils doesn't seem to be anymore threadsafe than raw MessageDigest. Still uses MessageDigest.getInstance under the covers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!