Created
April 1, 2014 07:18
-
-
Save whatnick/9909355 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.whatnick.btc; | |
import java.math.BigInteger; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.util.Arrays; | |
public class btc_validate { | |
private final static String template = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; | |
public static boolean check_bc(String BTC_address) | |
{ | |
byte[] decoded = decode_base58(BTC_address); | |
byte[] sig = Arrays.copyOfRange(decoded, 21, 25); | |
try { | |
MessageDigest digest = MessageDigest.getInstance("SHA-256"); | |
byte[] digest1 = digest.digest(Arrays.copyOf(decoded,21)); | |
byte[] digest2 = Arrays.copyOfRange(digest.digest(digest1),0,4); | |
System.out.println(bytesToHex(digest2)); | |
System.out.println(bytesToHex(sig)); | |
return Arrays.equals(digest2, sig ); | |
} catch (NoSuchAlgorithmException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
return false; | |
} | |
} | |
private static byte[] decode_base58(String BTC_address) | |
{ | |
BigInteger n = BigInteger.ZERO; | |
char[] chars = BTC_address.toCharArray(); | |
for (char c : chars) { | |
//check for valid chars | |
long index = template.indexOf(c); | |
if (index<0) return null; | |
n = (n.multiply(BigInteger.valueOf(58))).add(BigInteger.valueOf(index)); | |
} | |
byte[] out = new byte[25]; | |
byte[] unpadded = n.toByteArray(); | |
for(int i=1;i<=unpadded.length;i++) | |
{ | |
out[25-i] = unpadded[unpadded.length-i]; | |
} | |
return out; | |
} | |
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); | |
public static String bytesToHex(byte[] bytes) { | |
char[] hexChars = new char[bytes.length * 2]; | |
for ( int j = 0; j < bytes.length; j++ ) { | |
int v = bytes[j] & 0xFF; | |
hexChars[j * 2] = hexArray[v >>> 4]; | |
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; | |
} | |
return new String(hexChars); | |
} | |
public static void main(String[] args) | |
{ | |
String bc = "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"; | |
System.out.println(check_bc(bc)); | |
System.out.println(check_bc(bc.replace('N', 'P'))); | |
System.out.println(check_bc("1111111111111111111114oLvT2")); | |
System.out.println(check_bc("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment