How can I create an SHA512 digest string in Java using bouncy castle?

前端 未结 4 1854
梦谈多话
梦谈多话 2020-12-24 08:52

This unit test is failing:

    public void testDigest() throws NoSuchAlgorithmException {
    String hashExpected = \"150a14ed5bea6cc731cf86c41566ac427a8db48         


        
相关标签:
4条回答
  • 2020-12-24 09:43

    Just an addition to Kevin's answer: Since Java 5, you can use String.format("%0128x", new BigInteger(1, digesta)) instead of commons-codec to format the byte array as a 128 digit hex encoded number with leading zeros.

    0 讨论(0)
  • 2020-12-24 09:44

    Since BouncyCastle 1.49 there is a handful toHexString method in the Hex class. For example:

    Hex.toHexString(digest);
    

    will return you the hash digest as a Java String in a hexadecimal format.

    For reference see BouncyCastle javadoc or grepcode.

    0 讨论(0)
  • 2020-12-24 09:46

    Yes, you need to turn your byte array into a hex string. :-) Look into Apache Commons Codec, especially the Hex class.

    0 讨论(0)
  • 2020-12-24 09:50

    The value you're expecting is a Hex-encoded value. You're creating a String based on the raw bytes, which won't work.

    You should use the standard Java Crypto API whenever possible instead of BouncyCastle specific APIs.

    Try the following (the Hex library comes from commons-codec):

    Security.addProvider(new BouncyCastleProvider());
    
    String data = "hello world";
    
    MessageDigest mda = MessageDigest.getInstance("SHA-512", "BC");
    byte [] digesta = mda.digest(data.getBytes());
    
    MessageDigest mdb = MessageDigest.getInstance("SHA-512", "BC");
    byte [] digestb = mdb.digest(data.getBytes());
    
    System.out.println(MessageDigest.isEqual(digesta, digestb));
    
    System.out.println(Hex.encodeHex(digesta));
    
    0 讨论(0)
提交回复
热议问题