package com.datacomo.pcm.ejb.systemcore.util;
import java.security.MessageDigest;
import java.util.Random;
public class Md5Encrtypt {
/**
* MD5加密算法
*
* @param s
* 加密数字
* @return 加密后的值
*/
public final static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] strTemp = s.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
/**
* 去除字母
*
* @param number
* 加密后的值
* @return 去除字母后的值
*/
public static String getNumber(String number) {
StringBuffer mun = new StringBuffer();
char[] cha = number.toCharArray();
for (int i = 0; i < number.length(); i++) {
if (Character.isDigit(cha[i])) {
mun.append(cha[i]);
}
}
return mun.toString();
}
/**
* 生成随机数
*
* @param count
* @return
*/
public static String random(int count) {
String mun = "";
Random random = new Random();
for (int i = 0; i < count; i++) {
mun += random.nextInt(10);
}
return mun;
}
/**
* 获得加密后的POS卡号码
*
* @param posNum
* pos卡号码
* @return 加密后的POS卡号码
*/
public static String getMd5Encrtypt(String posNum) {
StringBuffer PosNumber = new StringBuffer();
PosNumber.append(posNum);
String md5PosNum = Md5Encrtypt.MD5(posNum);
String md5Num = Md5Encrtypt.getNumber(md5PosNum);
if (md5Num.length() > 18) {
md5Num = md5Num.substring(0, 18);
PosNumber.append(md5Num);
} else if (md5Num.length() < 18) {
int num = 18 - md5Num.length();
String randomNum = Md5Encrtypt.random(num);
PosNumber.append(md5Num);
PosNumber.append(randomNum);
} else if (md5Num.length() == 18) {
PosNumber.append(md5Num);
}
return PosNumber.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
Md5Encrtypt md5Encrtypt = new Md5Encrtypt();
String posNum = md5Encrtypt.getMd5Encrtypt("12345678901223");
System.out.println("加密后的卡号为:" + posNum);
}
}