Skip to content

Verify the hash of Telegram.WebApp.initDataUnsafe #724

Open
@prog-ape

Description

@prog-ape

public static Boolean checkHash(String token, String hash, String initData) {
try {
byte[] by = hmacSHA256("WebAppData", token);
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(by, "HmacSHA256");
hmacSha256.init(secret_key);
hmacSha256.update(initData.getBytes());
byte[] bytes = hmacSha256.doFinal();
return StringUtils.equalsIgnoreCase(hash, byteArrayToHexString(bytes));
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

public static String byteArrayToHexString(byte[] b) {
    StringBuilder hs = new StringBuilder();
    String stmp;
    for (int n = 0; b != null && n < b.length; n++) {
        stmp = Integer.toHexString(b[n] & 0XFF);
        if (stmp.length() == 1)
            hs.append('0');
        hs.append(stmp);
    }
    return hs.toString().toLowerCase();
}

public static byte[] hmacSHA256(String key, String data)
        throws NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(secretKeySpec);
    return mac.doFinal(data.getBytes());
}

Is there something wrong with my code? Why is it always false? It worked at first, but later it stopped working because of some update in miniapp

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions