普通私钥32B,版本号以"00"开头
WIF(Wallet Import Format)格式私钥51位,以“5”开头,版本号以"80"开头
wif压缩格式52位,以“L"/"K"开头,最后一位为是否压缩
wif格式可以自动侦测地址错误,通过私钥的hash值产生校验码
package crypto;
public class BitcoinAddressUtil {
/**
* 将16进制私钥转成WIF格式或WIF-compressed格式
* flag:boolean,是否采用压缩格式.true:压缩格式
*/
public static String generatePrivateKeyWIF(String hexprivKey, boolean flag) {
String versionStr = "";
if (flag) {
versionStr = "80" + hexprivKey + "01";
} else {
versionStr = "80" + hexprivKey;
}
try {
String hashDouble = HashUtils.sha256(HashUtils.hexToByteArray(HashUtils.sha256(HashUtils.hexToByteArray(versionStr))));
String checkSum = hashDouble.substring(0, 8);
String strPrivKey = versionStr + checkSum;
return Base58Util.encode(HashUtils.hexToByteArray(strPrivKey));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* WIF格式私钥返回到16进制格式
*
* @param wifPrivKey ,WIF格式私钥
*/
public static String getHexPrivateKey(String wifPrivKey) {
validateWifPrivateKey(wifPrivKey);
boolean flag = true;
if (wifPrivKey.length() == 51 && wifPrivKey.indexOf("5") == 0) {
flag = false;
}
byte[] arrPrivKey = Base58Util.decode(wifPrivKey);
String hexStr = HashUtils.byte2HexStr(arrPrivKey);
String result = "";
if (flag) {
result = hexStr.substring(2, hexStr.length() - 10);
} else {
result = hexStr.substring(2, hexStr.length() - 8);
}
return result;
}
//验证wif私钥是否有效
public static boolean validateWifPrivateKey(String wifPrivateKey) {
byte[] arrPrivateKey = Base58Util.decode(wifPrivateKey);
String hexStr = HashUtils.bytesToHex(arrPrivateKey);
String checksum = hexStr.substring(hexStr.length() - 8);
String versionStr = hexStr.substring(0, hexStr.length() - 8);
try {
String checksumNew = HashUtils.sha256(HashUtils.hexToByteArray(HashUtils.sha256(HashUtils.hexToByteArray(versionStr)))).substring(0, 8);
if (checksum.equals(checksumNew)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
String ss = generatePrivateKeyWIF("18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725", false);
System.out.println(ss);
String hexPrivateKey = getHexPrivateKey("Kx45GeUBSMPReYQwgXiKhG9FzNXrnCeutJp4yjTd5kKxCitadm3C");
System.out.println(hexPrivateKey);
boolean flag = validateWifPrivateKey("5J1F7GHadZG3sCCKHCwg8Jvys9xUbFsjLnGec4H125Ny1V9nR6V");
System.out.println(flag);
}
}