Java Code Examples for java.math.BigInteger#toString()

The following examples show how to use java.math.BigInteger#toString() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: burp-api-drops   File: AES_256.java    License: Apache License 2.0 6 votes vote down vote up
/**
	 * same as php do.
	 * 
	 * @param input
	 * @return
	 */
	public static String MD5(String input) {
		String result = input;
		if (input != null) {
			MessageDigest md = null;
			try {
				md = MessageDigest.getInstance("MD5");
				md.update(input.getBytes());
				BigInteger hash = new BigInteger(1, md.digest());
				result = hash.toString(16);
				while (result.length() < 32) {
					result = "0" + result;
				}
			}
			catch (NoSuchAlgorithmException e) {
//				logger.info("Exception:" + e);
			}
		}
		return result;
	}
 
Example 2
Source Project: cloudstack   File: UtilsForTest.java    License: Apache License 2.0 6 votes vote down vote up
public static String createMD5String(String password) {
    MessageDigest md5;
    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new CloudRuntimeException("Error", e);
    }

    md5.reset();
    BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes()));

    // make sure our MD5 hash value is 32 digits long...
    StringBuffer sb = new StringBuffer();
    String pwStr = pwInt.toString(16);
    int padding = 32 - pwStr.length();
    for (int i = 0; i < padding; i++) {
        sb.append('0');
    }
    sb.append(pwStr);
    return sb.toString();
}
 
Example 3
Source Project: xipki   File: CertActions.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Object execute0() throws Exception {
  CrlReason crlReason = CrlReason.forNameOrText(reason);

  if (!CrlReason.PERMITTED_CLIENT_CRLREASONS.contains(crlReason)) {
    throw new InvalidConfException("reason " + reason + " is not permitted");
  }

  Date invalidityDate = null;
  if (isNotBlank(invalidityDateS)) {
    invalidityDate = DateUtil.parseUtcTimeyyyyMMddhhmmss(invalidityDateS);
  }

  BigInteger serialNo = getSerialNumber();
  String msg = "certificate (serial number = 0x" + serialNo.toString(16) + ")";
  try {
    caManager.revokeCertificate(caName, serialNo, crlReason, invalidityDate);
    println("revoked " + msg);
    return null;
  } catch (CaMgmtException ex) {
    throw new CmdFailure("could not revoke " + msg + ", error: " + ex.getMessage(), ex);
  }
}
 
Example 4
/**
 * return a hexadecimal printed representation of the specified
 * BigInteger object. the value is formatted to fit on lines of
 * at least 75 characters, with embedded newlines. Words are
 * separated for readability, with eight words (32 bytes) per line.
 */
public static String toHexString(BigInteger b) {
    String hexValue = b.toString(16);
    StringBuffer buf = new StringBuffer(hexValue.length()*2);

    if (hexValue.startsWith("-")) {
        buf.append("   -");
        hexValue = hexValue.substring(1);
    } else {
        buf.append("    ");     // four spaces
    }
    if ((hexValue.length()%2) != 0) {
        // add back the leading 0
        hexValue = "0" + hexValue;
    }
    int i=0;
    while (i < hexValue.length()) {
        // one byte at a time
        buf.append(hexValue.substring(i, i+2));
        i+=2;
        if (i!= hexValue.length()) {
            if ((i%64) == 0) {
                buf.append("\n    ");     // line after eight words
            } else if (i%8 == 0) {
                buf.append(" ");     // space between words
            }
        }
    }
    return buf.toString();
}
 
Example 5
Source Project: AVM   File: ShadowEnergyLimitTarget.java    License: MIT License 5 votes vote down vote up
@Callable
public static void callBigIntegerToString(int count) throws IllegalArgumentException{
    byte[] arr1 = new byte[32];
    Arrays.fill(arr1, 0, 32, Byte.MAX_VALUE);
    BigInteger testValue = new BigInteger(arr1);
    for (int i = 0; i < count; i++){
        testValue.toString();
    }
}
 
Example 6
Source Project: weblaf   File: FileUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns MD5 for the data provided by {@link InputStream} and uses a buffer of the specified length.
 *
 * @param inputStream  data stream to process
 * @param bufferLength buffer length
 * @return MD5 for the data provided by {@link InputStream}
 */
@NotNull
public static String computeMD5 ( @NotNull final InputStream inputStream, final int bufferLength )
{
    final BufferedInputStream bis = new BufferedInputStream ( inputStream );
    try
    {
        final MessageDigest digest = MessageDigest.getInstance ( "MD5" );
        final byte[] buffer = new byte[ bufferLength ];
        int bytesRead;
        while ( ( bytesRead = bis.read ( buffer, 0, buffer.length ) ) > 0 )
        {
            digest.update ( buffer, 0, bytesRead );
        }
        final byte[] md5sum = digest.digest ();
        final BigInteger bigInt = new BigInteger ( 1, md5sum );
        return bigInt.toString ( 16 );
    }
    catch ( final Exception e )
    {
        throw new UtilityException ( "Unable to compute MD5 for InputStream: " + inputStream, e );
    }
    finally
    {
        try
        {
            bis.close ();
        }
        catch ( final Exception ignored )
        {
            //
        }
    }
}
 
Example 7
public void assertMatchingToString(N value, BigInteger asSigned, BigInteger asUnsigned, String description) {
    String expected = signed
        ? asSigned.toString(radix)
        : asUnsigned.toString(radix);

    String actual = toString.apply(value);

    assertEquals(actual, expected, description + " conversion should be the same");
}
 
Example 8
Source Project: j2objc   File: Debug.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * return a hexadecimal printed representation of the specified
 * BigInteger object. the value is formatted to fit on lines of
 * at least 75 characters, with embedded newlines. Words are
 * separated for readability, with eight words (32 bytes) per line.
 */
public static String toHexString(BigInteger b) {
    String hexValue = b.toString(16);
    StringBuffer buf = new StringBuffer(hexValue.length()*2);

    if (hexValue.startsWith("-")) {
        buf.append("   -");
        hexValue = hexValue.substring(1);
    } else {
        buf.append("    ");     // four spaces
    }
    if ((hexValue.length()%2) != 0) {
        // add back the leading 0
        hexValue = "0" + hexValue;
    }
    int i=0;
    while (i < hexValue.length()) {
        // one byte at a time
        buf.append(hexValue.substring(i, i+2));
        i+=2;
        if (i!= hexValue.length()) {
            if ((i%64) == 0) {
                buf.append("\n    ");     // line after eight words
            } else if (i%8 == 0) {
                buf.append(" ");     // space between words
            }
        }
    }
    return buf.toString();
}
 
Example 9
/**
 * return a hexadecimal printed representation of the specified
 * BigInteger object. the value is formatted to fit on lines of
 * at least 75 characters, with embedded newlines. Words are
 * separated for readability, with eight words (32 bytes) per line.
 */
public static String toHexString(BigInteger b) {
    String hexValue = b.toString(16);
    StringBuffer buf = new StringBuffer(hexValue.length()*2);

    if (hexValue.startsWith("-")) {
        buf.append("   -");
        hexValue = hexValue.substring(1);
    } else {
        buf.append("    ");     // four spaces
    }
    if ((hexValue.length()%2) != 0) {
        // add back the leading 0
        hexValue = "0" + hexValue;
    }
    int i=0;
    while (i < hexValue.length()) {
        // one byte at a time
        buf.append(hexValue.substring(i, i+2));
        i+=2;
        if (i!= hexValue.length()) {
            if ((i%64) == 0) {
                buf.append("\n    ");     // line after eight words
            } else if (i%8 == 0) {
                buf.append(" ");     // space between words
            }
        }
    }
    return buf.toString();
}
 
Example 10
Source Project: jdk8u60   File: Debug.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * return a hexadecimal printed representation of the specified
 * BigInteger object. the value is formatted to fit on lines of
 * at least 75 characters, with embedded newlines. Words are
 * separated for readability, with eight words (32 bytes) per line.
 */
public static String toHexString(BigInteger b) {
    String hexValue = b.toString(16);
    StringBuffer buf = new StringBuffer(hexValue.length()*2);

    if (hexValue.startsWith("-")) {
        buf.append("   -");
        hexValue = hexValue.substring(1);
    } else {
        buf.append("    ");     // four spaces
    }
    if ((hexValue.length()%2) != 0) {
        // add back the leading 0
        hexValue = "0" + hexValue;
    }
    int i=0;
    while (i < hexValue.length()) {
        // one byte at a time
        buf.append(hexValue.substring(i, i+2));
        i+=2;
        if (i!= hexValue.length()) {
            if ((i%64) == 0) {
                buf.append("\n    ");     // line after eight words
            } else if (i%8 == 0) {
                buf.append(" ");     // space between words
            }
        }
    }
    return buf.toString();
}
 
Example 11
/**
 * 根据网络地址生成文件名, 因为有很多网络地址的名称比较怪异. 建议在设计过程中, 接口中考虑文件名. 此方法只是粗暴的解决方法.
 * FIXME: 可优化
 * 
 * @param url
 * @return
 */
