密码知识系列之基于J2ME的MD5算法类
实现MD5算法的类,提供一个静态的函数toMD5()供调用;还提供一个getMD5ofStr()函数生成一个MD5加密串。
public class MD5
{
static final int S11 = 7;
static final int S12 = 12;
static final int S13 = 17;
static final int S14 = 22;
static final int S21 = 5;
static final int S22 = 9;
static final int S23 = 14;
static final int S24 = 20;
static final int S31 = 4;
static final int S32 = 11;
static final int S33 = 16;
static final int S34 = 23;
static final int S41 = 6;
static final int S42 = 10;
static final int S43 = 15;
static final int S44 = 21;
static final char Hex[]=
{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F};
static final byte PADDING[] = {
-128, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0
};
private long state[];
private long count[];
private byte buffer[];
public String digestHexStr;
private byte digest[];
private byte test;
public String getMD5ofStr(String s)
{//返回MD5串;
int i;
md5Init();
md5Update(s.getBytes(), s.length());
md5Final();
digestHexStr = "";
for(i = 0;i<16;i++)
digestHexStr=digestHexStr+byteHEX(digest[i]);
return digestHexStr;
}
public MD5()
{
state = new long[4];
count = new long[2];
buffer = new byte[64];
digest = new byte[16];
md5Init();
}
private void md5Init()
{//初始化部分变量;
count[0] = 0L;
count[1] = 0L;
state[0] = 0x67452301L;
state[1] = 0xefcdab89L;
state[2] = 0x98badcfeL;
state[3] = 0x10325476L;
}
private long F(long l, long l1, long l2)
{
return l & l1 | ~l & l2;
}
private long G(long l, long l1, long l2)
{
return l & l2 | l1 & ~l2;
}
private long H(long l, long l1, long l2)
{
return l ^ l1 ^ l2;
}
private long I(long l, long l1, long l2)
{
return l1 ^ (l | ~l2);
}
private long FF(long l, long l1, long l2, long l3, long l4, long l5, long l6)
{
l += F(l1, l2, l3) + l4 + l6;
l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);
l += l1;
return l;
}
private long GG(long l, long l1, long l2, long l3, long l4, long l5, long l6)
{
l += G(l1, l2, l3) + l4 + l6;
l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);
l += l1;
return l;
}
private long HH(long l, long l1, long l2, long l3, long l4, long l5, long l6)
{
l += H(l1, l2, l3) + l4 + l6;
l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);
l += l1;
return l;
}
private long II(long l, long l1, long l2, long l3, long l4, long l5, long l6)
{
l += I(l1, l2, l3) + l4 + l6;
l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);
l += l1;
return l;
}
private void md5Update(byte abyte0[], int i)
{//补位操作,abyte0为需要进行MD5加密的字符串,i为字符串长度;
byte abyte1[] = new byte[64];
int k = (int)(count[0] >>> 3) & 0x3f;
if((count[0] += i << 3) < (long)(i << 3))
count[1]++;
count[1] += i >>> 29;
int l = 64 - k;
int j;
if(i >= l)
{
md5Memcpy(buffer, abyte0, k, 0, l);
md5Transform(buffer);
for(j = l; j + 63 < i; j += 64)
{
md5Memcpy(abyte1, abyte0, 0, j, 64);
md5Transform(abyte1);
}
k = 0;
} else
{
j = 0;
}
md5Memcpy(buffer, abyte0, k, j, i - j);
}
private vo
补充:综合编程 , 安全编程 ,