eth和tron地址互转工具类(java)
1、依赖导入
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>4.9.4</version>
</dependency>
<dependency>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-core</artifactId>
<version>0.16.2</version>
</dependency>
2、代码实现
package org.example.test;
import org.bitcoinj.core.Base58;
import org.bouncycastle.util.encoders.Hex;
import org.web3j.crypto.Keys;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class AddressChangeUtils {
public static String ethToTron(String ethAddress) {
if (ethAddress.startsWith("0x")) {
ethAddress = ethAddress.substring(2);
}
ethAddress = "41" + ethAddress;
byte[] byte1 = Hex.decode(ethAddress);
byte[] byte2 = sha256(byte1);
byte[] byte3 = sha256(byte2);
byte[] result = new byte[byte1.length + 4];
System.arraycopy(byte1, 0, result, 0, byte1.length);
System.arraycopy(byte3, 0, result, byte1.length, 4);
return Base58.encode(result);
}
public static String tronToEth(String tronAddress) {
String s = "0x" + Hex.toHexString(Base58.decodeChecked(tronAddress)).substring(2);
return Keys.toChecksumAddress(s);
}
private static byte[] sha256(byte[] data) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return digest.digest(data);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256 algorithm not found", e);
}
}
}