普通私鑰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);
}
}