Skip to content

Commit

Permalink
Adding MixedCaseChecksum feature implementing EIP55 standard
Browse files Browse the repository at this point in the history
  • Loading branch information
AB3rtz committed Sep 15, 2022
1 parent e1022c5 commit 7f4dd58
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.syntifi.crypto.key.checksum;

import org.bouncycastle.jcajce.provider.digest.Keccak;
import org.bouncycastle.util.encoders.Hex;

/**
* Implementation of the EIP-55: Mixed-case checksum address encoding
* Documentation available at: https://eips.ethereum.org/EIPS/eip-55
*
* @author Alexandre Carvalho
* @author Andre Bertolace
* @since 0.5.0
*/
public class MixedCaseChecksum {

public static String kekkac256(String value) {
Keccak.DigestKeccak kekkac256 = new Keccak.Digest256();
byte[] hash = kekkac256.digest(value.getBytes());
return Hex.toHexString(hash);
}

public static String checksumEncode(String address) {
Boolean withPrefix = address.startsWith("0x");
String value = address.toLowerCase().replace("0x", "");
char[] hash = kekkac256(value).toCharArray();
char[] chars = value.toCharArray();
char[] encoded = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
encoded[i] = Character.digit(hash[i], 16) > 7
? Character.toUpperCase(chars[i])
: chars[i];
}
return withPrefix
? "0x" + String.valueOf(encoded)
: String.valueOf(encoded);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.syntifi.crypto.key.checksum;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class MixedCaseChecksumTest {

@Test
void shouldMatchLowerCaseAddress() {
assertEquals("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359",
MixedCaseChecksum.checksumEncode("0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359"));
}

@Test
void shouldMatchUpperCaseAddress() {
assertEquals("0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359",
MixedCaseChecksum.checksumEncode("0xFB6916095CA1DF60BB79CE92CE3EA74C37C5D359"));
}

@Test
void kekkac256ShouldMatch() {
assertEquals("a9059cbb2ab09eb219583f4a59a5d0623ade346d962bcd4e46b11da047c9049b",
MixedCaseChecksum.kekkac256("transfer(address,uint256)"));
}
}

0 comments on commit 7f4dd58

Please sign in to comment.