public static byte[] doubleDigest(byte[] input) { return doubleDigest(input, 0, input.length); }
/** * Uses the checksum in the last 4 bytes of the decoded data to verify the rest * are correct. The checksum is removed from the returned data. * * @throws Exception * if the input is not base 58 or the checksum does not validate. */ public static byte[] decodeChecked(String input) throws Exception { byte[] tmp = decode(input); if (tmp.length < 4) throw new Exception("Input too short"); byte[] checksum = new byte[4]; System.arraycopy(tmp, tmp.length - 4, checksum, 0, 4); byte[] bytes = new byte[tmp.length - 4]; System.arraycopy(tmp, 0, bytes, 0, tmp.length - 4); tmp = doubleDigest(bytes); byte[] hash = new byte[4]; System.arraycopy(tmp, 0, hash, 0, 4); if (!Arrays.equals(hash, checksum)) throw new Exception("Checksum does not validate"); return bytes; }
/** * Generate unique id by creating a UUID and encoding the bytes in base 58. * * @return */ protected String generateUniqueId() { UUID uuid = UUID.randomUUID(); ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return Base58.encode(bb.array()); }
public static byte[] decode(String input) throws Exception { byte[] bytes = decodeToBigInteger(input).toByteArray(); // We may have got one more byte than we wanted, if the high bit of the // next-to-last byte was not zero. This // is because BigIntegers are represented with twos-compliment notation, thus if // the high bit of the last // byte happens to be 1 another 8 zero bits will be added to ensure the number // parses as positive. Detect // that case here and chop it off. boolean stripSignByte = bytes.length > 1 && bytes[0] == 0 && bytes[1] < 0; // Count the leading zeros, if any. int leadingZeros = 0; for (int i = 0; input.charAt(i) == ALPHABET.charAt(0); i++) { leadingZeros++; } // Now cut/pad correctly. Java 6 has a convenience for this, but Android can't // use it. byte[] tmp = new byte[bytes.length - (stripSignByte ? 1 : 0) + leadingZeros]; System.arraycopy(bytes, stripSignByte ? 1 : 0, tmp, leadingZeros, tmp.length - leadingZeros); return tmp; }