Copy Code code as follows:
Import Java.security.Key;
Import Java.security.SecureRandom;
Import Java.security.spec.AlgorithmParameterSpec;
Import Javax.crypto.Cipher;
Import Javax.crypto.SecretKeyFactory;
Import Javax.crypto.spec.DESKeySpec;
Import Javax.crypto.spec.IvParameterSpec;
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
public class Des
{
public static final String algorithm_des = "des/cbc/pkcs5padding";
private static log log = Logfactory.getlog (Des.class);
/**
* des algorithm, encryption
*
* @param data to be encrypted string
* @param key Encryption private key, length can not be less than 8 bits
* @return encrypted byte array, generally combined with BASE64 encoding
* @throws Cryptexception exception
*/
public static string encode (string key,string data) throws Exception
{
Return encode (Key, data.getbytes ());
}
/**
* des algorithm, encryption
*
* @param data to be encrypted string
* @param key Encryption private key, length can not be less than 8 bits
* @return encrypted byte array, generally combined with BASE64 encoding
* @throws Cryptexception exception
*/
public static string Encode (String key,byte[] data) throws Exception
{
Try
{
Deskeyspec DKs = new Deskeyspec (Key.getbytes ());
Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");
Key cannot be less than 8 bytes in length
Key Secretkey = Keyfactory.generatesecret (DKS);
Cipher Cipher = cipher.getinstance (algorithm_des);
Ivparameterspec IV = new Ivparameterspec ("********". GetBytes ());
Algorithmparameterspec Paramspec = IV;
Cipher.init (Cipher.encrypt_mode, Secretkey,paramspec);
byte[] bytes = cipher.dofinal (data);
Return Base64.encode (bytes);
catch (Exception e)
{
throw new Exception (e);
}
}
/**
* des algorithm, decryption
*
* @param data to decrypt string
* @param key to decrypt the private key, the length can not be less than 8 bits
* @return the decrypted byte array
* @throws Exception exception
*/
public static byte[] Decode (String key,byte[] data throws Exception
{
Try
{
securerandom sr = new SecureRandom ();
Deskeyspec DKs = new Deskeyspec (Key.getbytes ());
Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");
Key cannot be less than 8 bytes in length
Key Secretkey = Keyfactory.generatesecret (DKS);
Cipher Cipher = cipher.getinstance (algorithm_des);
Ivparameterspec IV = new Ivparameterspec ("********". GetBytes ());
Algorithmparameterspec Paramspec = IV;
Cipher.init (Cipher.decrypt_mode, Secretkey,paramspec);
return cipher.dofinal (data);
catch (Exception e)
{
E.printstacktrace ();
throw new Exception (e);
}
}
/**
* Get the encoded value
* @param key
* @param data
* @return
* @throws Exception
* @throws Exception
*/
public static string Decodevalue (string key,string data) throws Exception
{
Byte[] datas;
String value = null;
Datas = Decode (key, Base64.decode (data));
Value = new String (datas);
if (Value.equals ("")) {
throw new Exception ();
}
return value;
}
}