字符串desede 3des加密示例分享
/*字符串 desede(3des) 加密*/
import java.security.security;
import javax.crypto.cipher;
import javax.crypto.secretkey;
import javax.crypto.spec.secretkeyspec;
import sun.misc.base64decoder;
import sun.misc.base64encoder;
public class des3 {
private static final string algorithm = "desede"; //定义加密算法,可用
// des,desede,blowfish
// keybyte为加密密钥,长度为24字节
// src为被加密的数据缓冲区(源)
public static string encryptmode(byte[] keybyte, byte[] src)
{
try
{
// 生成密钥
secretkey deskey = new secretkeyspec(keybyte, algorithm);
// 加密
cipher c1 = cipher.getinstance(algorithm);
c1.init(cipher.encrypt_mode, deskey);
// 开始加密运算
byte[] encryptedbytearray = c1.dofinal(src);
// 加密运算之后 将byte[]转化为base64的string
base64encoder enc = new base64encoder();
return enc.encode(encryptedbytearray);
}
catch (java.security.nosuchalgorithmexception e1)
{
e1.printstacktrace();
}
catch (javax.crypto.nosuchpaddingexception e2)
{
e2.printstacktrace();
}
catch (java.lang.exception e3)
{
e3.printstacktrace();
}
return null;
}
// keybyte为加密密钥,长度为24字节
// src为加密后的缓冲区
public static byte[] decryptmode(byte[] keybyte, string src)
{
try {
// 生成密钥
secretkey deskey = new secretkeyspec(keybyte, algorithm);
// 解密
cipher c1 = cipher.getinstance(algorithm);
c1.init(cipher.decrypt_mode, deskey);
// 解密运算之前
base64decoder dec = new base64decoder();
byte[] encryptedbytearray = dec.decodebuffer(src);
// 解密运算 将base64的string转化为byte[]
return c1.dofinal(encryptedbytearray);
} catch (java.security.nosuchalgorithmexception e1) {
e1.printstacktrace();
} catch (javax.crypto.nosuchpaddingexception e2) {
e2.printstacktrace();
} catch (java.lang.exception e3) {
e3.printstacktrace();
}
return null;
}
// 转换成十六进制字符串
public static 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 static void main(string[] args)
{
// 添加新安全算法,如果用jce就要把它添加进去
security.addprovider(new com.sun.crypto.provider.sunjce());
final byte[] keybytes = { 0x11, 0x22, 0x4f, 0x58, (byte) 0x88, 0x10,
0x40, 0x38, 0x28, 0x25, 0x79, 0x51, (byte) 0xcb, (byte) 0xdd,
0x55, 0x66, 0x77, 0x29, 0x74, (byte) 0x98, 0x30, 0x40, 0x36,
(byte) 0xe2 }; // 24字节的密钥
string szsrc = "this is a 3des test. 测试";
system.out.println("加密前的字符串:" + szsrc);
string encoded = encryptmode(keybytes, szsrc.getbytes());
system.out.println("加密后的字符串:" + encoded);
byte[] srcbytes = decryptmode(keybytes, encoded);
system.out.println("解密后的字符串:" + (new string(srcbytes)));
}
}
上一篇: Android系统关机的全流程解析