ylliX - Online Advertising Network
Vertex AI - Antrophic and Mistral models: Why does it require Imegen access?

Digital Signature of Hash (HMACSHA256) in Java using SHA256 algorithm & Pkcs1 RSA signature padding didn’t match with dot net implementation


I am trying to create digital signature of the hash (created using HMACSHA256) in Java using SHA256 algorithm & Pkcs1 RSA signature padding but it is not producing the same signature as implemented in .net by vendor.

My Java code :

private String hmacSha256(String data, String key) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    mac.init(secretKeySpec);
    byte[] hmacSha256Bytes = mac.doFinal(data.getBytes("UTF-8"));
    return Base64.getEncoder().encodeToString(hmacSha256Bytes);
}

private String signHash(String hash, PrivateKey privateKey) throws Exception {
    Signature signature = Signature.getInstance("SHA256withRSA", "BC");
    signature.initSign(privateKey);
    signature.update(Base64.getDecoder().decode(hash));
    byte[] signedBytes = signature.sign();
    return Base64.getEncoder().encodeToString(signedBytes);
}

private String signMessage(String hashedMsg, PrivateKey privateKey) throws Exception {
    Signature signature = Signature.getInstance("SHA256withRSA", "BC");
    signature.initSign(privateKey);
    signature.update(hashedMsg.getBytes("UTF-8"));
    byte[] signedBytes = signature.sign();
    return Base64.getEncoder().encodeToString(signedBytes);
}

SignHash is adding signature to a already hashed message whereas SignMessage is adding hash again to already hashed message and then adding signature. SignMessage is making the correct signature as per the vendor but SignHash is creating different.

Dotnet code implementation for SignHash function by vendor :

RSA rSA = RSA.Create();
rSA.ImportRSAPrivateKey(array, out var _);
byte[] hash = Convert.FromBase64String(message);
byte[] inArray = rSA.SignHash(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return Convert.ToBase64String(inArray);



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *