Posted on 2011-05-13 11:46
xsong 阅读(267)
评论(0) 编辑 收藏
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
/**
* User: fengxuesong
* Date: 11-3-30
* Time: 下午4:48
* 使用 DES 加密解密
*/
public class DesTest {
static final byte[] IV = new byte[]{-29, 105, 5, 40, -94, -98, -113, -100};
static final String priKey="11111111111";
static final String data="admin11";
public static void main(String args[]) throws Exception {
//加密
String encrypt = encodeDesWithBase64(priKey,data);
//输出加密的字符串
System.out.println(encrypt );
String decrypt =decodeDesWithBase64(priKey,encrypt );
System.out.println(decrypt );
}
private static String encodeDesWithBase64(String priKey,String data) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
DESKeySpec desKS = new DESKeySpec(priKey.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES/CBC/PKCS5Padding");
cip.init(Cipher.ENCRYPT_MODE, sk, new IvParameterSpec(IV));
byte bb [] =cip.doFinal(data.getBytes());
return new BASE64Encoder().encode(bb);
}
private static String decodeDesWithBase64(String priKey,String data) throws Exception{
DESKeySpec desKS = new DESKeySpec(priKey.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES/CBC/PKCS5Padding");
cip.init(Cipher.DECRYPT_MODE, sk, new IvParameterSpec(IV));
byte bb [] =cip.doFinal(new BASE64Decoder().decodeBuffer(data));
return new String(bb);
}
}