Ethereum: Extracting ECDSA ras Encoded as Signatures
Electronic Cash Transactions (ECC) are a type of digital currency that uses the Elliptic Curve Digital Signature Algorithm (ECDSA) to create secure and private signatures. In this article, we will explore how to extract the r and s components from an ECDSA signed message in Ethereum.
ECDSA and Signature Construction Overview
When creating a signature using ECDSA, two key components are created: r
and s
. These values are used to sign messages and are part of the elliptic curve. In this article, we will focus on extracting r
and s
from an ECDSA signed message.
How to Extract r and s
The process of extracting r
and s
involves several steps:
- Hashing: First, you need to hash the input signature using the
verifyingKey
(i.e.v
,p
, andq
). This creates a digest that matches the signed message.
- Split the digest: Next, split the digest into two parts: the first part is used to extract
r
ands
, while the second part is discarded.
- Encode the ECDSA values
: In Ethereum, each r and s is encoded as a pair of byte arrays (
[r, s]
). To extract these values, you need to take the first two bytes (or four bytes) from the first half of the digest.
Code example
To illustrate this process, consider an example in Solidity:
pragma strength ^ 0,8,0;
contract signature {
// ... more functions ...
function sign(string memory sigStr) public returns (bytes32 r, bytes32 s) {
// Hash the input signature with the verification key
bytes32 digest = keccak256(abi.encodePacked(sigStr));
// Split the digest into two halves
uint160 firstHalf = uint160(commit);
uint160 secondHalf = uint160(digest) | 0x80000000;
// Encode the ECDSA values as a pair of byte arrays
bytes32 r;
bytes32 s;
uint8 i, j;
for (i = 1; i < firstHalf + 128; i++) {
j = i + 2;
r = keccak256(abi.encodePacked((first half & 0x7FFFFFFF) << (j - 1), (second half >> 64) | ((j - 2) * 65536)));
}
for (i = 1; i < second half + 128; i++) {
j = i + 2;
s = keccak256(abi.encodePacked((first half & 0x7FFFFFFF) << (j - 1), ((second half >> 64) | ((j - 2) * 65536))));
}
return (r, s);
}
}
In this example, the sign
function takes a signed message as input and returns the corresponding values r and s. The function first hashes the input signature with the verification key and then splits the digest into two halves. Finally, it encodes the ECDSA values as a pair of byte fields using the Keccak-256 hash function.
Conclusion
In this article, we explored how to extract the r
and s
components from an ECDSA signed message on Ethereum. By understanding the process of hashing, hashing, and encoding ECDSA values as a pair of byte fields, you can now write your own functions to sign messages using ECC signatures.