Example usage for java.math BigInteger toString

List of usage examples for java.math BigInteger toString

Introduction

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

Prototype

public String toString(int radix) 

Source Link

Document

Returns the String representation of this BigInteger in the given radix.

Usage

From source file:graphene.util.crypto.PasswordHash.java

/**
 * Converts a byte array into a hexadecimal string.
 * //  w  ww  .  j  a v  a 2s  . c om
 * @param array
 *            the byte array to convert
 * @return a length*2 character string encoding the byte array
 */
protected String toHex(final byte[] array) {
    final BigInteger bi = new BigInteger(1, array);
    final String hex = bi.toString(16);
    final int paddingLength = (array.length * 2) - hex.length();
    if (paddingLength > 0) {
        return String.format("%0" + paddingLength + "d", 0) + hex;
    } else {
        return hex;
    }
}

From source file:no.kantega.useradmin.controls.ResetPasswordController.java

public ModelAndView doHandleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    RequestParameters param = new RequestParameters(request);

    String domain = param.getString("domain");
    String id = param.getString("userId");

    DefaultIdentity ident = new DefaultIdentity();
    ident.setUserId(id);/*  w  ww .ja  v a 2  s . c  om*/
    ident.setDomain(domain);

    Profile user = getProfileConfiguration(domain).getProfileManager().getProfileForUser(ident);

    String password1 = param.getString("password1");
    String password2 = param.getString("password2");

    Map<String, Object> model = new HashMap<>();
    model.put("domain", domain);

    Configuration aksessConf = Aksess.getConfiguration();

    String mailtemplate = aksessConf.getString("security.passwordmail.template");

    if (mailtemplate != null && getProfileConfiguration(domain).getPasswordManager() != null) {

        if (isBlank(user.getEmail())) {
            model.put("noemail", Boolean.TRUE);
        } else {

            model.put("maildefault", aksessConf.getBoolean("security.passwordmail.default", false));

            Velocity.init();

            File confDir = new File(Configuration.getApplicationDirectory());
            File mailDir = new File(confDir, "mail");

            File temp = new File(mailDir, mailtemplate);

            VelocityContext context = new VelocityContext();

            context.put("editor", aksessConf.getString("mail.editor"));
            StringBuilder name = new StringBuilder();
            name.append(user.getGivenName());
            if (user.getSurname() != null && !user.getSurname().trim().equals("")) {
                name.append(" ").append(user.getSurname());
            }
            context.put("userId", id);
            context.put("name", name.toString());

            StringWriter sw = new StringWriter();
            Velocity.evaluate(context, sw, mailtemplate, new InputStreamReader(new FileInputStream(temp),
                    aksessConf.getString("velocity.templateencoding", "iso-8859-1")));

            model.put("mailtemplate", sw.toString());

            model.put("mailto", user.getEmail());
            {
                String from = aksessConf.getString("security.passwordmail.from");
                from = from == null ? aksessConf.getString("mail.editor") : from;
                model.put("mailfrom", from);
            }
            {
                String subject = aksessConf.getString("security.passwordmail.subject");
                subject = subject == null ? "Nytt passord" : subject;
                model.put("mailsubject", subject);
            }
        }

    }

    if (password1 != null) {

        // We're sending email
        if (request.getParameter("mailsubmit") != null) {

            String from = param.getString("from");
            String subject = param.getString("subject");
            String message = param.getString("message");

            VelocityContext context = new VelocityContext();

            BigInteger number = new BigInteger(40, random);

            String generatedPassword = number.toString(Character.MAX_RADIX);

            context.put("password", generatedPassword);

            StringWriter sw = new StringWriter();
            Velocity.evaluate(context, sw, "message", new StringReader(message));

            MailSender.send(from, user.getEmail(), subject, sw.toString());

            ProfileManagementConfiguration config = getProfileConfiguration(domain);
            PasswordManager passwordManager = config.getPasswordManager();
            if (passwordManager != null) {
                passwordManager.setPassword(ident, generatedPassword, generatedPassword);
                model.put("userId", id);
                model.put("message", "useradmin.password.saved");
                return new ModelAndView(new RedirectView("../profile/search"), model);
            }

        } else {
            // Just set the password
            ValidationErrors errors = passwordValidator.isValidPassword(password1, password2, ident);
            if (errors.getLength() > 0) {
                model.put("errors", errors);
            } else {
                ProfileManagementConfiguration config = getProfileConfiguration(domain);
                PasswordManager passwordManager = config.getPasswordManager();
                if (passwordManager != null) {
                    passwordManager.setPassword(ident, password1, password2);
                    model.put("userId", id);
                    model.put("message", "useradmin.password.saved");
                    return new ModelAndView(new RedirectView("../profile/search"), model);
                }
            }
        }
    }
    model.put("userId", id);

    return new ModelAndView("password/reset", model);
}

