有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java/Android中使用多个值生成SHA256哈希

我有两个对象,需要根据它们生成SHA 256哈希

第一个值是一个JSONObject 第二个值是一个字符串变量

理想情况下,我需要的是

Hash Hash=新的Hash(JSONObject,String)

我找不到任何接受两个值的哈希生成方法

有人能帮我吗


共 (1) 个答案

  1. # 1 楼答案

    使用键和值生成sha256哈希代码的正确方法

       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();  
            }