package com.example.cipher.desede;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Locale;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.jupiter.api.Test;
public class DesEdeTest {
@Test
public void desEdeTest3() {
String plainText = getUuid(32);
// 如果分组模式使用CBC、CFB、OFB、CTR,则需要一个初始化向量IV
String transformation = "DESEDE/OFB/PKCS5Padding";
// desede算法的初始化向量只能是64bit(8字节)
IvParameterSpec ivParameterSpec = new IvParameterSpec(getUuid(8).getBytes(StandardCharsets.UTF_8));
encryptAndDecryptTest(plainText, transformation, ivParameterSpec);
}
@Test
public void desEdeTest2() {
String plainText = getUuid(32);
String transformation = "DESEDE/ECB/PKCS5Padding";
encryptAndDecryptTest(plainText, transformation, null);
}
@Test
public void desEdeTest1() {
String plainText = getUuid(32);
String transformation = "DESEDE";
encryptAndDecryptTest(plainText, transformation, null);
}
private void encryptAndDecryptTest(String plaintext, String transformation, IvParameterSpec ivParameterSpec) {
try {
System.out.println("plaintext = " + plaintext);
// desede算法的秘钥为192bit(24字节)
String originKey = getUuid(24);
SecretKeySpec key = new SecretKeySpec(originKey.getBytes(StandardCharsets.UTF_8), "DESEDE");
Cipher cipher = Cipher.getInstance(transformation);
if (ivParameterSpec != null) {
cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
} else {
cipher.init(Cipher.ENCRYPT_MODE, key);
}
byte[] encryptBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
String encryptStr = Base64.getEncoder().encodeToString(encryptBytes);
System.out.println("encryptStr = " + encryptStr);
if (ivParameterSpec != null) {
cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
} else {
cipher.init(Cipher.DECRYPT_MODE, key);
}
byte[] decryptBytes = cipher.doFinal(encryptBytes);
String decryptStr = new String(decryptBytes);
System.out.println("decryptStr = " + decryptStr);
System.out.println("isSuccess = " + plaintext.equalsIgnoreCase(decryptStr));
} catch (Exception e) {
e.printStackTrace();
}
}
private String getUuid(int len) {
String uuid = UUID.randomUUID().toString().toLowerCase(Locale.US).replaceAll("-", "");
return uuid.substring(0, len);
}
}
在java中使用三重DES实现加解密
最新推荐文章于 2024-10-05 07:39:03 发布