Delphi代码:
uses
IdGlobal, IdHashSHA, IdHMACSHA1, IdSSLOpenSSL
//Add by wh 2021-03-19
function HMACSHA256(const sValue, sKey: String): String;
var
hmac: TIdHMACSHA256;
hash: TIdBytes;
begin
LoadOpenSSLLibrary;
if not TIdHashSHA256.IsAvailable then
raise Exception.Create('SHA256 hashing is not available!');
hmac := TIdHMACSHA256.Create;
try
hmac.Key := IndyTextEncoding_UTF8.GetBytes(sKey);
hash := hmac.HashValue(IndyTextEncoding_UTF8.GetBytes(sValue));
Result := LowerCase(ToHex(hash));
finally
hmac.Free;
end;
end;
//Add by wh 2021-03-19 23:55:18
function HMACSHA256_BASE64(const sValue, sKey: string): string;
function IdBytesToAnsiString(ParamBytes: TIdBytes): AnsiString;
var
i: Integer;
S: AnsiString;
begin
S := '';
for i := 0 to Length(ParamBytes) - 1 do
begin
S := S + AnsiChar(ParamBytes[i]);
end;
Result := S;
end;
var
hmac: TIdHMACSHA256;
hash: TIdBytes;
begin
LoadOpenSSLLibrary;
if not TIdHashSHA256.IsAvailable then
raise Exception.Create('SHA256 hashing is not available!');
hmac := TIdHMACSHA256.Create;
try
hmac.Key := IndyTextEncoding_UTF8.GetBytes(sKey);
hash := hmac.HashValue(IndyTextEncoding_UTF8.GetBytes(sValue));
Result := EncodeString(IdBytesToAnsiString(hash));
finally
hmac.Free;
end;
end;
JAVA代码:
public static void main(String[] args) throws Exception {
String s1=BASE64_HMACSHA256("123","21+20t4jm4DlkMv3nA5OSf76GrH+ifEORkO3T2yztec=");
System.out.println(s1);
}
public static String BASE64_HMACSHA256(String data, String key) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"));
byte[] signData = mac.doFinal(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : signData) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
System.out.println(sb.toString());
java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
// System.out.println(encoder.encodeToString(signData));
return encoder.encodeToString(signData);
}
JAVA中计算结果:
在线计算结果:
原创文章,转载请注明出处!谢谢