From source file:withings.apiaccess.WithingsAPI.java

private String md5Hash(String string) throws Exception {
    MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
    digest.update(string.getBytes());//from  w ww .jav  a 2s.co  m
    byte messageDigest[] = digest.digest();

    // Get the Hex String
    BigInteger bigInt = new BigInteger(1, messageDigest);
    return bigInt.toString(16);
}

From source file:org.jmangos.realm.network.packet.auth.client.CMD_AUTH_LOGON_CHALLENGE.java

@Override
protected void readImpl() throws BufferUnderflowException, RuntimeException {

    readC();/* w ww  .  j av a  2s  . c om*/
    if (readC() == WoWAuthResponse.WOW_SUCCESS.getMessageId()) {
        final SecureRandom random = new SecureRandom();
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
            return;
        }
        final BigInteger k = new BigInteger("3");
        final byte[] Bb = readB(32);
        final BigInteger g = new BigInteger(readB(readC()));
        final byte[] Nb = readB(readC());
        final byte[] saltb = readB(32);
        /* byte[] unk3 = */readB(16);
        readC();
        ArrayUtils.reverse(Bb);
        final BigInteger B = new BigInteger(1, Bb);
        ArrayUtils.reverse(Bb);
        ArrayUtils.reverse(Nb);
        final BigInteger N = new BigInteger(1, Nb);
        ArrayUtils.reverse(Nb);
        final BigInteger a = new BigInteger(1, random.generateSeed(19));

        final byte[] passhash = sha.digest(this.config.AUTH_LOGIN.toUpperCase().concat(":")
                .concat(this.config.AUTH_PASSWORD.toUpperCase()).getBytes(Charset.forName("UTF-8")));
        sha.update(saltb);
        sha.update(passhash);

        final byte[] xhash = sha.digest();
        ArrayUtils.reverse(xhash);
        final BigInteger x = new BigInteger(1, xhash);
        logger.debug("x:" + x.toString(16).toUpperCase());
        final BigInteger v = g.modPow(x, N);
        logger.debug("v:" + v.toString(16).toUpperCase());
        final BigInteger A = g.modPow(a, N);
        logger.debug("A:" + A.toString(16).toUpperCase());
        logger.debug("B:" + B.toString(16).toUpperCase());
        this.ahash = A.toByteArray();
        ArrayUtils.reverse(this.ahash);
        sha.update(this.ahash);
        sha.update(Bb);
        final byte[] hashu = sha.digest();
        ArrayUtils.reverse(hashu);
        final BigInteger u = new BigInteger(1, hashu);
        logger.debug("u:" + u.toString(16).toUpperCase());
        final BigInteger S = (B.subtract(k.multiply(g.modPow(x, N)))).modPow(a.add(u.multiply(x)), N);

        final byte[] full_S = S.toByteArray();
        ArrayUtils.reverse(full_S);
        logger.debug("t:" + StringUtils.toHexString(full_S));
        final byte[] s1_hash = new byte[16];
        final byte[] s2_hash = new byte[16];
        for (int i = 0; i < 16; i++) {
            s1_hash[i] = full_S[i * 2];
            s2_hash[i] = full_S[(i * 2) + 1];
        }
        final byte[] t1 = sha.digest(s1_hash);
        final byte[] t2 = sha.digest(s2_hash);
        final byte[] vK = new byte[40];
        for (int i = 0; i < 20; i++) {
            vK[i * 2] = t1[i];
            vK[(i * 2) + 1] = t2[i];
        }

        byte[] hash = new byte[20];
        logger.debug("N:" + N.toString(16).toUpperCase());
        hash = sha.digest(Nb);

        logger.debug("hash:" + new BigInteger(1, hash).toString(16).toUpperCase());

        byte[] gH = new byte[20];
        sha.update(g.toByteArray());
        gH = sha.digest();
        for (int i = 0; i < 20; ++i) {
            hash[i] ^= gH[i];
        }

        byte[] t4 = new byte[20];
        t4 = sha.digest(this.config.AUTH_LOGIN.toUpperCase().getBytes(Charset.forName("UTF-8")));

        sha.update(hash);
        logger.debug("hash:" + StringUtils.toHexString(hash));
        sha.update(t4);
        logger.debug("t4:" + StringUtils.toHexString(t4));
        sha.update(saltb);
        logger.debug("saltb:" + StringUtils.toHexString(saltb));
        sha.update(this.ahash);
        logger.debug("ahash:" + StringUtils.toHexString(this.ahash));
        sha.update(Bb);
        logger.debug("Bb:" + StringUtils.toHexString(Bb));
        sha.update(vK);
        logger.debug("vK:" + StringUtils.toHexString(vK));
        this.m1 = sha.digest();

        sha.update(this.ahash);
        sha.update(this.m1);
        sha.update(vK);
        logger.debug("m1 value" + StringUtils.toHexString(this.m1));
        @SuppressWarnings("unused")
        final byte[] m2 = sha.digest();

        final ChannelPipeline pipeline = getClient().getChannel().getPipeline();
        ((RealmToAuthChannelHandler) pipeline.getLast()).setSeed(vK);

    } else {
        getChannel().getPipeline().remove("handler");
        getChannel().getPipeline().remove("eventlog");
        getChannel().getPipeline().remove("executor");
        getChannel().close();
        getChannel().getFactory().releaseExternalResources();
    }
}

