Example usage for java.math BigInteger BigInteger

List of usage examples for java.math BigInteger BigInteger

Introduction

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

Prototype

private BigInteger(long val) 

Source Link

Document

Constructs a BigInteger with the specified value, which may not be zero.

Usage

From source file:cn.ctyun.amazonaws.util.StringUtils.java

public static BigInteger toBigInteger(String s) {
    return new BigInteger(s);
}

From source file:com.cloud.utils.crypt.RSAHelper.java

private static RSAPublicKey readKey(String key) throws Exception {
    byte[] encKey = Base64.decodeBase64(key.split(" ")[1]);
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(encKey));

    byte[] header = readElement(dis);
    String pubKeyFormat = new String(header);
    if (!pubKeyFormat.equals("ssh-rsa"))
        throw new RuntimeException("Unsupported format");

    byte[] publicExponent = readElement(dis);
    byte[] modulus = readElement(dis);

    KeySpec spec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
    RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(spec);

    return pubKey;
}

From source file:com.examples.with.different.packagename.ClassNumberUtilsTest.java

@Test
public void testCreateBigInteger() {
    assertEquals("createBigInteger(String) failed", new BigInteger("12345"),
            ClassNumberUtils.createBigInteger("12345"));
    assertEquals("createBigInteger(null) failed", null, ClassNumberUtils.createBigInteger(null));

    assertEquals("createBigInteger(String) failed", new BigInteger("255"),
            ClassNumberUtils.createBigInteger("0xff"));
    assertEquals("createBigInteger(String) failed", new BigInteger("255"),
            ClassNumberUtils.createBigInteger("0Xff"));
    assertEquals("createBigInteger(String) failed", new BigInteger("255"),
            ClassNumberUtils.createBigInteger("#ff"));
    assertEquals("createBigInteger(String) failed", new BigInteger("-255"),
            ClassNumberUtils.createBigInteger("-0xff"));
    assertEquals("createBigInteger(String) failed", new BigInteger("255"),
            ClassNumberUtils.createBigInteger("0377"));
    assertEquals("createBigInteger(String) failed", new BigInteger("-255"),
            ClassNumberUtils.createBigInteger("-0377"));
    assertEquals("createBigInteger(String) failed", new BigInteger("-255"),
            ClassNumberUtils.createBigInteger("-0377"));
    assertEquals("createBigInteger(String) failed", new BigInteger("-0"),
            ClassNumberUtils.createBigInteger("-0"));
    assertEquals("createBigInteger(String) failed", new BigInteger("0"),
            ClassNumberUtils.createBigInteger("0"));
}

From source file:Main.java

/**
 * convert value to given type.//ww  w . ja v a 2 s .c o m
 * null safe.
 *
 * @param value value for convert
 * @param type  will converted type
 * @return value while converted
 */
public static Object convertCompatibleType(Object value, Class<?> type) {

    if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof String) {
        String string = (String) value;
        if (char.class.equals(type) || Character.class.equals(type)) {
            if (string.length() != 1) {
                throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!"
                        + " when convert String to char, the String MUST only 1 char.", string));
            }
            return string.charAt(0);
        } else if (type.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, string);
        } else if (type == BigInteger.class) {
            return new BigInteger(string);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(string);
        } else if (type == Short.class || type == short.class) {
            return Short.valueOf(string);
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(string);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(string);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(string);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(string);
        } else if (type == Byte.class || type == byte.class) {
            return Byte.valueOf(string);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(string);
        } else if (type == Date.class) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse((String) value);
            } catch (ParseException e) {
                throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT
                        + ", cause: " + e.getMessage(), e);
            }
        } else if (type == Class.class) {
            return forName((String) value);
        }
    } else if (value instanceof Number) {
        Number number = (Number) value;
        if (type == byte.class || type == Byte.class) {
            return number.byteValue();
        } else if (type == short.class || type == Short.class) {
            return number.shortValue();
        } else if (type == int.class || type == Integer.class) {
            return number.intValue();
        } else if (type == long.class || type == Long.class) {
            return number.longValue();
        } else if (type == float.class || type == Float.class) {
            return number.floatValue();
        } else if (type == double.class || type == Double.class) {
            return number.doubleValue();
        } else if (type == BigInteger.class) {
            return BigInteger.valueOf(number.longValue());
        } else if (type == BigDecimal.class) {
            return BigDecimal.valueOf(number.doubleValue());
        } else if (type == Date.class) {
            return new Date(number.longValue());
        }
    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (type.isArray()) {
            int length = collection.size();
            Object array = Array.newInstance(type.getComponentType(), length);
            int i = 0;
            for (Object item : collection) {
                Array.set(array, i++, item);
            }
            return array;
        } else if (!type.isInterface()) {
            try {
                Collection result = (Collection) type.newInstance();
                result.addAll(collection);
                return result;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (type == List.class) {
            return new ArrayList<>(collection);
        } else if (type == Set.class) {
            return new HashSet<>(collection);
        }
    } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
        Collection collection;
        if (!type.isInterface()) {
            try {
                collection = (Collection) type.newInstance();
            } catch (Throwable e) {
                collection = new ArrayList<>();
            }
        } else if (type == Set.class) {
            collection = new HashSet<>();
        } else {
            collection = new ArrayList<>();
        }
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++) {
            collection.add(Array.get(value, i));
        }
        return collection;
    }
    return value;
}

