Java实现DES加密求助

VF0x01 2020-06-13 05:16:44
/**
* @ClassName AesDesDemo1
* @Description TODO
* @Date 2020/6/13 13:48
* @Version 1.0
**/
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.sun.org.apache.regexp.internal.RE;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import sun.misc.BASE64Decoder;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AesDesDemo1 {
public static void main(String[] args) throws Exception{
String input="hellowor";
String key = "12345678";
String trans = "DES/CBC/PKCS5Padding";
String algorithm="DES";
IvParameterSpec iv=getIv(key);

System.out.println("input :" + input);
String encryptDES1=AnotherDESencrypt(input,key,trans,algorithm,iv);
System.out.println("DES encode:"+encryptDES1);

System.out.println("DES decode:"+AnotherDESdecode(encryptDES1,key,trans,algorithm,iv));
}


public static String AnotherDESencrypt(String input,String key,String encryptType,String algorithm,IvParameterSpec ivParameterSpec)throws Exception{
Cipher cipher=Cipher.getInstance(encryptType);
byte[] k=key.getBytes();
SecretKey secretKey= SecretKeyFactory.getInstance(algorithm).generateSecret(new DESKeySpec(k));
cipher.init(Cipher.ENCRYPT_MODE,secretKey,ivParameterSpec);
byte[] bytes =cipher.doFinal(input.getBytes());
String encode=Base64.encode(bytes);
return encode;
}

public static IvParameterSpec getIv(String key){
byte[] keys=key.getBytes();
IvParameterSpec ivParameterSpec=new IvParameterSpec(keys);
return ivParameterSpec;
}

public static String AnotherDESdecode(String encode,String key,String encryptType,String algorithm,IvParameterSpec ivParameterSpec)throws Exception {

Cipher cipher = Cipher.getInstance(encryptType);
byte[] k = key.getBytes();
SecretKey secretKey= SecretKeyFactory.getInstance(algorithm).generateSecret(new DESKeySpec(k));
cipher.init(Cipher.DECRYPT_MODE,secretKey,ivParameterSpec);
byte[] data=encode.getBytes();
return new String(cipher.doFinal(data));
}
}
加密没有问题,解密会报Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
可是我连iv向量都是固定的值,为什么会报错?
...全文
22 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
VF0x01 2020-06-13
  • 打赏
  • 举报
回复

50,537

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