public static String generateNameByNetUrl(String url)
{
	byte[] md5 = getMD5(url.getBytes());
	BigInteger bi = new BigInteger(md5).abs();

	return bi.toString(RADIX);
}
 
Example 12
Source Project: binnavi   File: ZyOperandBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static String getUnsignedBigIntegerString(final BigInteger value,
    final COperandTreeNode node, final int radix) {
  // We only need to take care of values which are less than zero.
  if (value.signum() != -1) {
    return value.toString(radix);
  }

  INaviOperandTreeNode currentNode = node.getParent();
  while (currentNode.getType() != ExpressionType.SIZE_PREFIX) {
    if (currentNode.getParent() == null) {
      throw new IllegalStateException("Error: could not determine size of operand.");
    }
    currentNode = currentNode.getParent();
  }

  final BigInteger twosComplement = value.abs().not().add(BigInteger.ONE);
  // TODO(timkornau): The code here uses strings as the current implementation of the operand
  // nodes stores all value information in a string field. To change this the size and value
  // information of an operand node need to be stored in different fields. b/11566525
  switch (currentNode.getValue()) {
    case "byte":
      return twosComplement.and(new BigInteger("FF", 16)).toString(radix);
    case "word":
      return twosComplement.and(new BigInteger("FFFF", 16)).toString(radix);
    case "dword":
      return twosComplement.and(new BigInteger("FFFFFFFF", 16)).toString(radix);
    case "fword":
      return twosComplement.and(new BigInteger("FFFFFFFFFFFF", 16)).toString(radix);
    case "qword":
      return twosComplement.and(new BigInteger("FFFFFFFFFFFFFFFF", 16)).toString(radix);
    case "oword":
      return twosComplement.and(new BigInteger("FFFFFFFFFFFFFFFFFFFF", 16)).toString(radix);
    default:
      throw new IllegalStateException("Error: size of operand tree node is not supported.");
  }
}
 
Example 13
@Override
public String toString(BigInteger value) {
	return value.toString(16);
}
 
Example 14
Source Project: reacteu-app   File: DecodedBitStreamParser.java    License: MIT License 4 votes vote down vote up
/**
 * Convert a list of Numeric Compacted codewords from Base 900 to Base 10.
 *
 * @param codewords The array of codewords
 * @param count     The number of codewords
 * @return The decoded string representing the Numeric data.
 */
/*
   EXAMPLE
   Encode the fifteen digit numeric string 000213298174000
   Prefix the numeric string with a 1 and set the initial value of
   t = 1 000 213 298 174 000
   Calculate codeword 0
   d0 = 1 000 213 298 174 000 mod 900 = 200

   t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082
   Calculate codeword 1
   d1 = 1 111 348 109 082 mod 900 = 282

   t = 1 111 348 109 082 div 900 = 1 234 831 232
   Calculate codeword 2
   d2 = 1 234 831 232 mod 900 = 632

   t = 1 234 831 232 div 900 = 1 372 034
   Calculate codeword 3
   d3 = 1 372 034 mod 900 = 434

   t = 1 372 034 div 900 = 1 524
   Calculate codeword 4
   d4 = 1 524 mod 900 = 624

   t = 1 524 div 900 = 1
   Calculate codeword 5
   d5 = 1 mod 900 = 1
   t = 1 div 900 = 0
   Codeword sequence is: 1, 624, 434, 632, 282, 200

   Decode the above codewords involves
     1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 +
   632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000

   Remove leading 1 =>  Result is 000213298174000
 */
private static String decodeBase900toBase10(int[] codewords, int count) throws FormatException {
  BigInteger result = BigInteger.ZERO;
  for (int i = 0; i < count; i++) {
    result = result.add(EXP900[count - i - 1].multiply(BigInteger.valueOf(codewords[i])));
  }
  String resultString = result.toString();
  if (resultString.charAt(0) != '1') {
    throw FormatException.getFormatInstance();
  }
  return resultString.substring(1);
}
 
