public String createSha1(File file) throws TechnicalException { try (InputStream fis = new FileInputStream(file);) { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); int n = 0; byte[] buffer = new byte[8192]; while (n != -1) { n = fis.read(buffer); if (n > 0) { sha1.update(buffer, 0, n); } } return new HexBinaryAdapter().marshal(sha1.digest()); } catch (NoSuchAlgorithmException | IOException e) { throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE_CHECKSUM_IO_EXCEPTION), e); } }
private void inviteUser(GameProfile profile) { MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); Gson gson = new Gson(); UserListWhitelist whitelistedPlayers = server.getConfigurationManager().func_152599_k(); final ArrayList<String> tempHash = new ArrayList<String>(); String name = profile.getName().toLowerCase(); try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(whitelistedPlayers.func_152706_a(name).getId().toString().getBytes(Charset.forName("UTF-8"))); tempHash.add((new HexBinaryAdapter()).marshal(hash)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } CreeperHostServer.InviteClass invite = new CreeperHostServer.InviteClass(); invite.hash = tempHash; invite.id = CreeperHostServer.updateID; Util.putWebResponse("https://api.creeper.host/serverlist/invite", gson.toJson(invite), true, true); }
private void removeUser(GameProfile profile) { MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); Gson gson = new Gson(); final ArrayList<String> tempHash = new ArrayList<String>(); try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(profile.getId().toString().getBytes(Charset.forName("UTF-8"))); tempHash.add((new HexBinaryAdapter()).marshal(hash)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } CreeperHostServer.InviteClass invite = new CreeperHostServer.InviteClass(); invite.hash = tempHash; invite.id = CreeperHostServer.updateID; CreeperHostServer.logger.debug("Sending " + gson.toJson(invite) + " to revoke endpoint"); String resp = Util.putWebResponse("https://api.creeper.host/serverlist/revokeinvite", gson.toJson(invite), true, true); CreeperHostServer.logger.debug("Response from revoke endpoint " + resp); }
public static String getPlayerHash(UUID uuid) { if (hashCache.containsKey(uuid)) return hashCache.get(uuid); String playerHash; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(uuid.toString().getBytes(Charset.forName("UTF-8"))); playerHash = (new HexBinaryAdapter()).marshal(hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } hashCache.put(uuid, playerHash); return playerHash; }
@ApiMethod @Comment(value = "Hash the bytes with the given algorithm") public static String hash(byte[] byteArr, String algorithm) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); digest.update(byteArr); byte[] bytes = digest.digest(); String hex = (new HexBinaryAdapter()).marshal(bytes); return hex; } catch (Exception ex) { Lang.rethrow(ex); } return null; }
public static String calcSHA(File file) throws Exception { MessageDigest sha1 = MessageDigest.getInstance("SHA-512"); InputStream input = new FileInputStream(file); try { byte[] buffer = new byte[8192]; int len = input.read(buffer); while (len != -1) { sha1.update(buffer, 0, len); len = input.read(buffer); } input.close(); return new HexBinaryAdapter().marshal(sha1.digest()); } catch (Exception ex) { return ""; } }
public static void main(String[] args) throws IOException { final byte[] bytes2 = Base64.getDecoder().decode("YnsLfVSN"); System.out.println(new HexBinaryAdapter().marshal(bytes2)); if(true) { return; } String filename = "/Users/esinev/Library/Preferences/IdeaIC15/scratches/docker-create-endpoint.txt"; LineNumberReader reader = new LineNumberReader(new FileReader(filename)); String line; while (( line = reader.readLine()) != null) { // System.out.println(line); if(line.length() >= 50 && line.charAt(48) == ' ' && line.charAt(49) == ' ') { String hex = line.substring(0, 49); final byte[] bytes = new HexBinaryAdapter().unmarshal(hex.replace(" ", "")); String value = new String(bytes); System.out.print(value); // line = line.substring(50); } else { System.out.println(line); } // System.out.println(line); } }
@Test public void testUUIDConverter() throws ConverterException { UUID uuid = UUID.randomUUID(); OracleQuirks orclQuirks = new OracleQuirks(); Converter<UUID> uuidConverter = new OracleUUIDConverter(); byte[] rawUuid = (byte[])uuidConverter.toDatabaseParam(uuid); UUID reconvertedUuid = uuidConverter.convert(rawUuid); assertEquals(uuid, reconvertedUuid); // convert bytes to hex and put hyphens into the string to recreate the UUID string representation, just to be // sure everything is done correct. String hex = new HexBinaryAdapter().marshal(rawUuid); String hexUuid = String.format("%s-%s-%s-%s-%s", hex.substring(0,8), hex.substring(8,12), hex.substring(12, 16), hex.substring(16, 20), hex.substring(20)).toLowerCase(); assertEquals(uuid.toString(), hexUuid); }
private String sha2OfBigger(File f) { try (FileChannel ch = new RandomAccessFile(f, "r").getChannel()) { int size = (int) Math.min(f.length(), Integer.MAX_VALUE); MappedByteBuffer byteBuffer // 2G = ch.map(FileChannel.MapMode.READ_ONLY, 0, size); MessageDigest sha2 = MessageDigest.getInstance("SHA-256"); long offset = 0; byte[] array = new byte[Integer.MAX_VALUE >> 2]; while (size != 0) { while (byteBuffer.remaining() > 0) { int numInArray = Math.min(array.length, byteBuffer.remaining()); byteBuffer.get(array, 0, numInArray); sha2.update(array, 0, numInArray); } offset += size; size = (int) Math.min(Integer.MAX_VALUE, f.length() - offset); byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, offset, size); } return new HexBinaryAdapter().marshal(sha2.digest()); } catch (IOException | NoSuchAlgorithmException e) { e.printStackTrace(); return "\\"; } }
private String sha2Of(File file) { if (file.length() > Integer.MAX_VALUE >> 2) { return sha2OfBigger(file); } try (FileChannel ch = new FileInputStream(file).getChannel()) { byte[] arry = new byte[1024 * 8]; ByteBuffer byteBuffer = ByteBuffer.wrap(arry); int size = ch.read(byteBuffer); MessageDigest sha2 = MessageDigest.getInstance("SHA-256"); while (size != -1) { sha2.update(arry, 0, size); byteBuffer.rewind(); size = ch.read(byteBuffer); } return new HexBinaryAdapter().marshal(sha2.digest()); } catch (IOException | NoSuchAlgorithmException e) { e.printStackTrace(); return "\\"; } }
private static String calcSHA1(File file) throws IOException, NoSuchAlgorithmException { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); // todo algorithm here?? try (InputStream input = new FileInputStream(file)) { byte[] buffer = new byte[1024 * 8]; int len = input.read(buffer); while (len != -1) { sha1.update(buffer, 0, len); len = input.read(buffer); } return new HexBinaryAdapter().marshal(sha1.digest()); } }
private String calculateSha1(File file) throws MojoExecutionException { InputStream input = null; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); input = new FileInputStream(file); byte[] buffer = new byte[8192]; int len; while ((len = input.read(buffer)) != -1) { messageDigest.update(buffer, 0, len); } return new HexBinaryAdapter().marshal(messageDigest.digest()); } catch (Exception exception) { throw new MojoExecutionException("Could not create SHA1 of file [" + file + "]"); } finally { IOUtils.closeQuietly(input); } }
/** * Calculate and return the sha1 sum of an input stream * * @param in the input stream to calculate the sha1 sum of * * @return the sha1 sum * * @throws IOException if there was an error calculating the sha1 sum */ public static String calculateSha1(InputStream in) throws IOException { MessageDigest messageDigest; InputStream inputStream = null; try { messageDigest = MessageDigest.getInstance("SHA-1"); inputStream = new BufferedInputStream(in); byte[] buffer = new byte[8192]; int len = inputStream.read(buffer); while (len != -1) { messageDigest.update(buffer, 0, len); len = inputStream.read(buffer); } return(new HexBinaryAdapter().marshal(messageDigest.digest())); } catch (NoSuchAlgorithmException ex) { throw new IOException(ex); } finally { IOUtils.closeQuietly(inputStream); } }
@Test public void testSigning() throws AddressFormatException { NetworkParameters netParams = TestNet3Params.get(); HexBinaryAdapter adapter = new HexBinaryAdapter(); Context context = Context.getOrCreate(netParams); byte[] bx = adapter.unmarshal("0100000001bd5ee90ffe5eedd67c09c3bb348dd7dc1308800eb221b1c92dda651010519ba3010000006a4730440220467868c0b2ed001a915cca5269b928698bee8aba4fe454e1d775070d9e4041cb02205d1c979dbc75e5dc656c4e9d5969d716a383797bd5ad5df79a13d0d6e3f51ccb012102403adb7674f25212bc8cf4a97797154a4980c60e9f328c90300b71a8a04389c7ffffffff024088db60000000001976a914990628d3670f439a5f9e0dfa6492b8bbf3b3fa1b88ac76cf6edd050000001976a914b679378d01ee7203a454bca2ad25698ef23a056388ac00000000"); org.bitcoinj.core.Transaction testbx = new org.bitcoinj.core.Transaction(netParams, bx); org.bitcoinj.core.Transaction tx = new org.bitcoinj.core.Transaction(netParams); tx.addOutput(org.bitcoinj.core.Coin.SATOSHI.multiply(testbx.getOutput(0).getValue().value - 50000l), new Address(netParams, "mobDb19geJ66kkQnsSYvN9PNEKNDiNBHEp")); System.out.println(testbx.getOutput(0)); tx.addInput(testbx.getOutput(0)); String seckey = "3EC95EBFEDCF77373BABA0DE345A0962E51344CD2D0C8DBDF93AEFD0B66BE240"; byte[] privkey = Hex.decode(seckey); ECKey ecPriv = ECKey.fromPrivate(privkey); Sha256Hash hash2 = tx.hashForSignature(0, testbx.getOutput(0).getScriptPubKey().getProgram(), Transaction.SigHash.ALL, false); ECKey.ECDSASignature ecSig = ecPriv.sign(hash2); TransactionSignature txSig = new TransactionSignature(ecSig, Transaction.SigHash.ALL, false); Script inputScript = ScriptBuilder.createInputScript(txSig, ECKey.fromPublicOnly(ecPriv.getPubKey())); tx.getInput(0).setScriptSig(inputScript); String hexBin = DatatypeConverter.printHexBinary(tx.bitcoinSerialize()); System.out.println(hexBin); tx.getInput(0).verify(testbx.getOutput(0)); // SUCCESSFULLY BROADCAST WOO! }
/** * This method passes an SWA attachment as a request * and expects an SWA attachment as a response. * Note that the body content in both cases is empty. * (See the wsdl) * @param attachment (swa) * @return attachment (swa) */ @WebMethod(operationName="swaAttachment", action="swaAttachment") @XmlJavaTypeAdapter(HexBinaryAdapter.class) @WebResult(name = "jpegImageResponse", targetNamespace = "", partName = "jpegImageResponse") @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) public byte[] swaAttachment( @XmlJavaTypeAdapter(HexBinaryAdapter.class) @WebParam(name = "jpegImageRequest", targetNamespace = "", partName = "jpegImageRequest") byte[] attachment) { if (attachment == null || attachment.length == 0){ throw new RuntimeException("Received empty attachment"); } else { // Change the first three characters and return the attachment attachment[0] = 'S'; attachment[1] = 'W'; attachment[2] = 'A'; } return attachment; }
@Override protected void writeToFile(List<ExportEntry> csvEntries) throws IOException { // Setup compression stuff ZipOutputStream zos = new ZipOutputStream(fileOutpuStream); zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(9); // Setup signature stuff MessageDigest md; try { md = MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException ex) { LOG.log(Level.SEVERE, "Missing hash algorithm for signature. No file exported!", ex); throw new IOException("Missing hash algorithm for signature."); } DigestOutputStream dos = new DigestOutputStream(zos, md); // write data zos.putNextEntry(new ZipEntry(DATA_ZIP_ENTRY)); CsvWriter cwriter = new CsvWriter(dos, VaultCsvEntry.CSV_DELIMITER, Charset.forName("UTF-8")); cwriter.writeRecord(((CsvEntry) csvEntries.get(0)).getCsvHeaderRecord()); for (ExportEntry item : csvEntries) { cwriter.writeRecord(((CsvEntry) item).toCsvRecord()); } cwriter.flush(); // add signature file zos.putNextEntry(new ZipEntry(SIGNATURE_ZIP_ENTRY)); String sigString = (new HexBinaryAdapter()).marshal(md.digest()); zos.write(sigString.getBytes(), 0, sigString.getBytes().length); // close everything cwriter.close(); dos.close(); zos.close(); fileOutpuStream.close(); }
private void inviteUser(GameProfile profile) { MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); Gson gson = new Gson(); UserListWhitelist whitelistedPlayers = server.getPlayerList().getWhitelistedPlayers(); final ArrayList<String> tempHash = new ArrayList<String>(); String name = profile.getName().toLowerCase(); try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(whitelistedPlayers.getByName(name).getId().toString().getBytes(Charset.forName("UTF-8"))); tempHash.add((new HexBinaryAdapter()).marshal(hash)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } CreeperHostServer.InviteClass invite = new CreeperHostServer.InviteClass(); invite.hash = tempHash; invite.id = CreeperHostServer.updateID; CreeperHostServer.logger.debug("Sending " + gson.toJson(invite) + " to add endpoint"); String resp = Util.putWebResponse("https://api.creeper.host/serverlist/invite", gson.toJson(invite), true, true); CreeperHostServer.logger.debug("Response from add endpoint " + resp); }
private void removeUser(GameProfile profile) { MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); Gson gson = new Gson(); final ArrayList<String> tempHash = new ArrayList<String>(); try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(profile.getId().toString().getBytes(Charset.forName("UTF-8"))); String hashString = (new HexBinaryAdapter()).marshal(hash); CreeperHostServer.logger.info("Removing player with hash " + hashString); tempHash.add(hashString); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } CreeperHostServer.InviteClass invite = new CreeperHostServer.InviteClass(); invite.hash = tempHash; invite.id = CreeperHostServer.updateID; CreeperHostServer.logger.debug("Sending " + gson.toJson(invite) + " to revoke endpoint"); String resp = Util.putWebResponse("https://api.creeper.host/serverlist/revokeinvite", gson.toJson(invite), true, true); CreeperHostServer.logger.debug("Response from revoke endpoint " + resp); }
/** * Converts an arbitrary message into an MD5 hash and returns it as a UTF-8 encoded string * * @param message is the message to convert * @return a UTF-8 encoded string representation of the MD5 hash */ String getMd5Hash(String message) { String result; try { MessageDigest md5 = MessageDigest.getInstance(MD5); result = (new HexBinaryAdapter()).marshal(md5.digest(message.getBytes())).toLowerCase(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error converting message to MD5 hash", e); } return result; }
public static String encode(String username, String password, byte[] salt) { HexBinaryAdapter hex = new HexBinaryAdapter(); byte[] digest, passDigest; MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } messageDigest.update(password.getBytes(UTF_8)); messageDigest.update(username.getBytes(UTF_8)); digest = messageDigest.digest(); byte[] hexDigest = hex.marshal(digest).toLowerCase().getBytes(US_ASCII); messageDigest.update(hexDigest); messageDigest.update(salt); passDigest = messageDigest.digest(); return "md5" + hex.marshal(passDigest).toLowerCase(); }
public static String sha256hash(String plaintext) { try{ MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); //Converting from bytes to hex return (new HexBinaryAdapter()).marshal(sha256.digest(plaintext.getBytes("UTF-8"))); } catch(Exception e) { System.out.println("Error while hashing: " + e.toString()); } return null; }
/** * Compute md5 hash of given stream * * @param stream stream to hash * @return hex string md5 hash * @throws NoSuchAlgorithmException * @throws IOException */ public static String md5HashStream(InputStream stream) throws NoSuchAlgorithmException, IOException { MessageDigest digest = MessageDigest.getInstance("MD5"); try (DigestInputStream expectDigestStream = new DigestInputStream(stream, digest)) { int read = 0; while ((read = expectDigestStream.read()) >= 0) { // don't care about the data } } return new HexBinaryAdapter().marshal(digest.digest()); }
static String computeMD5(String s) { try { //System.out.println("computing digest of " + file); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(s.getBytes()); return (new HexBinaryAdapter()).marshal(digest); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
public static String calculateMD5Sum(String inStr) { MessageDigest hasher = null; try{ hasher = java.security.MessageDigest.getInstance("MD5"); } catch(NoSuchAlgorithmException e){ LOG.error("Wrong hashing algorithm name provided while getting instance of MessageDigest: " + e.getLocalizedMessage()); } return (new HexBinaryAdapter()).marshal(hasher.digest(inStr.getBytes())); }
public static String hash(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes()); byte[] hashBytes = md.digest(); String hashedText = (new HexBinaryAdapter().marshal(hashBytes)); return hashedText.toLowerCase(); } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm not found."); } return null; }
private ImmutableSortedSet<String> getExistingDsData(DomainResource domain) { ImmutableSortedSet.Builder<String> dsDataJsons = ImmutableSortedSet.naturalOrder(); HexBinaryAdapter hexBinaryAdapter = new HexBinaryAdapter(); for (DelegationSignerData dsData : domain.getDsData()) { dsDataJsons.add(JSONValue.toJSONString(ImmutableMap.of( "keyTag", dsData.getKeyTag(), "algorithm", dsData.getAlgorithm(), "digestType", dsData.getDigestType(), "digest", hexBinaryAdapter.marshal(dsData.getDigest())))); } return dsDataJsons.build(); }
private void persistDomainWithHosts(HostResource... hosts) { ImmutableSet.Builder<Key<HostResource>> hostRefs = new ImmutableSet.Builder<>(); for (HostResource host : hosts) { hostRefs.add(Key.create(host)); } persistResource(newDomainResource("evil.tld").asBuilder() .setNameservers(hostRefs.build()) .setDsData(ImmutableSet.of( DelegationSignerData.create(1, 2, 3, new HexBinaryAdapter().unmarshal("dead")), DelegationSignerData.create(4, 5, 6, new HexBinaryAdapter().unmarshal("beef")))) .build()); }
public static String hashPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(password.getBytes("UTF-8")); byte[] bytes = md.digest(); return (new HexBinaryAdapter()).marshal(bytes); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } return null; }
public static String generateToken(String username) throws NoSuchAlgorithmException, UnsupportedEncodingException { try { SecureRandom random = new SecureRandom(); String token_data = UUID.randomUUID().toString() + username + System.nanoTime() + new BigInteger(32, random).toString(32); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(token_data.getBytes("UTF-8")); byte[] bytes = md.digest(); return new HexBinaryAdapter().marshal(bytes); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } return null; }
/** * * @param sHexString * @return byte[] */ public static byte[] toByteArray(String sHexString) { //Need to add HexString Check sHexString = sHexString .replaceAll("(\\]|\\)|\\}|\\(|\\[|\\{)", "") .replace(":", ""); HexBinaryAdapter adapter = new HexBinaryAdapter(); if (isModulus(sHexString.replace(" ", ""))) return adapter.unmarshal(sHexString.replace(" ", "")); else return new HexString().toByteArray(); }
public static synchronized String createResultHash(int sequence, byte[] data) { createMd(); md.update(ByteBuffer.allocate(4).putInt(sequence).array()); if (data != null) { md.update(data); } /* store the hash */ return (new HexBinaryAdapter()).marshal(md.digest()); }
@Override public String createChecksum(String fileName, MessageDigest md) throws IOException { byte[] digest = createChecksum(getInputStream(fileName), md); String hex = (new HexBinaryAdapter()).marshal(digest).toLowerCase(); return hex; }
public String getMessageDigestAsHexadecimalString (String algorithm) { return (new HexBinaryAdapter()).marshal ( getMessageDigest (algorithm).digest ()); }
public static String getSHA(String string) throws Exception { MessageDigest sha1 = MessageDigest.getInstance("SHA-512"); sha1.update(string.getBytes()); return new HexBinaryAdapter().marshal(sha1.digest()); }
public static byte[] hexToBytes(String hexString) { HexBinaryAdapter adapter = new HexBinaryAdapter(); byte[] bytes = adapter.unmarshal(hexString); return bytes; }
/** * Writes the data to a CSV file and generates a signature hash. * Then it puts both of this into a ZIP archive file. * * @param csvEntries The {@link ExportEntry} to be exported. * @throws IOException Thrown if the SHA-512 hash algorithm is missing. */ @Override protected void writeToFile(final List<ExportEntry> csvEntries) throws IOException { // Setup compression stuff FileOutputStream fileOutputStream = getFileOutputStream(); final int zipCompressionLevel = 9; ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream); zipOutputStream.setMethod(ZipOutputStream.DEFLATED); zipOutputStream.setLevel(zipCompressionLevel); // Setup signature MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException exception) { LOG.log(Level.SEVERE, "Missing hash algorithm for signature. No file exported!", exception); throw new IOException("Missing hash algorithm for signature."); } DigestOutputStream digestOutputStream = new DigestOutputStream(zipOutputStream, digest); // write data zipOutputStream.putNextEntry(new ZipEntry(DATA_ZIP_ENTRY)); CsvWriter cwriter = new CsvWriter(digestOutputStream, VaultCsvEntry.CSV_DELIMITER, Charset.forName("UTF-8")); cwriter.writeRecord(((CsvEntry) csvEntries.get(0)).getCsvHeaderRecord()); for (ExportEntry item : csvEntries) { cwriter.writeRecord(((CsvEntry) item).toCsvRecord()); } cwriter.flush(); // add signature file zipOutputStream.putNextEntry(new ZipEntry(SIGNATURE_ZIP_ENTRY)); String sigString = (new HexBinaryAdapter()).marshal(digest.digest()); zipOutputStream.write(sigString.getBytes("UTF-8"), 0, sigString.getBytes("UTF-8").length); // Closing the streams cwriter.close(); digestOutputStream.close(); zipOutputStream.close(); fileOutputStream.close(); }
/** * This method takes in a transaction hash and returns a bitcoinj transaction object. */ synchronized org.bitcoinj.core.Transaction getTransaction(String transactionHash) throws IOException { org.bitcoinj.core.Transaction tx = null; String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"method\":\"getrawtransaction\", \"params\":[\"" + transactionHash + "\"]}"; HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); Base64 b = new Base64(); String authString = rpcuser + ":" + rpcpass; String encoding = b.encodeAsString(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length)); connection.setDoInput(true); OutputStream out = connection.getOutputStream(); out.write(requestBody.getBytes()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); JSONObject json = new JSONObject(response.toString()); String hexTx = (String) json.get("result"); HexBinaryAdapter adapter = new HexBinaryAdapter(); byte[] bytearray = adapter.unmarshal(hexTx); Context context = Context.getOrCreate(netParams); tx = new org.bitcoinj.core.Transaction(netParams, bytearray); } out.flush(); out.close(); return tx; }