Java实现DES加密求助
/**
* @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向量都是固定的值,为什么会报错?