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.livily.pusher.Pusher.java

/**
 * Returns a HMAC/SHA256 representation of the given string
 * // w  ww. j  a  va2  s .  co  m
 * @param data
 * @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:components.security.Password.java

/**
 * Generates a token.
 *
 * @return the generated token.
 */
public String generateToken() {
    return new BigInteger(1024, random).toString(32);
}

From source file:com.offbynull.peernetic.common.identification.IdGenerator.java

/**
 * Generates a {@link Id}./*  ww  w.  j a v  a 2s  . co  m*/
 * @return a {@link Id} between {@code 0} and {@code limit}
 * @throws NullPointerException if any arguments are {@code null}
 */
public Id generate() {
    try {
        int rawLen = limit.length;
        byte[] raw = new byte[rawLen];
        random.nextBytes(raw);

        BigInteger rawBd = new BigInteger(1, raw);
        BigInteger limitBd = new BigInteger(1, limit);

        rawBd = rawBd.mod(limitBd);

        return new Id(rawBd.toByteArray(), limit);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.cloud.server.auth.MD5UserAuthenticator.java

@Override
public String encode(final String password) {
    try {/*from   www .  j  a va2 s  .  c om*/
        final MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.reset();
        BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes()));
        String pwStr = pwInt.toString(16);
        int padding = 32 - pwStr.length();
        StringBuilder sb = new StringBuilder(32);
        for (int i = 0; i < padding; i++) {
            sb.append('0'); // make sure the MD5 password is 32 digits long
        }
        sb.append(pwStr);
        return sb.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new CloudRuntimeException("Unable to hash password", e);
    }

}

From source file:com.github.sebhoss.identifier.service.SuppliedIdentifiers.java

@Override
public String nextUuidInBase62() {
    return Base62.encode(new BigInteger(convertUuidToString(randomUUID()), 16));
}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static String getMD5Sum(String variable) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(variable.getBytes());// ww w  .  j ava2 s  .  c  o  m
    return new BigInteger(1, md.digest()).toString(16);
}

From source file:com.artivisi.iso8583.Message.java

public void setPrimaryBitmapStream(String bitmap) {
    this.primaryBitmap = new BigInteger(bitmap, 16);
}

From source file:org.springframework.cloud.consul.bus.EventService.java

/**
 * from https://github.com/hashicorp/consul/blob/master/api/event.go#L90-L104 //
 * IDToIndex is a bit of a hack. This simulates the index generation to // convert an
 * event ID into a WaitIndex. func (e *Event) IDToIndex(uuid string) uint64 { lower :=
 * uuid[0:8] + uuid[9:13] + uuid[14:18] upper := uuid[19:23] + uuid[24:36] lowVal, err
 * := strconv.ParseUint(lower, 16, 64) if err != nil { panic("Failed to convert " +
 * lower) } highVal, err := strconv.ParseUint(upper, 16, 64) if err != nil {
 * panic("Failed to convert " + upper) } return lowVal ^ highVal //^ bitwise XOR
 * integers }//from   w w  w.java  2  s .  co  m
 */
public BigInteger toIndex(String eventId) {
    String lower = eventId.substring(0, 8) + eventId.substring(9, 13) + eventId.substring(14, 18);
    String upper = eventId.substring(19, 23) + eventId.substring(24, 36);
    BigInteger lowVal = new BigInteger(lower, 16);
    BigInteger highVal = new BigInteger(upper, 16);
    BigInteger index = lowVal.xor(highVal);
    return index;
}

From source file:edu.utdallas.bigsecret.cipher.AesCtr.java

/**
 * Encrypts input data with AES CTR mode.
 * @param data Input byte array.// ww w.j  av  a  2  s .  c om
 * @return Encryption result.
 * @throws Exception Throws exception if there is no data to encrypt.<br>
 *                 May throw exception based on Javax.Crypto.Cipher class
 */
public byte[] encrypt(byte[] data) throws Exception {
    //check if there is data to encrypt
    if (data.length == 0) {
        throw new Exception("No data to encrypt");
    }

    //create iv
    byte[] iv = new byte[BLOCK_SIZE_BYTES];
    byte[] randomNumber = (new BigInteger(BLOCK_SIZE_BITS, m_secureRandom)).toByteArray();
    int a;
    for (a = 0; a < randomNumber.length && a < BLOCK_SIZE_BYTES; a++)
        iv[a] = randomNumber[a];
    for (; a < BLOCK_SIZE_BYTES; a++)
        iv[a] = 0;

    //init cipher instance
    m_cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, m_keySpec, new IvParameterSpec(iv));

    //return concatenation of iv + encrypted data      
    return ArrayUtils.addAll(iv, m_cipher.doFinal(data));
}

From source file:org.smartplatforms.oauth2.SmartClientUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException {

    try {/* w w  w.  ja  va 2 s. c o  m*/
        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(clientId);

        if (client != null) {

            String password = Strings.nullToEmpty(client.getClientSecret());

            if (client.getTokenEndpointAuthMethod() != null
                    && (client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY)
                            || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT))) {

                // Issue a random password each time to prevent password auth from being used (or skipped)
                // for private key or shared key clients, see #715

                password = new BigInteger(512, new SecureRandom()).toString(16);
            }

            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;
            Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(client.getAuthorities());
            authorities.add(ROLE_CLIENT);

            if (adminClients.contains(client.getClientId())) {
                GrantedAuthority roleClient = new SimpleGrantedAuthority("ROLE_ADMIN");
                authorities.add(roleClient);
            }

            return new User(clientId, password, enabled, accountNonExpired, credentialsNonExpired,
                    accountNonLocked, authorities);
        } else {
            throw new UsernameNotFoundException("Client not found: " + clientId);
        }
    } catch (InvalidClientException e) {
        throw new UsernameNotFoundException("Client not found: " + clientId);
    }

}