Example usage for java.math BigInteger toString

List of usage examples for java.math BigInteger toString

Introduction

In this page you can find the example usage for java.math BigInteger toString.

Prototype

public String toString(int radix) 

Source Link

Document

Returns the String representation of this BigInteger in the given radix.

Usage

From source file:org.blackbananacoin.incubator.extsupernode.SuperNodeApiTester.java

public void mineBlock(Block b) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    BigInteger target = Difficulty.getTarget(b.getDifficultyTarget());
    log.debug("[Mine] target=0x{}", target.toString(16));
    int count = 0;
    for (Integer nonce : nonceTrySet) {
        b.setNonce(nonce);// w ww .  j  a  v a2  s.  c o m
        b.computeHash();
        BigInteger hashAsInteger = new Hash(b.getHash()).toBigInteger();
        count++;
        if (hashAsInteger.compareTo(target) <= 0) {
            log.debug("[Mine End] count={}, nonce=0x{}", count, Integer.toHexString(nonce));
            log.debug("[Mine End] hashInteger=0x{}", hashAsInteger.toString(16));
            break;
        }
    }
    statsMs.addValue(stopwatch.elapsed(TimeUnit.MILLISECONDS));
    statsCount.addValue(count);
    log.debug("Mine Block with time {} and hash {}", stopwatch, b.getHash());
}

From source file:com.hichinaschool.flashcards.libanki.Utils.java

/**
 * SHA1 checksum.// w  w  w  .  ja v a2s .co m
 * Equivalent to python sha1.hexdigest()
 *
 * @param data the string to generate hash from
 * @return A string of length 40 containing the hexadecimal representation of the MD5 checksum of data.
 */
public static String checksum(String data) {
    String result = "";
    if (data != null) {
        MessageDigest md = null;
        byte[] digest = null;
        try {
            md = MessageDigest.getInstance("SHA1");
            digest = md.digest(data.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage());
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.checksum: " + e.getMessage());
            e.printStackTrace();
        }
        BigInteger biginteger = new BigInteger(1, digest);
        result = biginteger.toString(16);

        // pad with zeros to length of 40 This method used to pad
        // to the length of 32. As it turns out, sha1 has a digest
        // size of 160 bits, leading to a hex digest size of 40,
        // not 32.
        if (result.length() < 40) {
            String zeroes = "0000000000000000000000000000000000000000";
            result = zeroes.substring(0, zeroes.length() - result.length()) + result;
        }
    }
    return result;
}

From source file:info.pancancer.arch3.utils.Utilities.java

public String digest(String plaintext) {
    String result = null;//from  ww  w .  jav  a 2s  .c o m
    MessageDigest m;
    try {
        m = MessageDigest.getInstance("MD5");
        m.reset();
        m.update(plaintext.getBytes(StandardCharsets.UTF_8));
        byte[] digest = m.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        final int radix = 16;
        result = bigInt.toString(radix);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:com.hichinaschool.flashcards.libanki.Utils.java

/**
 * Generate the SHA1 checksum of a file.
 * @param file The file to be checked//from ww  w.j  av  a  2  s .  c o m
 * @return A string of length 32 containing the hexadecimal representation of the SHA1 checksum of the file's contents.
 */
public static String fileChecksum(String file) {
    byte[] buffer = new byte[1024];
    byte[] digest = null;
    try {
        InputStream fis = new FileInputStream(file);
        MessageDigest md = MessageDigest.getInstance("SHA1");
        int numRead = 0;
        do {
            numRead = fis.read(buffer);
            if (numRead > 0) {
                md.update(buffer, 0, numRead);
            }
        } while (numRead != -1);
        fis.close();
        digest = md.digest();
    } catch (FileNotFoundException e) {
        Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: File not found.", e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: No such algorithm.", e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: IO exception.", e);
    }
    BigInteger biginteger = new BigInteger(1, digest);
    String result = biginteger.toString(16);
    // pad with zeros to length of 40 - SHA1 is 160bit long
    if (result.length() < 40) {
        result = "0000000000000000000000000000000000000000".substring(0, 40 - result.length()) + result;
    }
    return result;
}

From source file:com.mobilesorcery.sdk.builder.linux.deb.BuilderUtil.java

/**
 * Calculates the md5 has for a file and returns the
 * hash as a hex string/*  w w  w . j  a  va2  s.  c  om*/
 *
 * @param f File to hash
 * @return 128 bit hash in hex
 *
 * @throws NoSuchAlgorithmException
 * @throws FileNotFoundException
 * @throws IOException
 */
public String calcFileMD5Sum(File f) throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    MessageDigest m = MessageDigest.getInstance("MD5");
    FileInputStream fos = new FileInputStream(f);

    // Hash file
    int size = (int) f.length();
    while (size > 0) {
        int count = fos.read(m_copyBuffer);
        m.update(m_copyBuffer, 0, count);
        size -= count;
    }
    fos.close();

    BigInteger hash = new BigInteger(1, m.digest());
    return hash.toString(16);
}

From source file:org.activiti.rest.api.cycle.ContentGet.java

private void getContent(ActivitiRequest req, WebScriptResponse res) throws IOException {
    CycleContentService contentService = CycleServiceFactory.getContentService();

    // Retrieve the artifactId from the request
    String cnonectorId = req.getMandatoryString("connectorId");
    String artifactId = req.getMandatoryString("artifactId");
    String contentRepresentationId = req.getMandatoryString("contentRepresentationId");

    // Retrieve the artifact from the repository
    RepositoryArtifact artifact = repositoryService.getRepositoryArtifact(cnonectorId, artifactId);

    ContentRepresentation contentRepresentation = contentService.getContentRepresentation(artifact,
            contentRepresentationId);/*from ww  w . j  av a  2 s .  co m*/

    MimeType contentType = contentRepresentation.getRepresentationMimeType();
    // assuming we want to create an attachment for binary data...
    boolean attach = contentType.getName().startsWith("application/") ? true : false;

    // TODO: This code should become obsolete when the connectors store the file
    // names properly with suffix.
    String attachmentFileName = null;
    if (attach) {
        attachmentFileName = artifact.getMetadata().getName();

        if (contentType.equals(CycleApplicationContext.get(XmlMimeType.class))
                && !attachmentFileName.endsWith(".xml")) {
            attachmentFileName += ".xml";
        } else if (contentType.equals(CycleApplicationContext.get(JsonMimeType.class))
                && !attachmentFileName.endsWith(".json")) {
            attachmentFileName += ".json";
        } else if (contentType.equals(CycleApplicationContext.get(TextMimeType.class))
                && !attachmentFileName.endsWith(".txt")) {
            attachmentFileName += ".txt";
        } else if (contentType.equals(CycleApplicationContext.get(PdfMimeType.class))
                && !attachmentFileName.endsWith(".pdf")) {
            attachmentFileName += ".pdf";
        } else if (contentType.equals(CycleApplicationContext.get(MsExcelMimeType.class))
                && !attachmentFileName.endsWith(".xls")) {
            attachmentFileName += ".xls";
        } else if (contentType.equals(CycleApplicationContext.get(MsPowerpointMimeType.class))
                && !attachmentFileName.endsWith(".ppt")) {
            attachmentFileName += ".ppt";
        } else if (contentType.equals(CycleApplicationContext.get(MsWordMimeType.class))
                && !attachmentFileName.endsWith(".doc")) {
            attachmentFileName += ".doc";
        }
    }

    InputStream contentInputStream = null;
    try {
        contentInputStream = contentRepresentation.getContent(artifact).asInputStream();

        // TODO: this is broken for SignavioPNG

        // Calculate an etag for the content using the MD5 algorithm
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(contentRepresentation.getContent(artifact).asByteArray());

        BigInteger number = new BigInteger(1, messageDigest);
        String etag = number.toString(16);
        while (etag.length() < 32) {
            etag = "0" + etag;
        }
        // String etag ="";
        String requestEtag = req.getHttpServletRequest().getHeader("If-None-Match");
        if (requestEtag != null) {
            // For some reason the etag (If-None-Match) parameter is always returned
            // as a quoted string, remove the quotes before comparing it with the
            // newly calculated etag
            requestEtag = requestEtag.replace("\"", "");
        }

        // Check whether the file has been modified since it was last fetched by
        // the client
        if (etag.equals(requestEtag)) {
            throw new WebScriptException(HttpServletResponse.SC_NOT_MODIFIED, "");
        } else {
            streamResponse(res, contentInputStream, new Date(0), etag, attach, attachmentFileName,
                    contentType.getContentType());
        }

    } catch (TransformationException e) {
        // Stream the contents of the exception as HTML, this is a workaround to
        // display exceptions that occur during content transformations
        streamResponse(res, new ByteArrayInputStream(e.getRenderContent().getBytes()), new Date(0), "", false,
                null, CycleApplicationContext.get(HtmlMimeType.class).getContentType());
    } catch (NoSuchAlgorithmException e) {
        // This should never be reached... MessageDigest throws an exception if it
        // is being instantiated with a wrong algorithm, but we know that MD5
        // exists.
    } finally {
        IoUtil.closeSilently(contentInputStream);
    }
}

From source file:com.liato.bankdroid.banking.banks.lansforsakringar.Lansforsakringar.java

private String generateChallenge(int originalChallenge) {
    try {/*from w  ww.ja  v  a 2  s .  com*/
        String h = Integer.toHexString(originalChallenge + (1000 * 20 / 4) + 100 * (18 / 3) + 10 * (2 / 2) + 6);
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] messageDigest = md.digest(h.getBytes());
        BigInteger number = new BigInteger(1, messageDigest);
        String md5 = number.toString(16);
        while (md5.length() < 40)
            md5 = "0" + md5;
        return md5;
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "";

}

From source file:edu.illinois.ncsa.domain.FileDescriptor.java

/**
 * @param md5sum/*from   w  ww.ja va2 s  . c om*/
 *            the md5sum to set
 */
@JsonIgnore
public void setMd5sum(BigInteger md5sum) {
    if (md5sum.signum() < 0) {
        md5sum = new BigInteger(1, md5sum.toByteArray());
    }
    this.md5sum = md5sum.toString(16);
    if (this.md5sum.length() < 16) {
        this.md5sum = "00000000000000000000000000000000".substring(this.md5sum.length()) + this.md5sum;
    }
}

From source file:org.wso2.carbon.appmgt.usage.publisher.APPMgtGoogleAnalayticsHandler.java

private String getClientUUID(MessageContext synCtx, String userAgent, String analyticCookie)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {

    if (analyticCookie != null) {
        if (log.isDebugEnabled()) {
            log.debug("Client UUID Exists: " + analyticCookie);
        }/*from  ww  w.j  av  a 2s . co  m*/
        return analyticCookie;
    }

    String message;
    message = userAgent + getRandomNumber() + UUID.randomUUID().toString();

    MessageDigest m = MessageDigest.getInstance("SHA-512");
    m.update(message.getBytes("UTF-8"), 0, message.length());
    byte[] sum = m.digest();
    BigInteger messageAsNumber = new BigInteger(1, sum);
    String md5String = messageAsNumber.toString(16);

    /* Pad to make sure id is 32 characters long. */
    while (md5String.length() < 32) {
        md5String = "0" + md5String;
    }

    if (log.isDebugEnabled()) {
        log.debug("Client UUID: " + "0x" + md5String.substring(0, 16));
    }

    return "0x" + md5String.substring(0, 16);
}

From source file:co.rsk.asm.EVMDissasembler.java

void printPush(OpCode op) {
    sb.append(' ').append(op.name()).append(' ');
    int nPush = op.val() - OpCode.PUSH1.val() + 1;
    String name = null;/*from  w w  w . j  a va  2s  .  co m*/
    if ((block != null) && (helper != null) && (nPush == 4)) { // optimization, only find int32 label refs
        int labelId = block.getTagIdByPos(pc + 1, tagIterator);
        if (labelId >= 0) {
            name = getVisualLabelName(labelId);
            sb.append(name);
            if (printOffsets)
                sb.append(" ;");
        }
    }

    if ((printOffsets) || (name == null)) {
        byte[] data = Arrays.copyOfRange(code, pc + 1, pc + nPush + 1);
        BigInteger bi = new BigInteger(1, data);
        sb.append("0x").append(bi.toString(16));
        if (bi.bitLength() <= 32) {
            sb.append(" (").append(new BigInteger(1, data).toString()).append(") ");
        }
    }
}