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(byte[] magnitude, int signum) 

Source Link

Document

This private constructor is for internal use and assumes that its arguments are correct.

Usage

From source file:com.github.rnewson.couchdb.lucene.couchdb.View.java

public String getDigest() {
    try {/*from  w  w w .ja v a  2s.c  o  m*/
        final MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(toBytes(json.optString("analyzer")));
        md.update(toBytes(json.optString("defaults")));
        md.update(toBytes(json.optString("index")));
        return new BigInteger(1, md.digest()).toString(Character.MAX_RADIX);
    } catch (final NoSuchAlgorithmException e) {
        throw new Error("MD5 support missing.");
    }
}

From source file:goraci.Print.java

public int run(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("s", "start", true, "start key");
    options.addOption("e", "end", true, "end key");
    options.addOption("l", "limit", true, "number to print");

    GnuParser parser = new GnuParser();
    CommandLine cmd = null;// ww w  . j av  a  2s.co  m
    try {
        cmd = parser.parse(options, args);
        if (cmd.getArgs().length != 0) {
            throw new ParseException("Command takes no arguments");
        }
    } catch (ParseException e) {
        System.err.println("Failed to parse command line " + e.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(getClass().getSimpleName(), options);
        System.exit(-1);
    }

    DataStore<Long, CINode> store = DataStoreFactory.getDataStore(Long.class, CINode.class,
            new Configuration());

    Query<Long, CINode> query = store.newQuery();

    if (cmd.hasOption("s"))
        query.setStartKey(new BigInteger(cmd.getOptionValue("s"), 16).longValue());

    if (cmd.hasOption("e"))
        query.setEndKey(new BigInteger(cmd.getOptionValue("e"), 16).longValue());

    if (cmd.hasOption("l"))
        query.setLimit(Integer.parseInt(cmd.getOptionValue("l")));
    else
        query.setLimit(100);

    Result<Long, CINode> rs = store.execute(query);

    while (rs.next()) {
        CINode node = rs.get();
        System.out.printf("%016x:%016x:%012d:%s\n", rs.getKey(), node.getPrev(), node.getCount(),
                node.getClient());

    }

    store.close();

    return 0;
}

From source file:cz.alej.michalik.totp.server.Users.java

/**
 * Vygenerovat kl? pro generovn TOTP hesla
 * /* w w  w  .j  a v a 2 s.  c  om*/
 * @return base32 etzec
 */
public static String generateSecret() {
    // Chci kl? o velikosti 20 byt
    int maxBits = 20 * 8 - 1;
    SecureRandom rand = new SecureRandom();
    byte[] val = new BigInteger(maxBits, rand).toByteArray();
    return new Base32().encodeToString(val);
}

From source file:io.github.benas.jpopulator.impl.DefaultRandomizer.java

/**
 * Generate a random value for the given type.
 *
 * @param type the type for which a random value will be generated
 * @return a random value for the given type or null if the type is not supported
 *//* w w  w .j a  v  a2 s .  co m*/
public static Object getRandomValue(final Class type) {

    /*
     * String and Character types
     */
    if (type.equals(String.class)) {
        return RandomStringUtils.randomAlphabetic(ConstantsUtil.DEFAULT_STRING_LENGTH);
    }
    if (type.equals(Character.TYPE) || type.equals(Character.class)) {
        return RandomStringUtils.randomAlphabetic(1).charAt(0);
    }

    /*
     * Boolean type
     */
    if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
        return ConstantsUtil.RANDOM.nextBoolean();
    }

    /*
     * Numeric types
     */
    if (type.equals(Byte.TYPE) || type.equals(Byte.class)) {
        return (byte) (ConstantsUtil.RANDOM.nextInt());
    }
    if (type.equals(Short.TYPE) || type.equals(Short.class)) {
        return (short) (ConstantsUtil.RANDOM.nextInt());
    }
    if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
        return ConstantsUtil.RANDOM.nextInt();
    }
    if (type.equals(Long.TYPE) || type.equals(Long.class)) {
        return ConstantsUtil.RANDOM.nextLong();
    }
    if (type.equals(Double.TYPE) || type.equals(Double.class)) {
        return ConstantsUtil.RANDOM.nextDouble();
    }
    if (type.equals(Float.TYPE) || type.equals(Float.class)) {
        return ConstantsUtil.RANDOM.nextFloat();
    }
    if (type.equals(BigInteger.class)) {
        return new BigInteger(
                Math.abs(ConstantsUtil.RANDOM.nextInt(ConstantsUtil.DEFAULT_BIG_INTEGER_NUM_BITS_LENGTH)),
                ConstantsUtil.RANDOM);
    }
    if (type.equals(BigDecimal.class)) {
        return new BigDecimal(ConstantsUtil.RANDOM.nextDouble());
    }
    if (type.equals(AtomicLong.class)) {
        return new AtomicLong(ConstantsUtil.RANDOM.nextLong());
    }
    if (type.equals(AtomicInteger.class)) {
        return new AtomicInteger(ConstantsUtil.RANDOM.nextInt());
    }

    /*
     * Date and time types
     */
    if (type.equals(java.util.Date.class)) {
        return ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue();
    }
    if (type.equals(java.sql.Date.class)) {
        return new java.sql.Date(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(java.sql.Time.class)) {
        return new java.sql.Time(ConstantsUtil.RANDOM.nextLong());
    }
    if (type.equals(java.sql.Timestamp.class)) {
        return new java.sql.Timestamp(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(Calendar.class)) {
        return Calendar.getInstance();
    }
    if (type.equals(org.joda.time.DateTime.class)) {
        return new org.joda.time.DateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.LocalDate.class)) {
        return new org.joda.time.LocalDate(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.LocalTime.class)) {
        return new org.joda.time.LocalTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.LocalDateTime.class)) {
        return new org.joda.time.LocalDateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.Duration.class)) {
        return new org.joda.time.Duration(Math.abs(ConstantsUtil.RANDOM.nextLong()));
    }
    if (type.equals(org.joda.time.Period.class)) {
        return new org.joda.time.Period(Math.abs(ConstantsUtil.RANDOM.nextInt()));
    }
    if (type.equals(org.joda.time.Interval.class)) {
        long startDate = Math.abs(ConstantsUtil.RANDOM.nextInt());
        long endDate = startDate + Math.abs(ConstantsUtil.RANDOM.nextInt());
        return new org.joda.time.Interval(startDate, endDate);
    }

    /*
     * Enum type
     */
    if (type.isEnum() && type.getEnumConstants().length > 0) {
        Object[] enumConstants = type.getEnumConstants();
        return enumConstants[ConstantsUtil.RANDOM.nextInt(enumConstants.length)];
    }

    /*
     * Return null for any unsupported type
     */
    return null;

}

