public static void main(String[] args) { String s = "text"; hash=DatatypeConverter.printHexBinary(MessageDigest.getInstance("MD5").digest(s.getBytes("UTF8"))) System.err.println(hash); }

## Advertisement

## Answer

You can’t. That’s what hashing is about. This is not a API or library limitation but a mathematical one, which is there by design.

You need to understand that hashing and encryption/ decryption are two completely different things (which are often used together).

## Hashing

A hash, or to be precise, a cryptographic hash, is the result of a mathematical one-way function which means it is meant to be irreversible. Once something is hashed, it is not possible to get the text that was hashed back from it. This is at least true for good hash algorithms, which are not considered broken. `MD5`

as well as `SHA1`

are considered broken, so if you need this in a security context, use `SHA-256`

or even `SHA-512`

instead. If you just need this for a checksum, `MD5`

should be fine.
You can just use an MD5 hash value and type it into Google and get the result back. That is not what you want from a hash function. E.g. take your the hash `1cb251ec0d568de6a929b520c4aed8d1`

which is the MD5 hash of your message `text`

and you’ll get a website which shows you the original text.

Another property of a hash it that for two different inputs it should ideally never have the same output. That is of course impossible as the set of possible messages to hash is much much bigger then the set of possible hash messages as hashes have a fixed length. But it should not be possible to generate such a hash collision artificially following some algorithm or clever input.

The only way to find out what was hashed is to hash many messages (brute-force) and see if the computed hash matches the hash to be cracked. See Rainbow tables for more information on this.

Hashes are mostly used to ensure integrity i.e. no modification was done to a message sent over the network. It is often used in conjunction with encryption algorithms (that’s probably where your confusion originates from) as you need more than integrity to guarantee secure communication i.e. additionally authentication (e.g. by using certificates) and confidentiality (this is provided by encryption algorithms).

## Encryption

An encryption function is a function which takes a message and a key and produces a result which is not readable unless you have the key. Side note: there may be one or two keys for encryption/ decryption depending on the algorithm you use (symmetric vs. asymmetric). If you have the key, it is reversible by applying the decryption function. If it was a one-way function like a hash, encryption would make no sense, as a recipient of a message would not be able to retrieve the message.

**9**People found this is helpful