Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Sign.signatureDataFromHex #1916

Merged
merged 5 commits into from
Aug 2, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions crypto/src/main/java/org/web3j/crypto/Sign.java
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,42 @@ public static Sign.SignatureData createSignatureData(
return new Sign.SignatureData(v, r, s);
}

/**
* Returns SignatureData from hex signature.
*
* @param hexSignature hex representation of signature
* @return SignatureData
* @throws RuntimeException if signature has invalid format
*/
public static SignatureData signatureDataFromHex(String hexSignature) throws SignatureException {
NickSneo marked this conversation as resolved.
Show resolved Hide resolved
byte[] sigBytes = Numeric.hexStringToByteArray(hexSignature);
byte v;
byte[] r, s;
if (sigBytes.length == 64) {
// EIP-2098; pull the v from the top bit of s and clear it
v = (byte) (27 + (sigBytes[32] >> 7));
sigBytes[32] &= 0x7f;
r = Arrays.copyOfRange(sigBytes, 0, 32);
s = Arrays.copyOfRange(sigBytes, 32, 64);

} else if (sigBytes.length == 65) {
r = Arrays.copyOfRange(sigBytes, 0, 32);
s = Arrays.copyOfRange(sigBytes, 32, 64);
v = sigBytes[64];
} else {
throw new SignatureException("invalid signature string");
}
// Allow a recid to be used as the v
if (v < 27) {
if (v == 0 || v == 1) {
v += 27;
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Show resolved Hide resolved
} else {
throw new SignatureException("signature invalid v byte");
}
}
return new Sign.SignatureData(v, r, s);
}

/**
* Given the components of a signature and a selector value, recover and return the public key
* that generated the signature according to the algorithm in SEC1v2 section 4.1.6.
Expand Down