From source file:com.sshtools.j2ssh.transport.publickey.dsa.SshDssPrivateKey.java

/**
 *
 *
 * @param data//from w w w. ja va  2s  .c  om
 *
 * @return
 *
 * @throws InvalidSshKeySignatureException
 */
public byte[] generateSignature(byte[] data) throws InvalidSshKeySignatureException {
    try {

        Signature sig = Signature.getInstance("SHA1withDSA");
        sig.initSign(prvkey);

        /*java.util.Random rnd = new java.util.Random();
           byte[] buffer = new byte[20];
           rnd.nextBytes(buffer);
           sig.update(buffer);
           byte[] test = sig.sign();*/
        sig.update(data);

        byte[] signature = sig.sign();
        byte[] decoded = new byte[40];

        SimpleASNReader asn = new SimpleASNReader(signature);
        asn.getByte();
        asn.getLength();
        asn.getByte();

        byte[] r = asn.getData();

        asn.getByte();

        byte[] s = asn.getData();

        if (r.length >= 20) {
            System.arraycopy(r, r.length - 20, decoded, 0, 20);
        } else {
            System.arraycopy(r, 0, decoded, 20 - r.length, r.length);
        }

        if (s.length >= 20) {
            System.arraycopy(s, s.length - 20, decoded, 20, 20);
        } else {
            System.arraycopy(s, 0, decoded, 20 + (20 - s.length), s.length);
        }

        if (log.isDebugEnabled()) {

            BigInteger rb = new BigInteger(1, r);
            log.debug(rb.toString(16));

            BigInteger sb = new BigInteger(1, s);
            log.debug(sb.toString(16));

            log.debug("s length is " + String.valueOf(s.length));
            log.debug("r length is " + String.valueOf(r.length));

            String str = "";

            for (int i = 0; i < signature.length; i++) {
                str += (Integer.toHexString(signature[i] & 0xFF) + " ");
            }

            log.debug("Java signature is " + str);

            str = "";

            for (int i = 0; i < decoded.length; i++) {
                str += (Integer.toHexString(decoded[i] & 0xFF) + " ");
            }

            log.debug("SSH signature is " + str);
        }

        ByteArrayWriter baw = new ByteArrayWriter();
        baw.writeString(getAlgorithmName());
        baw.writeBinaryString(decoded);

        return baw.toByteArray();
    } catch (Exception e) {
        throw new InvalidSshKeySignatureException(e);
    }
}

From source file:com.dii.ids.application.utils.io.SimpleDiskCache.java

private String md5(String s) {
    try {//from  w ww  . ja  va  2  s  . co  m
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(s.getBytes("UTF-8"));
        byte[] digest = m.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        return bigInt.toString(16);
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        throw new AssertionError();
    }
}

From source file:com.example.filipzoricic.online_shop.SimpleDiskCache.java

private String md5(String s) {
    try {/*from   w w w  .jav a 2 s. c  o m*/
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(s.getBytes("UTF-8"));
        byte[] digest = m.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        return bigInt.toString(16);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError();
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError();
    }
}

From source file:fr.paris.lutece.portal.web.style.PageTemplatesJspBeanTest.java

private String getRandomName() {
    Random rand = new SecureRandom();
    BigInteger bigInt = new BigInteger(128, rand);
    return "junit" + bigInt.toString(36);
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

private void createNewKeyStore() {
    BigInteger id = new BigInteger(64, new Random(System.currentTimeMillis()));
    File ksFile = new File(keyStoreDir, id.toString(16));
    createKeyStore(ksFile);/*from  w  w w. j a  v a  2s  .  co  m*/
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestStorageRestore.java

/**
 * This function returns a md5 hash of a file.
 *
 * @param file input file//from ww w. j  a v  a 2s. co m
 * @return The md5 string
 */
public String getFileMD5(File file) throws Exception {
    String res = new String();
    MessageDigest mD = MessageDigest.getInstance("MD5");
    DataInputStream dis = new DataInputStream(new FileInputStream(file));

    try {
        while (true) {
            mD.update(dis.readByte());
        }
    } catch (EOFException eof) {
    }

    BigInteger bigInt = new BigInteger(1, mD.digest());
    res = bigInt.toString(16);
    dis.close();

    return res;
}