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:co.rsk.validators.BlockTxsValidationRule.java

@Override
public boolean isValid(Block block, Block parent) {
    if (block == null || parent == null) {
        return false;
    }/* w  ww  .jav a 2 s . co m*/

    List<Transaction> txs = block.getTransactionsList();
    if (CollectionUtils.isEmpty(txs))
        return true;

    Repository parentRepo = repository.getSnapshotTo(parent.getStateRoot());

    Map<ByteArrayWrapper, BigInteger> curNonce = new HashMap<>();

    for (Transaction tx : txs) {
        byte[] txSender = tx.getSender();
        ByteArrayWrapper key = new ByteArrayWrapper(txSender);
        BigInteger expectedNonce = curNonce.get(key);
        if (expectedNonce == null) {
            expectedNonce = parentRepo.getNonce(txSender);
        }
        curNonce.put(key, expectedNonce.add(ONE));
        BigInteger txNonce = new BigInteger(1, tx.getNonce());

        if (!expectedNonce.equals(txNonce)) {
            logger.error("Invalid transaction: Tx nonce {} != expected nonce {} (parent nonce: {}): {}",
                    txNonce, expectedNonce, parentRepo.getNonce(txSender), tx);

            panicProcessor.panic("invalidtransaction",
                    String.format(
                            "Invalid transaction: Tx nonce %s != expected nonce %s (parent nonce: %s): %s",
                            txNonce.toString(), expectedNonce.toString(),
                            parentRepo.getNonce(txSender).toString(), Hex.toHexString(tx.getHash())));

            return false;
        }
    }

    return true;
}

From source file:jsave.Utils.java

private static BigInteger read_uint64(final RandomAccessFile raf) throws IOException {
    byte[] data = new byte[8];
    raf.read(data);/*w  w w . jav a2s.  c om*/
    return new BigInteger(1, data);
}

From source file:net.sf.keystore_explorer.crypto.digest.DigestUtil.java

/**
 * Get the digest of a message as a formatted String. Returned in base-16
 * with ':' separators every two characters padded with a leading 0 if
 * necessary to make for an even number of hex characters.
 *
 * @param message/*w  ww .  j a  v  a2s . c  o m*/
 *            The message to digest
 * @param digestType
 *            The message digest algorithm
 * @return The message digest
 * @throws CryptoException
 *             If message digester could not be created
 */
public static String getFriendlyMessageDigest(byte[] message, DigestType digestType) throws CryptoException {
    byte[] messageDigest = getMessageDigest(message, digestType);

    StringBuffer strBuff = new StringBuffer(new BigInteger(1, messageDigest).toString(16).toUpperCase());

    if ((strBuff.length() % 2) == 1) {
        strBuff.insert(0, '0');
    }

    if (strBuff.length() > 2) {
        for (int i = 2; i < strBuff.length(); i += 3) {
            strBuff.insert(i, ':');
        }
    }

    return strBuff.toString();
}

From source file:ac.elements.parser.SimpleDBConverter.java

/**
 * Decodes zero-padded positive long value from the string representation
 * /*w w  w . j a  va  2s . c om*/
 * com.xerox.amazonws.sdb.DataUtils
 * 
 * @param value
 *            zero-padded string representation of the long
 * @return original long value
 */
private static long decodeLong(String value) {
    BigInteger bi = new BigInteger(value, RADIX);
    bi = bi.add(BigInteger.valueOf(Long.MIN_VALUE));
    return bi.longValue();
}

From source file:com.jaspersoft.jasperserver.jaxrs.client.core.EncryptionUtils.java

private static PublicKey getPublicKey(String n, String e) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    int radix = 16;
    BigInteger modulus = new BigInteger(n, radix);
    BigInteger publicExponent = new BigInteger(e, radix);
    RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    return keyFactory.generatePublic(publicKeySpec);
}

From source file:Pusher.java

/**
 * Returns a HMAC/SHA256 representation of the given string
 * @param data/* w  w w. ja  v a  2s  . c o m*/
 * @return
 */
private static String hmacsha256Representation(String data) {
    try {
        // Create the HMAC/SHA256 key from application secret
        final SecretKeySpec signingKey = new SecretKeySpec(pusherApplicationSecret.getBytes(), "HmacSHA256");

        // Create the message authentication code (MAC)
        final Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);

        //Process and return data
        byte[] digest = mac.doFinal(data.getBytes("UTF-8"));
        digest = mac.doFinal(data.getBytes());
        //Convert to string
        BigInteger bigInteger = new BigInteger(1, digest);
        return String.format("%0" + (digest.length << 1) + "x", bigInteger);
    } catch (NoSuchAlgorithmException nsae) {
        //We should never come here, because GAE has HMac SHA256
        throw new RuntimeException("No HMac SHA256 algorithm");
    } catch (UnsupportedEncodingException e) {
        //We should never come here, because UTF-8 should be available
        throw new RuntimeException("No UTF-8");
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Invalid key exception while converting to HMac SHA256");
    }
}

