Home > Back-end >  Java implementation DES encryption for help
Java implementation DES encryption for help

Time:09-20

/* *
* @ the ClassName AesDesDemo1
* @ Description TODO
* @ Date 2020/6/13 glorifying the
* @ Version 1.0
* */
The import javax.mail. Crypto. Cipher;
The import javax.mail. Crypto. NoSuchPaddingException;
The import javax.mail. Crypto. SecretKey;
The import javax.mail. Crypto. SecretKeyFactory;
The import javax.mail. Crypto. Spec. DESKeySpec;
The import javax.mail. Crypto. Spec. DESedeKeySpec;
The import javax.mail. Crypto. Spec. IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

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

Import the Java. Security. InvalidKeyException;
Import the Java. Security. NoSuchAlgorithmException;

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

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

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


Public static String AnotherDESencrypt (String input, String key, String encryptType, String algorithm, IvParameterSpec IvParameterSpec) throws the Exception {
Cipher Cipher=Cipher. GetInstance (encryptType);
Byte [] k=key. GetBytes ();
SecretKey SecretKey=SecretKeyFactory. GetInstance (algorithm) generateSecret (new DESKeySpec (k));
Cipher. The init (cipher ENCRYPT_MODE, secretKey, ivParameterSpec);
Byte [] bytes=cipher. DoFinal (input. GetBytes ());
The String to encode=Base64 encode (bytes);
Return the 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 the Exception {

Cipher Cipher=Cipher. GetInstance (encryptType);
Byte [] k=key. GetBytes ();
SecretKey SecretKey=SecretKeyFactory. GetInstance (algorithm) generateSecret (new DESKeySpec (k));
Cipher. The init (cipher DECRYPT_MODE, secretKey, ivParameterSpec);
Byte [] data=https://bbs.csdn.net/topics/encode.getBytes ();
Return a new String (cipher doFinal (data));
}
}
Encryption, decryption will be submitted to the Exception in the thread "is the main" javax.mail. Crypto. BadPaddingException: Given the final block not properly padded. To issues can arise if a bad key is 2 during decryption.
But I iv vector is a fixed value, why would an error?

CodePudding user response:

  • Related