Example usage for java.math BigInteger mod

List of usage examples for java.math BigInteger mod

Introduction

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

Prototype

public BigInteger mod(BigInteger m) 

Source Link

Document

Returns a BigInteger whose value is (this mod m ).

Usage

From source file:org.trnltk.numeral.DigitsToTextConverter.java

private String convertNaturalNumberToWords(BigInteger naturalNumber) {
    Validate.isTrue(naturalNumber.compareTo(ZERO) >= 0);
    Validate.isTrue(naturalNumber.compareTo(MAX_NATURAL_NUMBER_SUPPORTED) <= 0, "Given number " + naturalNumber
            + " is larger than maximum supported natural number " + MAX_NATURAL_NUMBER_SUPPORTED);

    StringBuilder result = new StringBuilder();

    if (naturalNumber.compareTo(BigInteger.TEN) < 0) {
        result.append(NUMERAL_SYMBOL_NAMES.get(naturalNumber.intValue()));

    } else if (naturalNumber.compareTo(ONE_HUNDRED) < 0) {
        final BigInteger tensDigit = naturalNumber.divide(TEN);
        final BigInteger onesDigit = naturalNumber.mod(TEN);
        final String strTensDigit = TENS_MULTIPLES_NAMES.get(tensDigit.intValue());
        final String strOnesDigit = onesDigit.compareTo(ZERO) > 0 ? convertNaturalNumberToWords(onesDigit)
                : StringUtils.EMPTY;//from   www . j a v a 2  s  .c o  m
        result.append(strTensDigit).append(" ").append(strOnesDigit);

    } else if (naturalNumber.compareTo(ONE_THOUSAND) < 0) {
        final BigInteger hundredsDigit = naturalNumber.divide(ONE_HUNDRED);
        final BigInteger rest = naturalNumber.mod(ONE_HUNDRED);
        final String strHundredsDigit;
        if (hundredsDigit.equals(ZERO)) {
            strHundredsDigit = StringUtils.EMPTY;
        } else if (hundredsDigit.equals(ONE)) {
            strHundredsDigit = StringUtils.EMPTY;
        } else {
            strHundredsDigit = convertNaturalNumberToWords(hundredsDigit);
        }

        final String restStr = rest.compareTo(ZERO) > 0 ? convertNaturalNumberToWords(rest) : StringUtils.EMPTY;

        result.append(strHundredsDigit).append(" ").append(HUNDRED_NAME).append(" ").append(restStr);

    } else {
        int mostSignificantGroupBase = this.findMostSignificantGroupBase(naturalNumber);
        for (int i = mostSignificantGroupBase / 3; i > 0; i--) {
            int groupNumber = this.getNthGroupNumber(naturalNumber, i);
            //noinspection StatementWithEmptyBody
            if (groupNumber == 0) {
                // don't write 'sifir milyon'
            } else if (groupNumber == 1 && i == 1) {
                // don't write 'bir bin', but write 'bir milyon'(below)
                result.append(" ").append(THOUSAND_NAME);
            } else {
                final String strGroupNumber = this.convertNaturalNumberToWords(BigInteger.valueOf(groupNumber));
                result.append(" ").append(strGroupNumber).append(" ").append(THOUSAND_POWER_NAMES.get(i));
            }

            result = new StringBuilder(result.toString().trim());
        }

        final BigInteger lastGroupNumber = naturalNumber.mod(ONE_THOUSAND);
        if (lastGroupNumber.compareTo(ZERO) > 0)
            result.append(" ").append(convertNaturalNumberToWords(lastGroupNumber));
    }

    return result.toString().trim();
}

From source file:ch.bfh.evoting.alljoyn.BusHandler.java

/**
 * Get the public key of the given peer//w ww  .j  ava 2s . c  om
 * @param peerId the peer unique identifier
 * @return the SHA-256 mod 2^64 of the ASN-1 representation of the public key of the given peer
 */
public String getPeerPublicKey(String peerId) {

    if (!identityMap.containsKey(peerId)) {
        return null;
    } else {
        byte[] encodedKey = identityMap.get(peerId).getPublicKey().getEncoded();
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(encodedKey);
            BigInteger hashBI = new BigInteger(hash);
            return bytesToHex(hashBI.mod(BigInteger.valueOf(2).pow(64)).toByteArray());
        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();
            return "";
        }

    }
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Creates request for device SRP verification.
 *
 * @param challenge REQUIRED: {@link RespondToAuthChallengeResult} contains
 *            next challenge.//w w w  .  j ava2s  . c o  m
 * @param deviceSecret REQUIRED: Device secret verifier.
 * @param authenticationHelper REQUIRED: Internal helper class for SRP
 *            calculations.
 * @param deviceGroupKey the device group key
 * @return {@link RespondToAuthChallengeRequest}.
 */