From source file:net.ftb.util.CryptoUtils.java

/**
 * Newer implementation available if possible use {@link #encrypt(String str, byte[] key)}
 * @param str string to decrypt//from  ww  w  .  j  a  v a 2  s.  co m
 * @param key decryption key
 * @return decrypted string or "" if fails
 */
@Deprecated
public static String encryptLegacy(String str, byte[] key) {
    BigInteger str2;
    try {
        str2 = new BigInteger(str.getBytes("utf8")).xor(new BigInteger(1, key));
    } catch (UnsupportedEncodingException e) {
        return "";
    }
    return String.format("%040x", str2);
}

From source file:RSA.java

/** Encrypt the given plaintext message. */
public synchronized String encrypt(String message) {
    return (new BigInteger(message.getBytes())).modPow(e, n).toString();
}

From source file:com.boldust.math001.Math001Test.java

/**
 * Test of pow001 method, of class Math001.
 *///w w w .j a  va2s  .  com
@Test
public void testPow001() {
    System.out.println("pow001");
    Logger l = Logger.getLogger("powtest001");
    //        l.addHandler(new java.util.logging.ConsoleHandler());
    l.log(Level.SEVERE, "Powtest001");
    int base = 20;
    int exp = 5;
    BigInteger expResult = new BigInteger(Integer.valueOf(3200000).toString());
    BigInteger result1 = new BigInteger(Integer.valueOf(3200000).toString());
    BigInteger result = Math001.pow001(base, exp);
    System.out.println(expResult.equals(result));
    assertEquals(expResult, result);
    assertEquals(result1, result);
    // TODO review the generated test code and remove the default call to fail.
    //fail("The test case is a prototype.");
}

From source file:net.oauth.jsontoken.crypto.MagicRsaPublicKey.java

private static PublicKey parseKey(String magicKey) {
    String[] pieces = magicKey.split(Pattern.quote("."));
    if (pieces.length != 3) {
        throw new IllegalStateException("not a valid magic key: " + magicKey);
    }/*w w w . java  2s.c o m*/

    if (!pieces[0].equals("RSA")) {
        throw new IllegalStateException("unkown key type for magic key: " + pieces[0]);
    }

    String modulusString = pieces[1];
    String exponentString = pieces[2];

    byte[] modulusBytes = Base64.decodeBase64(modulusString);
    byte[] exponentBytes = Base64.decodeBase64(exponentString);

    BigInteger modulus = new BigInteger(modulusBytes);
    BigInteger exponent = new BigInteger(exponentBytes);

    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
    KeyFactory fac;
    try {
        fac = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA key factory missing on platform", e);
    }
    try {
        return fac.generatePublic(spec);
    } catch (InvalidKeySpecException e) {
        throw new IllegalStateException("bad key in descripor doc: " + magicKey, e);
    }
}

From source file:Main.java

static BigInteger reverseNumber(BigInteger num) {
    String digits = num.toString();
    int numDigits = digits.length();
    char[] sb = new char[numDigits];
    for (int i = 0; i < digits.length(); i++) {
        sb[i] = digits.charAt(numDigits - i - 1);
    }/*from ww  w .ja  v a 2 s  .  c om*/
    // Debug.println("rev",
    //    "reverseNumber(" + digits + ") -> " + "\"" + sb + "\"");
    return new BigInteger(new String(sb));
}

From source file:com.ok2c.lightmtp.util.InetAddressRange.java

public InetAddressRange(final InetAddress address, final int mask) {
    super();/*from  ww  w  . j  a  v  a 2  s .  c  om*/
    Args.notNull(address, "Address");
    if (mask < 0) {
        throw new IllegalArgumentException("Address mask may not be negative");
    }
    this.address = address;
    this.mask = mask;

    byte[] addr = address.getAddress();
    BigInteger bigint = new BigInteger(addr);
    int shiftBy = 0;
    if (mask > 0) {
        if (addr.length == 4) {
            shiftBy = 32 - mask;
        } else if (addr.length == 16) {
            shiftBy = 128 - mask;
        } else {
            throw new IllegalArgumentException("Unsupported address: " + address);
        }
    }
    if (shiftBy > 0) {
        bigint = bigint.shiftRight(shiftBy);
    }
    this.bigint = bigint;
    this.shiftBy = shiftBy;
}