Triple Des 加密解密 封装了byte数组和16进制字符串互相转换的操纵 使用起来更方便。
import pto.Cipher;
import pto.SecretKey;
import pto.spec.SecretKeySpec;
public class TriDES {
private static final String Algorithm = "DESede";
public static String encryptMode(byte[] keybyte, String src) {
try{
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return byte2Hex(c1.Bytes()));
}catch (Exception e) {
e.printStackTrace();
//e.getMessage();
}
return null;
}
public static String decryptMode(byte[] keybyte, String src) {
try{
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return new String(c1.doFinal(hex2Byte(src)));
}catch (Exception e) {
e.printStackTrace();
//e.getMessage();
}
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;
}
}
return hs.toUpperCase();
}
public static byte[] hex2Byte(String str) {
if (str == null)
return null;
str = im();
java数组字符串转数组 int len = str.length();
if (len == 0 || len % 2 == 1)
return null;
byte[] b = new byte[len / 2];
try {
for (int i = 0; i < str.length(); i += 2) {
b[i / 2] = (byte) Integer
.decode("0x" + str.substring(i, i + 2)).intValue();
}
return b;
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
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 };
String szSrc = "This is a 3DES test. 测试";
System.out.println("加密前的字符串:" + szSrc);
String encoded = encryptMode(keyBytes, szSrc);
System.out.println("加密后的字符串:" + encoded);
String srcBytes = decryptMode(keyBytes, encoded);
System.out.println("解密后的字符串:" + srcBytes);
srcBytes = decryptMode(keyBytes, "46872E6C5EDA9142D7C73208D2ACD0CB7183D0BA542DA373");
System.out.println("加密字符串直接解密后的字符串:" + srcBytes);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论