From source file:database.DBAccountManager.java

private static String hashPassword(String password) {
    String digest;/*from w w w .  ja  va 2  s .  co m*/
    try {
        MessageDigest md = MessageDigest.getInstance("md5");
        md.reset();
        byte[] bytes = md.digest(password.getBytes());
        digest = new BigInteger(1, bytes).toString(16);
    } catch (NoSuchAlgorithmException nsae) {
        nsae.printStackTrace();
        digest = null;
    }
    return digest;
}

From source file:mitm.common.util.MiscArrayUtils.java

/**
 * Converts the input string which is encoded in MAX_RADIX to a byte array (this function 
 * is the complement of ArrayUtils#toMaxRadix) 
 *//*from   w w  w.  j a v  a2 s. c o m*/
public static byte[] fromMaxRadix(String inputMaxRadix) {
    Check.notNull(inputMaxRadix, "inputMaxRadix");

    BigInteger bigInt = new BigInteger(inputMaxRadix, Character.MAX_RADIX);

    byte[] bytes = bigInt.toByteArray();

    /*
     * We need to remove the first byte added by toMaxRadix.
     */
    return ArrayUtils.subarray(bytes, 1, bytes.length);
}

From source file:com.orchestra.portale.externalauth.FbAuthenticationManager.java

public static User fbLoginJs(HttpServletRequest request, HttpServletResponse response,
        UserRepository userRepository) {

    //Get access_token from request
    String access_token = request.getParameter("access_token");
    User user = null;// w  w  w.  j  a  v  a  2s  . co m

    if (StringUtils.isNotEmpty(access_token)) {

        try {

            Boolean validity = FacebookUtils.ifTokenValid(access_token);

            //if token is valid, retrieve userid and email from Facebook
            if (validity) {
                Map<String, String> userId_mail = FacebookUtils.getUserIDMail(access_token);
                String id = userId_mail.get("id");
                String email = userId_mail.get("email");

                try {
                    user = fbUserCheck(id, email, userRepository);
                } catch (UserNotFoundException ioex) {
                    /*Retrieve User Data to Registration*/
                    Map<String, String> userData = FacebookUtils.getUserData(access_token);

                    /*Create User*/
                    com.orchestra.portale.persistence.sql.entities.User new_user = new com.orchestra.portale.persistence.sql.entities.User();
                    new_user.setFbEmail(userData.get("email"));
                    new_user.setFbUser(userData.get("id"));
                    new_user.setUsername(userData.get("email"));
                    new_user.setFirstName(userData.get("firstName"));
                    new_user.setLastName(userData.get("lastName"));
                    new_user.setPassword(new BigInteger(130, new SecureRandom()).toString(32));

                    /*Create Role*/
                    com.orchestra.portale.persistence.sql.entities.Role new_user_role = new com.orchestra.portale.persistence.sql.entities.Role();
                    new_user_role.setRole("ROLE_USER");
                    new_user_role.setUser(new_user);
                    ArrayList<com.orchestra.portale.persistence.sql.entities.Role> new_user_roles = new ArrayList<com.orchestra.portale.persistence.sql.entities.Role>();
                    new_user_roles.add(new_user_role);
                    new_user.setRoles(new_user_roles);

                    /*Save User*/
                    userRepository.save(new_user);

                    //Save user image
                    try {
                        String img_url = userData.get("img");
                        String user_id_img = userRepository.findByUsername(new_user.getUsername()).getId()
                                .toString();

                        HttpSession session = request.getSession();
                        ServletContext sc = session.getServletContext();

                        String destination = sc.getRealPath("/") + "dist" + File.separator + "user"
                                + File.separator + "img" + File.separator + user_id_img + File.separator;

                        NetworkUtils.saveImageFromURL(img_url, destination, "avatar.jpg");

                    } catch (MalformedURLException ex) {
                        throw new FacebookException();
                    } catch (IOException ioexc) {
                        ioexc.getMessage();
                    }

                    /*Create Spring User*/
                    boolean enabled = true;
                    boolean accountNonExpired = true;
                    boolean credentialsNonExpired = true;
                    boolean accountNonLocked = true;

                    user = new User(new_user.getUsername(), new_user.getPassword().toLowerCase(), enabled,
                            accountNonExpired, credentialsNonExpired, accountNonLocked,
                            getAuthorities(new_user.getRoles()));

                }

            }

        } catch (FacebookException ioex) {
            ioex.printStackTrace();
        }

    }

    return user;
}

From source file:io.kodokojo.service.redis.AbstractRedisStore.java

protected String generateId() {
    try (Jedis jedis = pool.getResource()) {

        SecureRandom secureRandom = new SecureRandom();
        String rand = new BigInteger(128, secureRandom).toString(10);
        String id = saltKey + rand + jedis.incr(getGenerateIdKey()).toString();
        String newId = RedisUtils.hexEncode(messageDigest.digest(id.getBytes()));
        return newId;
    }//from  w  ww .j av a  2s.  co  m
}