简单的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);
}
}
本文介绍了一种使用Java实现的简单DES加密解密方法。通过具体代码示例展示了如何利用DES算法进行数据加密和解密的过程。该方法首先定义了加密算法及模式,接着创建密钥并使用Cipher类完成加密或解密操作。
1345

被折叠的 条评论
为什么被折叠?



