-2

I have encrypted a string using the above code.

public String encrypt(String generatedKey)
    {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(generatedKey.getBytes("UTF-8"));
                byte digest[] = md.digest();
                return (new BASE64Encoder()).encode(digest);
            }
            catch (Exception e) {
                return null;
            }

    }

Similarly i need a code to decrypt the above generated code. How can i do this?

Gapchoos
  • 1,422
  • 5
  • 20
  • 40

3 Answers3

5

SHA is a digest algorithm, not an encryption algorithm. Digest values are not decryptable. That's why they are secure. Two different inputs may give same digest values. But it is a very little possibility. For sha256 it is 1/(2^256).

Output of digest algorithms have constant length. For SHA256 it is always 256 bit, regardless of your input length, 1 bit or 100 Gbs. If we could decrypt 256 bit digest value and have the original 1Gb input back, we would never need compression algorithms :)

Mehmet Ataş
  • 11,081
  • 6
  • 51
  • 78
2

Message digests produce a small "fingerprint" of a larger set of data. It's a one way procedure.

What you probably is looking for is encryption.

Key key = new SecretKeySpec(secret.getBytes(), ALGORITHM);

// Encrypt
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(plainText);

// Decrypt
cipher.init(Cipher.DECRYPT_MODE, key)
byte[] decryptedData = cipher.doFinal(encryptedData);

Where ALGORITHM can be one of http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html#Cipher

heffaklump
  • 1,526
  • 3
  • 21
  • 27
0

I am pretty sure that we cannot decode a SHA encrypted string directly.

See this for a clear explanation: How to decrypt SHA-256 encrypted String?

Community
  • 1
  • 1
venki
  • 1,121
  • 1
  • 9
  • 18