java 3DES (DESede/ECB/PKCS5Padding) 加解密
程序员文章站
2024-03-14 11:10:40
...
代码如下:
import cn.hutool.core.convert.Convert;
import org.apache.commons.lang3.RandomStringUtils;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
public class Util {
private static final String key = RandomStringUtils.randomAlphanumeric(24);
/**
* 3DES加密
*
* @param data
* @return
* @throws Exception
*/
public static String encrypt3DES(String data) throws Exception {
//加密
byte key_byte[] = key.getBytes();
SecretKey secretKey = new SecretKeySpec(key_byte, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(data.getBytes("utf-8"));
String str = Convert.toHex(bytes);
return str;
}
/**
* 3DES解密
*
* @param data
* @return
* @throws Exception
*/
public static String decrypt3DES(String data) throws Exception {
//解密
byte key_byte[] = key.getBytes();
SecretKey secretKey = new SecretKeySpec(key_byte, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(Convert.hexToBytes(data));
String hex = Convert.toHex(bytes);
String str = Convert.hexToStr(hex, Charset.forName("utf-8"));
return str;
}
public static void main(String[] args) throws Exception {
String str = "加解密测试!";
System.out.println("随机key-----------> " + key);
String encrypt3DES = encrypt3DES(str);
System.out.println("加密-----------> " + encrypt3DES);
String decrypt3DES = decrypt3DES(encrypt3DES);
System.out.println("解密-----------> " + decrypt3DES);
}
}
运行结果:
key-----------> vSEBYEGpBjfTseGyoaiVmUA1
加密-----------> 758d54430aec8c80b1f75b223dd8cd452639f1f1c9464440
解密-----------> 加解密测试!
ps:转载请注明出处
上一篇: cmake+CMakeLists的学习
下一篇: CMake宏-根据操作系统类型添加子目录