From source file:com.github.woki.payments.adyen.action.CSEUtil.java

public static Cipher rsaCipher(final String cseKeyText) throws NoSuchPaddingException, NoSuchAlgorithmException,
        InvalidKeyException, InvalidKeySpecException, IllegalArgumentException {
    String[] cseKeyParts = cseKeyText.split("\\|");
    if (cseKeyParts.length != 2) {
        throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText);
    }//from  w w w. ja  va 2  s. c  o m
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    BigInteger keyComponent1, keyComponent2;
    try {
        keyComponent1 = new BigInteger(cseKeyParts[1].toLowerCase(Locale.getDefault()), 16);
        keyComponent2 = new BigInteger(cseKeyParts[0].toLowerCase(Locale.getDefault()), 16);
    } catch (NumberFormatException e) {
        throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText);
    }
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(keyComponent1, keyComponent2);
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Cipher result = Cipher.getInstance("RSA/None/PKCS1Padding");
    result.init(Cipher.ENCRYPT_MODE, pubKey);
    return result;
}

From source file:com.bigdata.dastor.dht.CollatingOrderPreservingPartitioner.java

/**
 * Convert a byte array containing the most significant of 'sigbytes' bytes
 * representing a big-endian magnitude into a BigInteger.
 *///from  w  w w  .  j  ava  2s. c o m
private BigInteger bigForBytes(byte[] bytes, int sigbytes) {
    if (bytes.length != sigbytes) {
        // append zeros
        bytes = Arrays.copyOf(bytes, sigbytes);
    }
    return new BigInteger(1, bytes);
}

From source file:Controlador.ControladorUsuario.java

/**
 * Crea un codigo de recuperacion para el usuario, actualiza el usuario en
 * la BD con el codigo creado y la fecha de la creacion.
 *
 * @param u El usuario./*  w w  w .ja v  a2s  .com*/
 * @return El codigo creado.
 */
public String crearCodigoRecuperacion(Usuario u) {
    SecureRandom random = new SecureRandom();
    String codigo = new BigInteger(130, random).toString(32);
    u.setCodigo(codigo);
    Date d = new Date();
    u.setFechaCreacionCodigo(d);
    usuarioDAO.actualizar(u);
    return codigo;
}

From source file:org.homiefund.api.service.impl.InviteServiceImpl.java

@Override
@Transactional//from w  ww.j ava2 s . co  m
public void sendInvite(HomeDTO home, String email) throws IllegalArgumentException {
    Home dao = homeDAO.getById(home.getId());
    if (dao != null) {
        Invitation invitation = new Invitation();
        invitation.setValid(true);
        invitation.setHome(dao);
        invitation.setHash(new BigInteger(130, secureRandom).toString(64));
        invitation.setEmail(email);

        log.info(invitation);
        invitationDAO.create(invitation);

        mailService.sendInvite(mapper.map(invitation, InvitationDTO.class), email);
    } else {
        //todo or throw exception ?
        log.warn("Trying to invite into nonexistent home");
    }
}

From source file:de.taimos.dvalin.interconnect.model.MessageCryptoUtil.java

/**
 *
 * @param msg the message to sign/*from w ww  .j a  va  2 s  . com*/
 * @return the signature hash
 * @throws CryptoException on sign error
 */
public static String sign(final String msg) throws CryptoException {
    try {
        final String toEnc = msg + MessageCryptoUtil.SIGNATURE;
        final MessageDigest mdEnc = MessageDigest.getInstance("MD5");
        mdEnc.update(toEnc.getBytes(Charset.forName("UTF-8")), 0, toEnc.length());
        return new BigInteger(1, mdEnc.digest()).toString(16);
    } catch (final Exception e) {
        throw new CryptoException("Creating signature failed", e);
    }
}

From source file:br.vn.Controlador.ControladorClienteBean.java

public void setConfirma(String confirma) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");

    BigInteger hash = new BigInteger(1, md.digest(confirma.getBytes()));
    this.confirma = String.format("%32x", hash);

}