【问题标题】:Generate SHA 256 Hash using multiple values in Java/Android在 Java/Android 中使用多个值生成 SHA 256 哈希
【发布时间】:2014-06-11 10:09:05
【问题描述】:

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

第一个值是 JSONObject 第二个值是 String 变量。

理想情况下,我需要的是

Hash hash=new Hash(JSONObject, String);

我找不到任何采用两个值的哈希生成方法。

谁能帮我解决这个问题。

【问题讨论】:

  • 由你决定以某种方式合并这两个值,也许使用 StringBuilder。

标签: java android hash sha


【解决方案1】:

SHA 256 将字节数组用作输入。您需要将 JSONObject 和 String 转换为字节数组,然后在这些字节数组的连接上计算 SHA 256 哈希。

【讨论】:

    【解决方案2】:

    使用 key 和 value 生成 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();  
            } 
    

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 2014-08-19
      • 2011-04-18
      • 2011-03-22
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 2023-03-18
      • 2011-03-07
      相关资源
      最近更新 更多