Skip to content

Commit

Permalink
Create CryptoLib.sol
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored Oct 20, 2024
1 parent 95ac512 commit 44af80e
Showing 1 changed file with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

library CryptoLib {
// Hash a message using keccak256
function hashMessage(bytes memory message) internal pure returns (bytes32) {
return keccak256(message);
}

// Verify a signature
function verifySignature(
bytes32 messageHash,
bytes memory signature,
address signer
) internal pure returns (bool) {
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == signer;
}

// Get the Ethereum signed message hash
function getEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash));
}

// Recover the signer from a signature
function recoverSigner(bytes32 ethSignedMessageHash, bytes memory signature) internal pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = splitSignature(signature);
return ecrecover(ethSignedMessageHash, v, r, s);
}

// Split the signature into r, s, and v
function splitSignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) {
require(signature.length == 65, "CryptoLib: invalid signature length");
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// Adjust v value
if (v < 27) {
v += 27;
}
}
}

0 comments on commit 44af80e

Please sign in to comment.