1

I have two objects based on which SHA 256 Hash needs to be generated.

First value is a JSONObject Second value is a String variable.

Ideally, what i need is

Hash hash= new Hash(JSONObject, String);

I couldn't find any hash generation methods which takes two values.

Could anyone help me with this?.

1
  • It's up to you to somehow merge those two values, perhaps with a StringBuilder. Commented May 30, 2014 at 16:21

2 Answers 2

1

SHA 256 works on a byte array as input. You need to convert your JSONObject and your String to byte arrays, then calculate the SHA 256 hash on the concatenation of these byte arrays.

Sign up to request clarification or add additional context in comments.

Comments

0

The proper way of generating a sha256 hashcode using key and value

   public static String hashMac(String text, String secretKey)
                  throws SignatureException {

                 try {
                  Key sk = new SecretKeySpec(secretKey.getBytes(), HASH_ALGORITHM);
                  Mac mac = Mac.getInstance(sk.getAlgorithm());
                  mac.init(sk);
                  final byte[] hmac = mac.doFinal(text.getBytes());
                  return toHexString(hmac);
                 } catch (NoSuchAlgorithmException e1) {
                  // throw an exception or pick a different encryption method
                  throw new SignatureException(
                    "error building signature, no such algorithm in device "
                      + HASH_ALGORITHM);
                 } catch (InvalidKeyException e) {
                  throw new SignatureException(
                    "error building signature, invalid key " + HASH_ALGORITHM);
                 }
    }

    public static String toHexString(byte[] bytes) {  
            StringBuilder sb = new StringBuilder(bytes.length * 2);  

            Formatter formatter = new Formatter(sb);  
            for (byte b : bytes) {  
                formatter.format("%02x", b);  
            }  

            return sb.toString();  
        } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.