package com.icbc.api.test;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
/**
* 描述:3des加密
*
* @author wangcheng
* @create 2019-06-13-16:20
*/
public class TDESDemo {
public static String tdes_key="cputest";
public static void main(String[] args) throws Exception {
String[] args1 = new String[1];
args1[0] = "123";
System.out.println(des_encode(args1));
String[] args2 = new String[1];
args2[0] = des_encode(args1);
System.out.println(des_decode(args2));
}
public static String des_encode(String[] args) throws Exception {
String des_key = tdes_key;
Key key = Get3DESKey(des_key.getBytes());
Cipher cipher = Cipher.getInstance("DES");
cipher.init(1, key);
return byteArr2HexStr(cipher.doFinal(args[0].getBytes()));
}
public static String des_decode( String[] args) throws Exception {
String des_key = tdes_key;
Key key = Get3DESKey(des_key.getBytes());
Cipher cipher = Cipher.getInstance("DES");
cipher.init(2, key);
return new String(cipher.doFinal(hexStr2ByteArr(args[0])));
}
private static Key Get3DESKey(byte[] key) throws Exception {
byte[] tmpKey = new byte[8];
for (int i = 0; (i < key.length) && (i < tmpKey.length); ++i) {
tmpKey[i] = key[i];
}
SecretKeySpec secretKeySpec = new SecretKeySpec(tmpKey, "DES");
return secretKeySpec;
}
public static String byteArr2HexStr(byte[] value) throws Exception {
int i = value.length;
StringBuffer buf = new StringBuffer(i * 2);
for (int j = 0; j < i; ++j) {
int k = value[j];
while (k < 0) {
k += 256;
}
if (k < 16)
buf.append("0");
buf.append(Integer.toString(k, 16));
}
return buf.toString();
}
public static byte[] hexStr2ByteArr(String value) throws Exception {
byte[] bs1 = value.getBytes();
int i = bs1.length;
byte[] bs2 = new byte[i / 2];
for (int j = 0; j < i; j += 2) {
String str = new String(bs1, j, 2);
bs2[(j / 2)] = (byte) Integer.parseInt(str, 16);
}
return bs2;
}
}
java进行DES加密
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 我们在项目中为了安全方面的考虑,通常情况下会选择一种加密方式对需要安全性的文本进行加密,而Base64加密和DES...
- 二、利用加密算法DES实现java代码加密 传统的C/C++自动带有保护机制,但java不同,只要使用反编译工具,...
- 更新:MD5加密是单向的,只能加密不能解密(破解除外)。标题可能会引起读者误解,已经改正,感谢Li_Cheng同学...
- DES RSA MD5 AES 加密Demo下载地址 百度网盘下载地址链接: http://pan.baidu.c...
- 基于“对称密钥”的加密算法主要有DES、3DES(TripleDES)、AES、RC2、RC4、RC5和Blowf...