IT story

Java에서 SHA-256을 통한 해시 문자열

hot-time 2020. 8. 4. 22:50
반응형

Java에서 SHA-256을 통한 해시 문자열


인터넷뿐만 아니라이 주변을 둘러 보면서 Bouncy Castle 을 발견했습니다 . Bouncy Castle (또는 다른 무료 유틸리티)을 사용하여 Java에서 문자열의 SHA-256 해시를 생성하고 싶습니다. 그들의 문서를 보면 내가하고 싶은 일에 대한 좋은 예를 찾지 못하는 것 같습니다. 여기 누구든지 나를 도울 수 있습니까?


문자열을 해시하려면 내장 MessageDigest 클래스를 사용하십시오 .

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;

public class CryptoHash {
  public static void main(String[] args) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String text = "Text to hash, cryptographically.";

    // Change this to UTF-16 if needed
    md.update(text.getBytes(StandardCharsets.UTF_8));
    byte[] digest = md.digest();

    String hex = String.format("%064x", new BigInteger(1, digest));
    System.out.println(hex);
  }
}

위의 스 니펫 digest에는 해시 된 문자열이 hex포함되며 왼쪽에 0이 채워진 16 진 ASCII 문자열이 포함됩니다.


이것은 이미 런타임 라이브러리에서 구현되었습니다.

public static String calc(InputStream is) {
    String output;
    int read;
    byte[] buffer = new byte[8192];

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] hash = digest.digest();
        BigInteger bigInt = new BigInteger(1, hash);
        output = bigInt.toString(16);
        while ( output.length() < 32 ) {
            output = "0"+output;
        }
    } 
    catch (Exception e) {
        e.printStackTrace(System.err);
        return null;
    }

    return output;
}

JEE6 + 환경에서는 JAXB DataTypeConverter를 사용할 수도 있습니다 .

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));

You don't necessarily need the BouncyCastle library. The following code shows how to do so using the Integer.toHexString function

public static String sha256(String base) {
    try{
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuffer hexString = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}

Special thanks to user1452273 from this post: How to hash some string with sha256 in Java?

Keep up the good work !


When using hashcodes with any jce provider you first try to get an instance of the algorithm, then update it with the data you want to be hashed and when you are finished you call digest to get the hash value.

MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(in.getBytes());
byte[] digest = sha.digest();

you can use the digest to get a base64 or hex encoded version according to your needs


Java 8: Base64 available:

    MessageDigest md = MessageDigest.getInstance( "SHA-512" );
    md.update( inbytes );
    byte[] aMessageDigest = md.digest();

    String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
    return( outEncoded );

I suppose you are using a relatively old Java Version without SHA-256. So you must add the BouncyCastle Provider to the already provided 'Security Providers' in your java version.

    // NEEDED if you are using a Java version without SHA-256    
    Security.addProvider(new BouncyCastleProvider());

    // then go as usual 
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String text = "my string...";
    md.update(text.getBytes("UTF-8")); // or UTF-16 if needed
    byte[] digest = md.digest();

return new String(Hex.encode(digest));

This will work with "org.bouncycastle.util.encoders.Hex" following package

return new String(Hex.encode(digest));

Its in bouncycastle jar.

참고URL : https://stackoverflow.com/questions/3103652/hash-string-via-sha-256-in-java

반응형