简单的DES加密解密方法
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
public class DESCodecTest
{
public static final String ALGORITHM_DES = "DES/ECB/PKCS5Padding";
public static String encode(String key,String data) throws Exception
{
return encode(key, data.getBytes());
}
public static String encode(String key,byte[] data) throws Exception
{
try
{
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
//key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(data);
return bytes == null ? null : new String(Base64.encodeBase64(bytes));
// return bytes;
} catch (Exception e){
throw new Exception(e);
}
}
public static String decode(String key,String data) throws Exception
{
return decode(key, data.getBytes());
}
public static String decode(String key,byte[] data) throws Exception
{
try
{
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
//key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte [] bytes = cipher.doFinal(Base64.decodeBase64(data));
return bytes == null ? null : new String(bytes);
//return bytes;
} catch (Exception e)
{
throw new Exception(e);
}
}
public static void main(String [] args) throws Exception{
String en = DESCodecTest.encode("20160113SS000020", "PASSWORD");
System.out.println(en);
String result = DESCodecTest.decode("20160113SS000020", en);
System.out.println(result);
}
}