« MyEclipse4.0 | Main | 柳传志施振荣联手进军内容产业 捧互动杂志 »

随机数加密/解密

根据vb版本转过来的。

public static String encode(String s)
{
if(s == null)
return null;
byte buff[] = s.getBytes();
int i = 0;
String mstr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
i = buff.length;
String outs = " ";
for(int l = 0; l < i - 1; l++)
outs = outs + " ";

int buf = 0;
for(int l = 0; l < i; l++)
{
double r = Math.random();
double d = 5D * r;
int a = (int)d;
int j = (new Integer(a)).byteValue();
if(buff[l] < 0)
buf = buff[l] + 256;
else
buf = buff[l];
buf ^= j;
int k = buf % mstr.length();
int m = buf / mstr.length();
m = m * 8 + j;
String temps = mstr.substring(k, k + 1) + mstr.substring(m, m + 1);
outs = outs.substring(0, 2 * l) + temps + outs.substring(2 * l + 2);
}

return outs;
}
/**
* @param s
* @return
* @author hoofi
* 2005-9-23 9:23:53
*/
public static String decode(String s){
int j,k,m=0;
String mstr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
String t1,t2;

byte[] buff=new byte[s.length()/2];
int n=0;

for (int i = 0; i < s.length(); i++,i++) {

t1 = s.substring(i,i+1);
t2 = s.substring(i+1,i+2);
k = mstr.indexOf(t1) ;
m = mstr.indexOf(t2) ;

j = m / 8;
m = m - j * 8;

int num =j * mstr.length() + k;
num=num ^ m;

buff[n]=(new Integer(num)).byteValue();
n = n + 1;
}
String decode = new String(buff);
return decode;
}


RelatedEntries:
开源开发管理工具 - 10 19, 2005
MyEclipse4.0 - 9 06, 2005
javamail from - 4 04, 2005
PowerDesign一则技巧 - 11 09, 2004

Comments

VB版本
Private Function encode(ByVal s As String) As String '加密
If Len(s) = 0 Then Exit Function
Dim buff() As Byte
buff = StrConv(s, vbFromUnicode)
Dim i As Long
Dim j As Byte
Dim k As Byte, m As Byte
Dim mstr As String
mstr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"
Dim outs As String
i = UBound(buff) + 1
outs = Space(2 * i)
Dim temps As String
For i = 0 To UBound(buff)
Randomize Time
j = CByte(5 * (Math.Rnd()) + 0) '最大产生的随机数只能是5,不能再大了,再大的话,就要多用一个字节
buff(i) = buff(i) Xor j
k = buff(i) Mod Len(mstr)
m = buff(i) \ Len(mstr)
m = m * 2 ^ 3 + j
temps = Mid(mstr, k + 1, 1) + Mid(mstr, m + 1, 1)
Mid(outs, 2 * i + 1, 2) = temps
Next
encode = outs
End Function

Private Function decode(ByVal s As String) As String '解密
On Error GoTo myERR
Dim i As Long
Dim j As Byte
Dim k As Byte
Dim m As Byte
Dim mstr As String
mstr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"
Dim t1 As String, t2 As String
Dim buff() As Byte
Dim n As Long
n = 0
For i = 1 To Len(s) Step 2
t1 = Mid(s, i, 1)
t2 = Mid(s, i + 1, 1)
k = InStr(1, mstr, t1) - 1
m = InStr(1, mstr, t2) - 1
j = m \ 2 ^ 3
m = m - j * 2 ^ 3
ReDim Preserve buff(n)
buff(n) = j * Len(mstr) + k
buff(n) = buff(n) Xor m
n = n + 1
Next
decode = StrConv(buff, vbUnicode)
Exit Function
myERR:
decode = ""
End Function

Post a comment


Please enter the security code you see here