@n3okill/utils
Version:
Many javascript helpers
25 lines • 1.24 kB
JavaScript
import * as NodeCrypto from "crypto";
/**
* Validates if the given data is tampered.
* @param data Data to be validated. The data must be previously
* generated by `[hashData()]`.
* @param key Secret key that was previously used to generate the hash for the data in `[hashData()]`.
* function to see the supported hashing algorithms on your system. This must be the same
* as the value passed to `[hashData()]` when generating the hash for the data.
* @param algorithm Algorithm used to generate the data
* @return the real data with the hash stripped off. False if the data is tampered.
* @see hashData()
*/
export function validateData(data, key, algorithm = "sha256") {
const hashLength = NodeCrypto.createHmac(algorithm, key).update("test").digest("base64").length;
if (data.length >= hashLength) {
const hash = data.substring(0, hashLength);
const pureData = data.substring(hashLength, data.length);
const calculatedHash = NodeCrypto.createHmac(algorithm, key).update(pureData).digest("base64");
if (NodeCrypto.timingSafeEqual(Buffer.from(hash), Buffer.from(calculatedHash))) {
return pureData;
}
}
return false;
}
//# sourceMappingURL=validateData.js.map