|
我的系统是debian3.1, sun java 6的虚拟机,不知道为什么每次出来的加密后的字符串都不一样。
望好心的兄弟姐妹,帮帮忙。
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import sun.misc.BASE64Encoder;
public class Tdec {
public String byte2hex(byte[] b) // 二行制转字符串
{
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
if (n < b.length - 1)
hs = hs + ":";
}
return hs.toUpperCase();
}
public String getEnc(String s) {
String Algorithm = "DES"; // 定义 加密算法,可用 DES,DESede,Blowfish
BASE64Encoder base64en = new BASE64Encoder();
String str = null;
try {
// 生成密钥
KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
keygen.init(new SecureRandom());
SecretKey deskey = keygen.generateKey();
// 加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
byte[] cipherByte = c1.doFinal(s.getBytes());
System.out.println("加密后字节码 "+byte2hex(cipherByte));
str = base64en.encode(cipherByte);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
System.out.println("加密 : "+str);
return str;
}
/**
* @param args
*/
public static void main(String[] args) {
Tdec tdec=new Tdec();
tdec.getEnc("111111");
tdec.getEnc("111111");
tdec.getEnc("111111");
tdec.getEnc("111111");
}
}
输出结果如下:
加密后字节码 A7:7B:40:CB:15:2A:C0:3A
加密 : p3tAyxUqwDo=
加密后字节码 A4:0A:68:F3:AE:ED:72:B4
加密 : pApo867tcrQ=
加密后字节码 3C:91C:2D3:E1:84:E6
加密 : PJHcLdPhhOY=
加密后字节码 D9:64:E4:2D:C4:71:29:5E
加密 : 2WTkLcRxKV4=
:help :help :help |
|