How to decrypt SHA-256 encrypted String?

chiappone picture chiappone · Feb 16, 2012 · Viewed 278k times · Source

I have a string that was encoded using the following method, is there a way to decode this string back to its original value? Thanks.

public synchronized String encode(String password)
        throws NoSuchAlgorithmException, IOException {

    String encodedPassword = null;
    byte[] salt = base64ToByte(saltChars);

    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.reset();
    digest.update(salt);

    byte[] btPass = digest.digest(password.getBytes("UTF-8"));
    for (int i = 0; i < ITERATION_COUNT; i++) {
        digest.reset();
        btPass = digest.digest(btPass);
    }

    encodedPassword = byteToBase64(btPass);     
    return encodedPassword;
}

private byte[] base64ToByte(String str) throws IOException {

    BASE64Decoder decoder = new BASE64Decoder();
    byte[] returnbyteArray = decoder.decodeBuffer(str);

    return returnbyteArray;
}

private String byteToBase64(byte[] bt) {

    BASE64Encoder endecoder = new BASE64Encoder();
    String returnString = endecoder.encode(bt);

    return returnString;
}

Answer

Brendan Long picture Brendan Long · Feb 16, 2012

SHA-256 is a cryptographic (one-way) hash function, so there is no direct way to decode it. The entire purpose of a cryptographic hash function is that you can't undo it.

One thing you can do is a brute-force strategy, where you guess what was hashed, then hash it with the same function and see if it matches. Unless the hashed data is very easy to guess, it could take a long time though.

You may find the question "Difference between hashing a password and encrypting it" interesting.