encrypt Password - Android java.security

Android examples for java.security:Password

Description

encrypt Password

Demo Code


//package com.java2s;
import android.os.SystemClock;
import java.io.UnsupportedEncodingException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import java.util.Random;

public class Main {
    public static String encryptPassword(String s) {
        int i = 10 + (new Random(SystemClock.currentThreadTimeMillis()))
                .nextInt(90);//from  w  w w .  java  2  s .  c om
        return (new StringBuilder())
                .append(md5((new StringBuilder()).append(i).append(s)
                        .toString())).append(":").append(i).toString();
    }

    public static String md5(String s) {
        byte abyte0[];
        StringBuilder stringbuilder;
        int i;
        try {
            abyte0 = MessageDigest.getInstance("MD5").digest(
                    s.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException nosuchalgorithmexception) {
            throw new RuntimeException("Huh, MD5 should be supported?",
                    nosuchalgorithmexception);
        } catch (UnsupportedEncodingException unsupportedencodingexception) {
            throw new RuntimeException("Huh, UTF-8 should be supported?",
                    unsupportedencodingexception);
        }
        stringbuilder = new StringBuilder(2 * abyte0.length);
        i = abyte0.length;
        for (int j = 0; j < i; j++) {
            byte byte0 = abyte0[j];
            if ((byte0 & 0xff) < 16) {
                stringbuilder.append("0");
            }
            stringbuilder.append(Integer.toHexString(byte0 & 0xff));
        }

        return stringbuilder.toString();
    }
}

Related Tutorials