Example 15
Source Project: cloudstack   File: NetworkModelImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public List<String[]> generateVmData(String userData, String serviceOffering, long datacenterId,
                                     String vmName, String vmHostName, long vmId, String vmUuid,
                                     String guestIpAddress, String publicKey, String password, Boolean isWindows) {

    DataCenterVO dcVo = _dcDao.findById(datacenterId);
    final String zoneName = dcVo.getName();

    IPAddressVO publicIp = _ipAddressDao.findByAssociatedVmId(vmId);

    final List<String[]> vmData = new ArrayList<String[]>();

    if (userData != null) {
        vmData.add(new String[]{USERDATA_DIR, USERDATA_FILE, userData});
    }
    vmData.add(new String[]{METATDATA_DIR, SERVICE_OFFERING_FILE, StringUtils.unicodeEscape(serviceOffering)});
    vmData.add(new String[]{METATDATA_DIR, AVAILABILITY_ZONE_FILE, StringUtils.unicodeEscape(zoneName)});
    vmData.add(new String[]{METATDATA_DIR, LOCAL_HOSTNAME_FILE, StringUtils.unicodeEscape(vmHostName)});
    vmData.add(new String[]{METATDATA_DIR, LOCAL_IPV4_FILE, guestIpAddress});

    String publicIpAddress = guestIpAddress;
    String publicHostName = StringUtils.unicodeEscape(vmHostName);

    if (dcVo.getNetworkType() != DataCenter.NetworkType.Basic) {
        if (publicIp != null) {
            publicIpAddress = publicIp.getAddress().addr();
            publicHostName = publicIp.getAddress().addr();
        } else {
            publicHostName = null;
        }
    }
    vmData.add(new String[]{METATDATA_DIR, PUBLIC_IPV4_FILE, publicIpAddress});
    vmData.add(new String[]{METATDATA_DIR, PUBLIC_HOSTNAME_FILE, publicHostName});

    if (vmUuid == null) {
        vmData.add(new String[]{METATDATA_DIR, INSTANCE_ID_FILE, vmName});
        vmData.add(new String[]{METATDATA_DIR, VM_ID_FILE, String.valueOf(vmId)});
    } else {
        vmData.add(new String[]{METATDATA_DIR, INSTANCE_ID_FILE, vmUuid});
        vmData.add(new String[]{METATDATA_DIR, VM_ID_FILE, vmUuid});
    }

    vmData.add(new String[]{METATDATA_DIR, PUBLIC_KEYS_FILE, publicKey});

    String cloudIdentifier = _configDao.getValue("cloud.identifier");
    if (cloudIdentifier == null) {
        cloudIdentifier = "";
    } else {
        cloudIdentifier = "CloudStack-{" + cloudIdentifier + "}";
    }
    vmData.add(new String[]{METATDATA_DIR, CLOUD_IDENTIFIER_FILE, cloudIdentifier});

    if (password != null && !password.isEmpty() && !password.equals("saved_password")) {

        // Here we are calculating MD5 checksum to reduce the over head of calculating MD5 checksum
        // in windows VM in password reset script.

        if (isWindows) {
            MessageDigest md5 = null;
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                s_logger.error("Unexpected exception " + e.getMessage(), e);
                throw new CloudRuntimeException("Unable to get MD5 MessageDigest", e);
            }
            md5.reset();
            md5.update(password.getBytes(StringUtils.getPreferredCharset()));
            byte[] digest = md5.digest();
            BigInteger bigInt = new BigInteger(1, digest);
            String hashtext = bigInt.toString(16);

            vmData.add(new String[]{PASSWORD_DIR, PASSWORD_CHECKSUM_FILE, hashtext});
        }

        vmData.add(new String[]{PASSWORD_DIR, PASSWORD_FILE, password});
    }

    return vmData;
}
 
Example 16
public static String _printInteger(BigInteger val) {
    return val.toString();
}
 
Example 17
@Override
public String generate(String imageUri) {
	byte[] md5 = getMD5(imageUri.getBytes());
	BigInteger bi = new BigInteger(md5).abs();
	return bi.toString(RADIX);
}
 
Example 18
private String getRandomName( )
{
    Random rand = new SecureRandom( );
    BigInteger bigInt = new BigInteger( 128, rand );
    return "junit" + bigInt.toString( 36 );
}
 
Example 19
Source Project: symbolicautomata   File: BDD.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * <p>Given a domain index and an element index, return the element's name.
 * Called by the toStringWithDomains() function.</p>
 * 
 * @param i the domain number
 * @param j the element number
 * @return the string representation of that element
 */
public String elementName(int i, BigInteger j) {
    return j.toString();
}
 
Example 20
/**
 * converts a byte array to a binary String
 *
 * @param value the byte array to be converted
 * @return the binary string representation of the byte array
 */
public static String toBinaryString(byte[] value) {
    BigInteger helpBigInteger = new BigInteger(1, value);

    return helpBigInteger.toString(2);
}