主要内容:DES加密算法
源代码在线查看: des.java
package cs.lab.demo;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
/**
* DES加密的,文件中共有两个方法,加密、解密
* @author
* @author
*/
public class DES {
private String Algorithm = "DES";
private KeyGenerator keygen;
private SecretKey deskey;
private Cipher c;
private byte[] cipherByte;
/**
* 初始化 DES 实例
*/
public DES() {
init();
}
public void init() {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
try {
keygen = KeyGenerator.getInstance(Algorithm);
deskey = keygen.generateKey();
c = Cipher.getInstance("DES/CBC/NoPadding");
//c = Cipher.getInstance("DES/ECB/PKCS5Padding");
}
catch(NoSuchAlgorithmException ex){
ex.printStackTrace();
}
catch(NoSuchPaddingException ex){
ex.printStackTrace();
}
}
/**
* 对 String 进行加密
* @param str 要加密的数据
* @return 返回加密后的 byte 数组
*/
public byte[] createEncryptor(String str) {
try {
c.init(Cipher.ENCRYPT_MODE, deskey);
cipherByte = c.doFinal(str.getBytes());
}
catch(java.security.InvalidKeyException ex){
ex.printStackTrace();
}
catch(javax.crypto.BadPaddingException ex){
ex.printStackTrace();
}
catch(javax.crypto.IllegalBlockSizeException ex){
ex.printStackTrace();
}
return cipherByte;
}
/**
* 对 Byte 数组进行解密
* @param buff 要解密的数据
* @return 返回加密后的 String
*/
public String createDecryptor(byte[] buff) {
try {
c.init(Cipher.DECRYPT_MODE, deskey, c.getParameters() );
cipherByte = c.doFinal(buff);
}
catch(java.security.InvalidKeyException ex){
ex.printStackTrace();
}
catch(javax.crypto.BadPaddingException ex){
ex.printStackTrace();
}
catch(javax.crypto.IllegalBlockSizeException ex){
ex.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return (new String(cipherByte));
}
public static void main(String[] args) {
DES des = new DES();
try{
byte[] cipher = des.createEncryptor(args[0]);
System.out.println("Encrypted:"+new String(cipher));//将加密的byte数组以字符串方式显示
String plain = des.createDecryptor(cipher);
System.out.println("Decrypted:"+plain);
}catch(Exception e){e.printStackTrace();}
}
}