Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dsdstudio
Last active February 7, 2021 03:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsdstudio/9094070 to your computer and use it in GitHub Desktop.
Save dsdstudio/9094070 to your computer and use it in GitHub Desktop.
java sha-512 encryption
/**
* sha512 방식으로 암호화한 스트링을 리턴한다
*
* @param target
* @return [encrypted string]
*/
public final static String encryptSHA512(String target) {
try {
MessageDigest sh = MessageDigest.getInstance("SHA-512");
sh.update(target.getBytes());
StringBuffer sb = new StringBuffer();
for (byte b : sh.digest()) sb.append(String.format("%1$02x", 0xff & b));
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
@KennethDev
Copy link

이 주셔서 감사합니다! 내가 쓰고있는 프로그램에서 사용하기 위하여려고하고있다. (PS :이 나쁜 한국인 경우 미안 해요, 난 구글 번역 사용하고 있습니다)

@odiszapc
Copy link

Thats wrong. Correct implementation is:

private static String getHashCodeFromString(String str) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-512);
    md.update(str.getBytes());
    byte byteData[] = md.digest();

    //convert the byte to hex format method 1
    StringBuffer hashCodeBuffer = new StringBuffer();
    for (int i = 0; i < byteData.length; i++) {
        hashCodeBuffer.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }
    return hashCodeBuffer.toString();
}

To check yourslef you can try

echo -n "key-string" | sha512sum | awk '{print $1}'

@Oladapo95
Copy link

You missed a semi-colon boy

@creambun
Copy link

creambun commented Feb 6, 2018

I agree with odizapc. Or you can replace this line:

for (byte b : sh.digest()) sb.append(Integer.toHexString(0xff & b));

with this:

for (byte b : sh.digest()) sb.append(String.format("%1$02x", 0xff & b));

After all, thanks to dsdstudio and everyone

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment