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.opendatakit.sync.aggregate.SimpleJSONMessageReaderWriter.java

@Override
public void writeTo(T o, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> map, OutputStream rawStream)
        throws IOException, WebApplicationException {
    String encoding = getCharsetAsString(mediaType);
    try {/* w  w  w.  java2s. c o  m*/
        if (!encoding.equalsIgnoreCase(DEFAULT_ENCODING)) {
            throw new IllegalArgumentException("charset for the response is not utf-8");
        }
        // write it to a byte array
        ByteArrayOutputStream bas = new ByteArrayOutputStream(8192);
        OutputStreamWriter w = new OutputStreamWriter(bas, Charset.forName(ApiConstants.UTF8_ENCODE));
        mapper.writeValue(w, o);
        // get the array and compute md5 hash
        byte[] bytes = bas.toByteArray();
        String eTag;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);

            byte[] messageDigest = md.digest();

            BigInteger number = new BigInteger(1, messageDigest);
            String md5 = number.toString(16);
            while (md5.length() < 32)
                md5 = "0" + md5;
            eTag = "md5_" + md5;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Unexpected problem computing md5 hash", e);
        }
        map.putSingle(HttpHeaders.ETAG, eTag);

        rawStream.write(bytes);
        rawStream.flush();

    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:net.samuelbjohnson.javadev.crosstopix.Joiner.java

public boolean join(Statement imslpStatement, Statement cpdlStatement, boolean fullOutput)
        throws NoSuchAlgorithmException, RepositoryException {
    BigDecimal distance = computeDistance(imslpStatement.getObject().stringValue(),
            cpdlStatement.getObject().stringValue());

    if (!fullOutput) {
        outputWriter.print(imslpStatement.getObject().stringValue().length() + ",");
        outputWriter.print(cpdlStatement.getObject().stringValue().length() + ",");
        outputWriter.println(distance);//w  w  w.  j  a  va2  s  .co m
        return true;
    }

    MessageDigest md5 = MessageDigest.getInstance("MD5");
    md5.update((imslpStatement.getObject().stringValue() + cpdlStatement.getObject().stringValue()
            + distance.toPlainString()).getBytes());
    BigInteger hashInt = new BigInteger(1, md5.digest());
    String md5Sum = hashInt.toString(16);

    Resource subject = valueFactory.createURI(subjectNamespace, md5Sum);
    URI predicateImslp = valueFactory.createURI(predicateNamespace, "comparable_1");
    URI predicateCpdl = valueFactory.createURI(predicateNamespace, "comparable_2");
    URI predicateDiff = valueFactory.createURI(predicateNamespace, "similarity");

    outputRepCon.add(subject, predicateImslp, imslpStatement.getSubject());
    outputRepCon.add(subject, predicateCpdl, cpdlStatement.getSubject());
    outputRepCon.add(subject, predicateDiff, valueFactory.createLiteral(distance.doubleValue()));

    outputRepCon.commit();

    return true;
}

From source file:com.cisco.ca.cstg.pdi.services.license.LicenseCryptoServiceImpl.java

public void encryptToFile() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException, IOException {
    BufferedWriter out = null;/*from   w  w  w .  j  ava 2 s .  co  m*/
    try {
        byte[] raw = getPassword().getBytes(Charset.forName(Constants.UTF8));
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM_BLOWFISH);
        Cipher cipher = null;
        cipher = Cipher.getInstance(ALGORITHM_BLOWFISH);
        cipher.init(1, skeySpec);
        byte[] output = cipher.doFinal(getMetaData().getBytes());
        BigInteger n = new BigInteger(output);

        String b64hidden = Base64.encodeBase64String(n.toString(16).getBytes());
        setAssessmentKey(b64hidden);

        out = new BufferedWriter(new FileWriter(this.getAssessmentKeyFileName()));
        out.write(b64hidden);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.ichi2.libanki.Utils.java

/**
 * SHA1 checksum./*from   w  ww  .  j  a  va 2 s  .c o 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) {
            Timber.e(e, "Utils.checksum: No such algorithm.");
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            Timber.e(e, "Utils.checksum :: UnsupportedEncodingException");
            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:com.ichi2.libanki.Utils.java

/**
 * Generate the SHA1 checksum of a file.
 * @param file The file to be checked//  w w w  . java2 s.  c om
 * @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) {
        Timber.e(e, "Utils.fileChecksum: File not found.");
    } catch (NoSuchAlgorithmException e) {
        Timber.e(e, "Utils.fileChecksum: No such algorithm.");
    } catch (IOException e) {
        Timber.e(e, "Utils.fileChecksum: IO exception.");
    }
    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:org.wso2.carbon.apimgt.gateway.utils.APIMgtGoogleAnalyticsUtils.java

/**
 * Generate a visitor id for this hit. If there is a visitor id in the
 * messageContext, use that. Otherwise use a random number.
 *
 * @param authHeader Authentication header of the request
 *//*from w  ww. ja  v  a  2  s  .co  m*/
private String getVisitorId(String authHeader) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    String message = authHeader.split(" ")[1];
    if (message == null) {
        message = ANONYMOUS_USER_ID;
    }

    MessageDigest m = MessageDigest.getInstance("MD5");
    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;
    }

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

From source file:org.belio.service.gateway.SafcomGateway.java

private String createSpPass(String spIdString, String now, MessageDigest md) {
    String allpass = spIdString + (spproperties.getProperty(spIdString).split(",")[0]) + now;
    Launcher.LOG.info(spIdString);//from   w w w .jav a2  s .c  o  m
    md.update(allpass.getBytes());
    byte[] digest = md.digest();
    BigInteger bigInt = new BigInteger(1, digest);
    String spPasswordString = bigInt.toString(16);
    while (spPasswordString.length() < 32) {
        spPasswordString = "0" + spPasswordString;
    }
    Launcher.LOG.info(spPasswordString);
    //String recepient = "tel:254724170138";
    return spPasswordString;
}

From source file:org.wso2.carbon.humantask.core.utils.GUID.java

private String mapBytesToChars() {
    BigInteger bigInt = new BigInteger(id);
    return bigInt.toString(34);
}

From source file:ttworkbench.play.parameters.ipv6.editors.octet.OctetRangeVerifier.java

private String topOffValueWithZeros(final Long theValueOctets, final BigInteger theIntegerRepresentation,
        final Long theMinExpectedOctets) {
    return StringUtils.repeat("0", theMinExpectedOctets.intValue() - theValueOctets.intValue())
            + theIntegerRepresentation.toString(16);
}

From source file:CASUAL.communicationstools.heimdall.odin.OdinFile.java

/**
 * runs through a file and builds an MD5 of the actual file. Stops when last
 * block size is not 512 bytes as a Tar will be 512.
 *
 * @return OdinFile's actual MD5//from   w w w  .  j  ava2s.co m
 * @throws IOException {@inheritDoc}
 * @throws FileNotFoundException {@inheritDoc}
 * @throws NoSuchAlgorithmException {@inheritDoc}
 */
private String getActualAndExpectedOdinMd5()
        throws IOException, FileNotFoundException, NoSuchAlgorithmException {
    FileInputStream fis;
    fis = new FileInputStream(odinFile);
    MessageDigest digest = MessageDigest.getInstance("MD5");
    byte[] buffer = new byte[512];
    //read MD5 from file, break on the incomplete block (tar is 512 byte blocks)
    while ((fis.read(buffer)) == 512) {
        if (buffer[511] == 0xff) {
            break;
        }
        digest.update(buffer);
    }
    //last block will be MD5sum in Odin tar.gz format
    for (byte b : buffer) {
        //only read until end of MD5
        if (b == 0xff) {
            break;
        }
        expectedMd5 += (char) b;
    }

    //Create actual MD5sum from messageDigest
    byte[] md5sum = digest.digest();
    BigInteger bigInt = new BigInteger(1, md5sum);
    String localactualMd5 = bigInt.toString(16);
    while (localactualMd5.length() != 32) {
        localactualMd5 = "0" + localactualMd5;
    }

    //split expectedMd5sum from filename and only check sum
    expectedMd5 = expectedMd5.split("  ")[0];
    return localactualMd5;
}