public RespondToAuthChallengeRequest deviceSrpAuthRequest(RespondToAuthChallengeResult challenge,
        String deviceSecret, String deviceGroupKey, AuthenticationHelper authenticationHelper) {
    this.usernameInternal = challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_USERNAME);

    final BigInteger srpB = new BigInteger(challenge.getChallengeParameters().get("SRP_B"), 16);
    if (srpB.mod(AuthenticationHelper.N).equals(BigInteger.ZERO)) {
        throw new CognitoInternalErrorException("SRP error, B cannot be zero");
    }

    final BigInteger salt = new BigInteger(challenge.getChallengeParameters().get("SALT"), 16);
    final byte[] key = authenticationHelper.getPasswordAuthenticationKey(deviceKey, deviceSecret, srpB, salt);

    final Date timestamp = new Date();
    byte[] hmac;
    String dateString;
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        final SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256");
        mac.init(keySpec);
        mac.update(deviceGroupKey.getBytes(StringUtils.UTF8));
        mac.update(deviceKey.getBytes(StringUtils.UTF8));
        final byte[] secretBlock = Base64.decode(
                challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK));
        mac.update(secretBlock);

        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        dateString = simpleDateFormat.format(timestamp);
        final byte[] dateBytes = dateString.getBytes(StringUtils.UTF8);

        hmac = mac.doFinal(dateBytes);
    } catch (final Exception e) {
        throw new CognitoInternalErrorException("SRP error", e);
    }

    secretHash = CognitoSecretHash.getSecretHash(usernameInternal, clientId, clientSecret);

    final Map<String, String> srpAuthResponses = new HashMap<String, String>();
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SECRET_BLOCK,
            challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SIGNATURE,
            new String(Base64.encode(hmac), StringUtils.UTF8));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_TIMESTAMP, dateString);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_USERNAME, usernameInternal);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_DEVICE_KEY, deviceKey);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_SECRET_HASH, secretHash);

    final RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest();
    authChallengeRequest.setChallengeName(challenge.getChallengeName());
    authChallengeRequest.setClientId(clientId);
    authChallengeRequest.setSession(challenge.getSession());
    authChallengeRequest.setChallengeResponses(srpAuthResponses);

    return authChallengeRequest;
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Creates response for the second step of the SRP authentication.
 *
 * @param challenge REQUIRED: {@link InitiateAuthResult} contains next
 *            challenge./*w  ww.j a  v a2s.  c  om*/
 * @param authenticationDetails REQUIRED: {@link AuthenticationDetails} user
 *            authentication details.
 * @param authenticationHelper REQUIRED: Internal helper class for SRP
 *            calculations.
 * @return {@link RespondToAuthChallengeRequest}.
 */
private RespondToAuthChallengeRequest userSrpAuthRequest(InitiateAuthResult challenge,
        AuthenticationDetails authenticationDetails, AuthenticationHelper authenticationHelper) {
    final String userIdForSRP = challenge.getChallengeParameters()
            .get(CognitoServiceConstants.CHLG_PARAM_USER_ID_FOR_SRP);
    this.usernameInternal = challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_USERNAME);
    this.deviceKey = CognitoDeviceHelper.getDeviceKey(usernameInternal, pool.getUserPoolId(), context);
    secretHash = CognitoSecretHash.getSecretHash(usernameInternal, clientId, clientSecret);

    final BigInteger srpB = new BigInteger(challenge.getChallengeParameters().get("SRP_B"), 16);
    if (srpB.mod(AuthenticationHelper.N).equals(BigInteger.ZERO)) {
        throw new CognitoInternalErrorException("SRP error, B cannot be zero");
    }

    final BigInteger salt = new BigInteger(challenge.getChallengeParameters().get("SALT"), 16);
    final byte[] key = authenticationHelper.getPasswordAuthenticationKey(userIdForSRP,
            authenticationDetails.getPassword(), srpB, salt);

    final Date timestamp = new Date();
    byte[] hmac;
    String dateString;
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        final SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256");
        mac.init(keySpec);
        mac.update(pool.getUserPoolId().split("_", 2)[1].getBytes(StringUtils.UTF8));
        mac.update(userIdForSRP.getBytes(StringUtils.UTF8));
        final byte[] secretBlock = Base64.decode(challenge.getChallengeParameters().get("SECRET_BLOCK"));
        mac.update(secretBlock);

        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        dateString = simpleDateFormat.format(timestamp);
        final byte[] dateBytes = dateString.getBytes(StringUtils.UTF8);

        hmac = mac.doFinal(dateBytes);
    } catch (final Exception e) {
        throw new CognitoInternalErrorException("SRP error", e);
    }

    final Map<String, String> srpAuthResponses = new HashMap<String, String>();
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SECRET_BLOCK,
            challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SIGNATURE,
            new String(Base64.encode(hmac), StringUtils.UTF8));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_TIMESTAMP, dateString);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_USERNAME, usernameInternal);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_DEVICE_KEY, deviceKey);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_SECRET_HASH, secretHash);

    final RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest();
    authChallengeRequest.setChallengeName(challenge.getChallengeName());
    authChallengeRequest.setClientId(clientId);
    authChallengeRequest.setSession(challenge.getSession());
    authChallengeRequest.setChallengeResponses(srpAuthResponses);

    return authChallengeRequest;
}