public static String hash(String s) { try { String a = toHex(md5(s)); if (a != null) { return new String(a.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); } else { return ""; } } catch (Exception e) { log.error("not supported charset...{}", e.getMessage()); return s; } }方法md5可以为空数组吗
时间: 2024-02-14 08:23:04 浏览: 60
方法`md5`返回值可以为空数组,但是在该方法中,即使`md5`方法返回了空数组,由于`toHex`方法不会返回`null`,因此在`String a = toHex(md5(s));`行上,`a`变量不会为`null`,而是一个空字符串。因此,即使`md5`方法返回空数组,该方法最终返回的也将是一个空字符串或输入字符串`s`,而不是`null`。不能为空数组的情况可以在调用`toHex`方法的地方进行必要的空值检查,以避免`NullPointerException`异常。
相关问题
public static String hash(String s) { try { String a = toHex(md5(s)); if (a != null) { return new String(a.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); } else { return ""; } } catch (Exception e) { log.error("not supported charset...{}", e.getMessage()); return s; } } 方法md5可以为null吗
方法`md5`返回值可以为`null`,如果在`try`块中出现异常,或者`catch`块中的错误处理程序返回`null`,则该方法返回值为`null`。在`try`块中,如果`MessageDigest.getInstance("MD5")`或`algorithm.update(s.getBytes("UTF-8"))`抛出异常,那么`algorithm.digest()`将不会被调用,`messageDigest`将为`null`。在`catch`块中,如果出现异常,那么`md5`方法将返回`null`,因为`return null;`语句在`catch`块中。因此,需要在调用`md5`方法的地方进行必要的空值检查,以避免`NullPointerException`异常。
public static String hmacsha256(String plainStr, String key) { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(Charset.forName("UTF-8")), "HmacSHA256"); Mac mac=null; try { mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } byte digest[] = mac.doFinal(plainStr.getBytes(Charset.forName("UTF- 8"))); return new StringBuilder().append(byte2HexStr(digest)).toString(); } public static String byte2HexStr(byte array[]) { return array != null ? new String(Hex.encodeHex(array)) : null; } java to PHP
Here's the PHP equivalent of the Java code for computing HMAC-SHA256:
```
function hmacsha256($plainStr, $key) {
$secretKey = utf8_encode($key);
$digest = hash_hmac('sha256', utf8_encode($plainStr), $secretKey, true);
return bin2hex($digest);
}
```
Note that in PHP, the `hash_hmac` function is used to compute the HMAC with SHA256. The third parameter of `hash_hmac` is set to `true` to get the output as raw binary data. The `bin2hex` function is then used to convert the binary data to a hexadecimal string, which is the same format as the output of the `byte2HexStr` function in the Java code.
Also note that in PHP, strings are already represented as Unicode, so there's no need to convert the key and plain string to UTF-8 encoding using the `Charset.forName("UTF-8")` method.
阅读全文